Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!