Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda