Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
Filtering with checkboxes with useState

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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
      }
    })
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda