0

I have class Comopnent :

 state = { names: ['first', 'second'] }; updateSearch = (event) => { let updatedList = this.state.names; updatedList = updatedList.filter(name=> { return name.toLowerCase().search( event.target.value.toLowerCase()) !== -1; }) this.setState({names: updatedList}); } render() { const names = this.state.names.map((name) => { return ( <div key={name}> <span>{name}</span> </div> )}) return ( <div> <input placeholder="Search" type="text" onChange={this.updateSearch} /> {names} </div> ) } 

When I type some text that agrees with the name, search is working, and only that name is showing, but when i remove text from input all names should show back, but they don't (only the previously searched name is displayed). Why?

Thanks for answers in advance!

2
  • Because after removing the name you are not setting up the state to initial one. this line " this.setState({names: updatedList});" update the state . Commented Dec 5, 2018 at 14:36
  • @ashishsherawat So how to do that? Commented Dec 5, 2018 at 15:12

1 Answer 1

1
 Add one more val in state as initialName and in updateSearch set updateSearch value with initalNames. Try This. state = { names: ['first', 'second'], intiailNames:['first','second'] }; updateSearch = (event) => { let updatedList = this.state.intiailNames; updatedList = updatedList.filter(name=> { return name.toLowerCase().search( event.target.value.toLowerCase()) !== -1; }) this.setState({names: updatedList}); } 
Sign up to request clarification or add additional context in comments.

1 Comment

ok, I discovered myself how to do it well, but anyway thanks for help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.