I want to be able to add my different input refs together which represent genres of movies. It seems I can only add one genre and remove it in the array, like if I click both checkboxes I should have [‘Action’, ‘Sci Fi’] instead of just [‘Action’] and then after [‘Sci Fi’].
const [isCheckedA, setIsCheckedA] = useState(true);
const [isCheckedS, setIsCheckedS] = useState(true);
var actionInput = useRef();
var sciFiInput = useRef();
//my array
let genres = [];
const handleCheckedAct = ({ target }) => {
if (isCheckedA) {
actionInput = target.name
console.log(actionInput);
genres.push(actionInput);
console.log(genres)
setIsCheckedA(!isCheckedA);
} else {
genres.pop(actionInput);
console.log("else is being checked");
console.log(genres);
setIsCheckedA(!isCheckedA)
}
};
const handleCheckedSciFi = ({ target }) => {
if (isCheckedS) {
sciFiInput = target.name
console.log(sciFiInput);
genres.push(sciFiInput);
console.log(genres);
setIsCheckedS(!isCheckedS);
} else {
genres.pop(sciFiInput);
console.log("else is being checked");
console.log(genres);
setIsCheckedS(!isCheckedS);
}
};
I’m assuming this is React and this is a form. Without being able to see the JSX as well (well, the whole component function) it’s very difficult to advise.
But in general, either use controlled inputs (ie all values derived from useState or similar) or use refs. I’m not sure why you’re mixing the two here.
Secondly, HTML already does this for you, and often that’s enough, cf:
function Example() {
const submitHandler = (e) => {
// Important, otherwise the page will reload
e.preventDefault();
// Then populate a FormData object with the
// data input into the form
const data = new FormData(e.target);
// Just logging, but you can store in state or
// whatever you want to do with the data
for (const entry of data.entries()) {
console.log(entry);
}
}
return (
<form onSubmit={submitHandler}>
{/* Form inputs go here */}
<button type="submit">Submit</submit>
</form>
);
}
The useState is for counting if the box is checked or not. If I could use one useState variable, I would. I will provide the jsx too. I have 8 genres and I need to add them if checked and subtract them if not checked to the array.