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

132
Visualizações
Change color of Input field depending on if there is a match

I am trying something pretty simple i guess, but i cant seem to get it work properly. So i am using an input field to filter out an array of objects, which works medium good at the moment – (that means i am not sure if the condition is set up properly – sometimes it shows the right results, sometimes it doesnt.)

anyway i would like to change the background color depending on if there are objects matching the input or not.

Please can somebody help me fix this? This is my code:

const [searchInput, setSearchInput] = useState('');
  const [isValid, setIsValid] = useState(true)
  const style = (isValid ? 'searched' : '');


  const searchItems = (searchValue) => {
    setSearchInput(searchValue)
    if (searchInput !== '') {

        const filteredData = allData.filter((project) => {
            return Object.values(project).join('').toLowerCase().includes(searchInput.toLowerCase())
            
        })
        setFilteredResults(filteredData)
        setIsValid(true)
    }
    else{
        setFilteredResults(allData)
        setIsValid(false)

    }
}

and the input:

<label className="searchbar">
  <input  
    className={style}
    placeholder="A Visual Practice"
    onFocus={(e) => e.target.placeholder = "Search for?"} 
    onBlur={(e) => e.target.placeholder = "A Visual Practice"}
    onChange={(e) => searchItems(e.target.value)}
  />
</label>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

After setting the searchInput State, the component will be re-rendered. So what I would is the following:

  • Use the style state for checking if the input is valid or not and instead of storing a string, store a boolean (true for a valid input). I would call this state isValid and setIsValid.

  • Before the return of the component, create a constant for your styling

    const style = ${isValid ? 'searched' : ''};

Because the component will be re-rendered every time you change a state, the style constant will be changed based on the isValid state. This constant can then be used as a class for your component.

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