I've got a Form that allows multiple check boxes. When a user clicks the checkbox, it is supposed to add the value to an array of objects and when the user unclicks the value is to be removed from the array but this doesn't work unless the value is the last added in the array. When I log the index it only shows 0 on the console regardless of the array size. Pls I need help with this issue I've been stuck for the past 2 days.
The code:
import React, { useState, useEffect } from 'react';
import { Dialog, DialogTitle, DialogContent, makeStyles, ListItemSecondaryAction } from '@material-ui/core';
import { Button, ButtonToolbar } from 'react-bootstrap';
import Grid from '@material-ui/core/Grid';
import * as FaIcons from 'react-icons/fa';
import './FilterPopup.css'
import { filterData } from './filterData';
import { genresData } from './genresData'
export default function Filter(props) {
const { title, children, openPopup, setOpenPopup, genres, setGenres } = props;
const [filtergenres, setFilterGenres] = useState([]);
var index;
function verify(elem) {
for (let m = 0; m < filtergenres.length; m++) {
console.log(m);
var obj = filtergenres[m];
console.log(obj);
if (obj.id === elem) {
index = m;
return true;
} else {
return false;
}
}
}
function changeValue(elem) {
console.log(elem);
let newlist = filtergenres;
if (verify(elem)) {
console.log(index);
newlist.splice(index, 1);
setFilterGenres(newlist);
console.log(newlist);
console.log(filtergenres);
} else {
newlist.unshift({
id: elem,
value: elem
});
setFilterGenres(newlist);
console.log(newlist);
console.log(filtergenres);
}
}
return (
<Dialog open={openPopup} className='filterDialog' maxWidth="md">
<DialogTitle>
<div className='popupTitle'> Filter </div>
<Button className='popupCloseBtn' onClick={() => { setOpenPopup(false) }}>
<FaIcons.FaTimes />
</Button>
</DialogTitle>
<DialogContent dividers>
<form className='pop-up-forms'>
<label className='popuppart'>
Sort By:
<select className='filter-sort'>
{filterData.map((item, index) => {
return (
<option key={index} value={item.value}>{item.title}</option>
)
})}
</select>
<Button className='popupSearchSubmitBtn' onClick={() => { }}>
submit
</Button>
</label>
<label className='popuppart'>
Include Adult:
<input
className='filterchkbox'
name="isAdult"
type="checkbox" />
</label>
<label className='filterGenres'>
Genres:
<Grid container spacing={1} direction="row" justify="center" alignItems="center">
{genresData.map((item, index) => {
return (
<Grid item key={index}>
<label className='genresLabel'>
{item.name}
<input
className='filterchkbox'
name="isAdult"
type="checkbox"
value={item.id}
onClick={() => { changeValue(item.id) }} />
</label>
</Grid>
)
})}
</Grid>
</label>
</form>
</DialogContent>
</Dialog >
)
}