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

134
Views
how to filter list while typing with input field?

I am trying to filter my field while tying in input field as in autocomplete .I do like this but it not filter my list

here is my code

 onChangeHandler(e){
    console.log(e.target.value);
    var newArray = this.state.users.map((d)=>{
      return d.indexOf(e.target.value) !== -1 
    });
    console.log(newArray)
    this.setState({
      users:newArray
    })
  }

http://codepen.io/anon/pen/zNYGzb?editors=1010

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can do something like this:

class First extends React.Component {
  constructor(){
    super();
    this.state ={
      users: ['abc',"pdsa","eccs","koi"],
      input: '',
    }
  }

  onChangeHandler(e){
    this.setState({
      input: e.target.value,
    })
  }

  render (){
      const list = this.state.users
        .filter(d => this.state.input === '' || d.includes(this.state.input))
        .map((d, index) => <li key={index}>{d}</li>);

    return (<div>
      <input value={this.state.input} type="text" onChange={this.onChangeHandler.bind(this)}/>
        <ul>{list}</ul>
      </div>)
  }
}

ReactDOM.render(<First/>,document.getElementById('root'));

This is essentially expanding on what you had, and what you had was close. You could also choose to apply the filter within the changeHandler if you want, but I prefer to do it "later" if possible, in case you want to later add other filters or whatnot.

over 4 years ago · Santiago Trujillo Report

0

Your code is also fine, you just need to change .map to .filter method in your code and everything will work. Map method does not filter it just returns a new value for each element, which you were passing a boolean. Whereas you actually wanted to filter the list.

onChangeHandler(e){
    console.log(e.target.value);
    var newArray = this.state.users.filter((d)=>{
      return d.indexOf(e.target.value) !== -1 
    });
    console.log(newArray)
    this.setState({
      users:newArray
    })
  }

over 4 years ago · Santiago Trujillo 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!