Reputation: 355
I Have an Search Field Input , Through that Input I need to filter the data. So, How Can I Filter the data using Search Field.. Can Anyone help me in this..
class App extends Component {
constructor() {
super ();
this.state = {
monsters : [],
searchFeild :'',
};
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => this.setState({monsters : users}))
}
inputData =(event)=>{
console.log(event.target.value);
this.setState({searchFeild : event.target.value});
}
render() {
return (
<div className="App">
<input type ="text" placeholder ="Typeo" onChange={this.inputData}/>
<CardList monsters ={this.state.monsters}/>
</div>
);
}
}
export default App;
Upvotes: 0
Views: 119
Reputation: 15698
The complexity of your search is all up to you and how your monsters data-set looks. Let's say your array of monsters looks something like this:
monsters = [{name: "Pikachu"}, {name: "Meowth"}, {name: "Charmander"}]
You could do a very simple search to check whether the string
you enter in the input is included in the name
of the monster. It would be as simple as using array.protoype.filter()
and string.prototype.includes()
or string.prototype.contains()
Enhance your change-handler to:
inputData = (event) => {
const { value } = event.target
const { monsters } = this.state
const filteredMonsters = monsters.filter((monster) => {
return monster.name.includes(value)
})
this.setState({
monsters: filteredMonsters
})
}
But again, this is a very primitive search, you could enhance it by accounting for letter-casing, spaces, Regex and etc.
Upvotes: 0
Reputation: 169
use the filter function on the monsters
monsters.filter(m => !searchfield || m.name.contains(searchfield))
also your input is missing value. Check here for more info https://reactjs.org/docs/forms.html#controlled-components
Upvotes: 1