I have an array of things
const reportsData = [
{
name: 'Walter',
Laudos: 1,
},
{
name: 'John',
Laudos: 20,
},
]
Then on my react component, i need that when i click a checkbox, it sets a state that maked my list filter only that name. Like:
const [searchUser, setSearchUser] = useState('')
{reportsData
.filter((value: any) => {
if (searchUser == '') {
return value
} else if (
value.name
.toLowerCase()
.includes(searchUser.toLowerCase())
) {
return value
}
})
then on the checkbox
<input
type="checkbox"
checked={john} // just for example
onChange={john} // just for example
className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
/>
I need that when i press this one, it changes the searchUser value to 'John'.
Looked many responses in here but every one of them was messy asf or used this.setState instead of the useState.
How could i achieve this?
define the state this way:
const [searchUser, setSearchUser] = useState([])
then add each checkbox this way:
<input
type="checkbox"
thisUser="john" // just change this name to make checkbox for another user
defaultChecked={false}
onChange={changeSearchUser}
className="focus:ring-indigo-500 h-4 w-4 text-indigo-600 border-gray-300 rounded"
/>
add this function to your component:
function changeSearchUser(e){
if (e.target.checked) {
setSearchUser(previousSreach => [...previousSreach, e.target.thisUser])
}
else {
setSearchUser(previousSreach => {
const index = previousSreach.indexOf(e.target.thisUser)
if (index > -1) {
return previousSreach.splice(index, 1);
}
})
}
}