useEffect(() => { document.querySelector('.App').classList.toggle(theme) }, [theme])
useEffect(() => {
const el = document.querySelector('.App');
el.classList.add(theme);
return () => el.classList.remove(theme);
}, [ theme ]);
useEffect(() => {
const newArray = initialState.filter(n => checked.every(m => n[m]));
setData(newArray.length ? newArray : initialState);
}, [ checked ]);
isFlipped[index] = !isFlipped[index] setIsFlipped(isFlipped)
setIsFlipped(isFlipped.map((n, i) => i === index ? !n : n));
const Property = ({ data, onDelete }) => (
<div>
#{data.id}
<button onClick={onDelete}>Del</button>
</div>
);
const ConstructorPage = () => {
const [ properties, setProperties ] = useState([]);
const delProperty = property => setProperties(properties.filter(n => n !== property));
const addProperty = () => setProperties([
...properties,
{
id: 1 + Math.max(0, ...properties.map(n => n.id)),
},
]);
return (
<>
<button onClick={addProperty}>Add</button>
{properties.map(n => (
<Property
key={n.id}
data={n}
onDelete={() => delProperty(n)}
/>
))}
</>
);
};
setState({ ...state, show: !state.show });
. const [ text, setText ] = useState('');
const [ swiper, setSwiper ] = useState(null);
useEffect(() => {
if (swiper && text какой там вам нужен) {
swiper.slideNext();
}
}, [ swiper, text ]);
<Swiper
onSwiper={setSwiper}
...
<input
value={text}
onChange={e => setText(e.target.value)}
...
debounce(getData(), 2000);
const getData = useCallback(debounce(query => {
/*
* здесь всё по-старому, кроме body: JSON.stringify({ query: state.query }),
* надо заменить на body: JSON.stringify({ query }),
*/
}, 2000), []);
useEffect(() => {
getData(state.query);
}, [ state.query ]);
const el = useRef();
useEffect(() => {
const onClick = e => {
const dropdown = e.target.closest('.dropdown');
if (dropdown && dropdown !== el.current) {
setIsVisible(false);
}
};
document.addEventListener('click', onClick);
return () => {
document.removeEventListener('click', onClick);
};
}, []);
<div className="dropdown" ref={el}>
const defaultAnimals = {
cat: '',
dog: '',
mouse: '',
rhinoceros: '',
};
const animalsReducer = (state, action) => {
switch (action.type) {
case 'updateObj':
return {
...state,
obj: {
...state.obj,
[action.payload.name]: action.payload.value,
},
};
case 'addObjToArr':
return {
...state,
arr: [ ...state.arr, state.obj ],
obj: defaultAnimals,
};
default:
return state;
}
};
const Animals = () => {
const [ animals, dispatch ] = useReducer(animalsReducer, {
obj: defaultAnimals,
arr: [],
});
const onChange = ({ target: { name, value } }) => {
dispatch({
type: 'updateObj',
payload: { name, value },
});
};
const onSubmit = e => {
e.preventDefault();
dispatch({
type: 'addObjToArr',
});
};
return (
<div>
<form onSubmit={onSubmit}>
{Object.entries(animals.obj).map(([ k, v ]) => (
<div key={k}>
<label>
{k}:
<input name={k} value={v} onChange={onChange} />
</label>
</div>
))}
<button>Save</button>
</form>
<pre>{JSON.stringify(animals.obj, null, 2)}</pre>
<pre>{JSON.stringify(animals.arr, null, 2)}</pre>
</div>
);
};
const animalsReducer = (state, action) => {
switch (action.type) {
case 'updateObj':
return {
...state,
obj: {
...state.obj,
[action.payload.name]: action.payload.value,
},
};
case 'addObjToArr':
return {
...state,
arr: [
...state.arr,
{
animal: action.payload,
name: state.obj[action.payload],
},
],
};
default:
return state;
}
};
const Animals = () => {
const [ { obj, arr }, dispatch ] = useReducer(animalsReducer, {
obj: {
cat: '',
dog: '',
mouse: '',
rhinoceros: '',
},
arr: [],
});
const onChange = ({ target: { name, value } }) => {
dispatch({
type: 'updateObj',
payload: { name, value },
});
};
const onSubmit = (e, animal) => {
e.preventDefault();
dispatch({
type: 'addObjToArr',
payload: animal,
});
};
return (
<div>
{Object.entries(obj).map(([ k, v ]) => (
<form onSubmit={e => onSubmit(e, k)} key={k}>
{k}:
<input name={k} value={v} onChange={onChange} />
<button>Save</button>
</form>
))}
<pre>{JSON.stringify(obj, null, 2)}</pre>
<pre>{JSON.stringify(arr, null, 2)}</pre>
</div>
);
};
const [ coord, setCoord ] = useState(...);
function onActionTickComplete(e) {
const projection = e.get('target').options.get('projection');
const { globalPixelCenter, zoom } = e.get('tick');
setCoord(projection.fromGlobalPixels(globalPixelCenter, zoom));
}
<Map
onActionTickComplete={onActionTickComplete}
...
>
<Placemark geometry={coord} />
</Map>
const toggleSearchParams = params => {
const newSearchParams = [...searchParams];
for (const n of params) {
const index = newSearchParams.findIndex(m => n[0] === m[0] && n[1] === m[1]);
if (index === -1) {
newSearchParams.push(n);
} else {
newSearchParams.splice(index, 1);
}
}
setSearchParams(newSearchParams);
};
const handleChangeCheckBoxValue = e => {
toggleSearchParams([ [ 'selected', e.target.value ] ]);
};
const handleDeleteParams = () => {
toggleSearchParams(checkboxParams.map(n => [ 'selected', n ]));
};
как вернуть к первоначальному состоянию когда unchecked не понимаю
function Posts() {
const [ posts, setPosts ] = useState([]);
const [ filteredPosts, setFilteredPosts ] = useState([]);
const [ search, setSearch ] = useState('');
const [ checkbox, setCheckbox ] = useState(false);
useEffect(() => {
axios
.get('https://jsonplaceholder.typicode.com/posts')
.then(r => setPosts(r.data));
}, []);
useEffect(() => {
let filtered = posts;
if (search) {
const s = search.toLowerCase();
filtered = filtered.filter(n => n.title.toLowerCase().includes(s));
}
if (checkbox) {
filtered = filtered.filter(n => n.userId === 10);
}
setFilteredPosts(filtered);
}, [ posts, search, checkbox ]);
return (
<>
<input
type="text"
placeholder="Search for article..."
value={search}
onChange={e => setSearch(e.target.value)}
/>
<label>
User Id 10
<input
type="checkbox"
checked={checkbox}
onChange={e => setCheckbox(e.target.checked)}
/>
</label>
<ul>
{filteredPosts.map(n => (
<li key={n.id}>
<div>{n.userId}</div>
<div>{n.title}</div>
<div>{n.body}</div>
</li>
))}
</ul>
</>
);
}
{items.map(n => <div className="item">...</div>)}
.item:nth-child(6n + 3),
.item:nth-child(6n + 4) {
...
}
<button onClick={() => setModal('раз окно')}>1</button>
<button onClick={() => setModal('два окно')}>2</button>
<button onClick={() => setModal('три окно')}>3</button>
...
<Modal display={modal === 'раз окно'}>...</Modal>
<Modal display={modal === 'два окно'}>...</Modal>
<Modal display={modal === 'три окно'}>...</Modal>
Подскажите самые простые учебники / статьи / видео курсы по React, где нормальным языком доступно объясняется.
На офф сайте читал и мануалы и практическое руководство, тяжело очень дается и порой не понтно что к чему и зачем.
фразы оттуда навроде "Подъём состояния в родительский компонент — обычное дело при рефакторинге React-компонентов." лишь отпугивают новичков вроде меня
C javascript знаком на базовом уровне
fetch('https://jsonplaceholder.typicode.com/todos/1')
1
.const [data, setData] = useState(null);
{data.map(item => (
null
метод map
? - погуглите, разберитесь. Ну и замените null
на []
.