function Pokemon({ name, url }) {
const [ data, setData ] = useState(null);
useEffect(() => {
fetch(url).then(r => r.json()).then(setData);
}, [ url ]);
return (
<div>
<h4>{name}</h4>
{data
? <div>
<ul>{data.abilities.map(n => <li>{n.ability.name}</li>)}</ul>
<img src={data.sprites.front_default} />
</div>
: <div>loading...</div>
}
</div>
);
}
const Filter = ({ title, values, value, onChange }) => (
<div>
<h3>{title}</h3>
{values.map(n => (
<label>
<input
type="radio"
onChange={() => onChange(n)}
checked={value === n}
/>
{n}
</label>
))}
</div>
);
state = {
...
filteredProducts: [],
status: 'all',
}
onFilterStatusChange = status => {
this.setState({ status });
}
filterProducts() {
this.setState(({ status }) => ({
filteredProducts: status === 'all'
? this.state.products
: this.state.products.filter(n => n.prod_status.includes(status)),
}));
}
componentDidUpdate(prevProps, prevState) {
if (this.state.status !== prevState.status) {
this.filterProducts();
}
}
render() {
...
<Filter
title="Status:"
values={[ 'all', 'recommended', 'saleout', 'bestseller', 'new' ]}
value={this.state.status}
onChange={this.onFilterStatusChange}
/>
<Products products={this.state.filteredProducts} />
...
}
<div className="status">{status}</div>
пусть будет{status.split(',').map(n => <div className="status">{n}</div>)}
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) {
...
}