I'm checking a string that is delimited with pipes to populate checkboxes. I'm using the includes() to achieve this. But the problem is when two items are similar in names, they are both true because they both include the same string, event though they are different.
For example, in the string language: "English|Non-English"
, and this state
const [state, setState] = useState({
language: "English|Non-English",
})
mapping the
{language.map((item) => {
const checkboxvalues = state.language
return (
<Grid key={item} item sm={4} md={3}>
<FormControlLabel
className={classes.switchcontrol}
control={
<Checkbox
size="small"
name={item}
value={item}
checked={checkboxvalues.includes(item)}
onChange={handleOnChange}
/>
}
label={item}
/>
</Grid>
);
})}
checked={checkboxvalues.includes(item)} //This makes English true for both
How can I make it so that it treats English and Non-English independently. Also, I have a similar case with "Name|First Name", so it's not just a dash, white space too
Thanks
CodePudding user response:
You should split
checkboxvalues
, ideally outside the map
call to avoid doing it for each checkbox:
const checkboxvalues = state.language.split('|')
The rest of your code doesn't need to be changed because includes
also exists on arrays:
checkboxvalues.includes(item)