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

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

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 Denunciar

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 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