In my project, I have many checkboxes I'm working on and the goal is to use one onChange to keep track of checked box and store their values inside an array and remove when uncheck. But what i have done is returning an error. Can someone please tell me with what I'm doing wrong. codesandboxlink
the error i'm geeting
TypeError
selected.indexOf is not a function
OnChange
/src/App.js:11:24
8 |
9 | const OnChange = (id)=>{
10 | let selected = isselected;
> 11 | let find = selected.indexOf(id)
| ^
12 |
13 | if(find > -1){
14 | selected.splice(find, 1)
Here is my code App.js
import React from "react";
import "./styles.css";
import {useState} from 'react'
export default function App() {
const [isselected, setisselected] = useState([])
const OnChange = (id)=>{
let selected = isselected;
let find = selected.indexOf(id)
if(find > -1){
selected.splice(find, 1)
}else {
selected.push(id)
}
setisselected({selected})
console.log(isselected)
}
return (
<div className="App">
<div className="first-search">
<input
type="checkbox"
className="input-1"
value="Last 7 days"
name="last seven"
id= "1"
onChange={ (e)=> OnChange(e.target.value)}
selected={ (e)=> isselected.includes(e.target.value)}
/>
<label htmlFor="">
Last 7 days
</label>
</div>
<div className="first-search">
<input
type="checkbox"
className="input-1"
name="last24"
value="last24"
id= "2"
onChange={ (e)=> OnChange(e.target.value)}
selected={ (e)=> isselected.includes(e.target.value)}
/>
<label htmlFor="">
Last 24 hours
</label>
</div>
</div>
);
}
setisselected({selected}) if this tries to reset isselected its been declared and is const !
note: name="last seven" and name="last24" value="last24" do not look good as personal coding convention.
*It would be good if you posted the error from a debug message from the browser. e.g. firefox or chrome.