I am making a multiple select checkbox using React.js and useRedux react hook.
For default all is checked as true value. Either one or multiple place names is checked besides of all, all should be unchekced. (true -> false).
On the other hand, when all is checked, other names should be unchecked.
Here is the code :
// Data
const PLACE_TYPE_OPTIONS = [
{ name: "all", value: "all" },
{ name: "guest_house", value: "guest_house" },
{ name: "rental_house", value: "rental_house" },
{ name: "design_pension", value: "design_pension" },
{ name: "hanok_stay", value: "hanok_stay" },
{ name: "boutique_hotel", value: "boutique_hotel" },
{ name: "stone_stay", value: "stone_stay" }
];
// Checkbox Group
<div className="tit">PLACES</div>
<ul className="check_list">
{
PLACE_TYPE_OPTIONS.map(option => (
<li>
<label className="check_skin">
<input type="checkbox" onChange={() => dispatch({ type: TYPE_STATE, payload: option.value })} checked={state.typeState[option.value]} />
<span>{option.value}</span>
</label>
</li>
))
}
</ul>
// initialState
const initialState: IFindStayState = {
typeState: {
all: true,
guest_house: false,
rental_house: false,
design_pension: false,
hanok_stay: false,
boutique_hotel: false,
stone_stay: false
}
};
// useReducer
const reducer = (state: IFindStayState, action: Action): IFindStayState => {
switch (action.type) {
case TYPE_STATE:
return {
typeState: {
...state.typeState,
[action.payload]: !state.typeState[action.payload]
}
};
default:
return state;
}
};
If I can use conditional inside return statement in reducer so I did it like below
case TYPE_STATE:
return {
typeState: {
...(state.typeState["all"] && {
all: true,
guest_house: false,
rental_house: false,
design_pension: false,
hanok_stay: false,
boutique_hotel: false,
stone_stay: false
}),
...(state.typeState[action.payload] && {
all: false,
[action.payload]: !state.typeState[action.payload]
})
}
};
Of course the code above is not going to work because all value stay the same all the time.
How can I interact all and other value? Can I make it work using conditional statement inside of reducer??
(I am trying to make it work not using input library like Formik)
Aucun commentaire:
Enregistrer un commentaire