vendredi 4 septembre 2020

How to checkbox filtering in reactjs and handle state? and show the available item after the checkbox

I want to make a filter system using multiple checkbox. But when i checked one checkbox it filter the state but when i unchecked it how i can get back the all data in state . Also if i select multiple checkbox then it will filter from the filtered item.

Here is my code.

state = {
  restaurant : [
     {name: 'La mesa', cuisine: ['italian', 'indian']},
     {name: 'Red Bull', cuisine: ['chiness', 'french']}
     {name: 'Purnima', cuisine: ['thai', 'arabic']}
  ]
  cuisine: [
    {id: 1, name: 'italian'},
    {id: 2, name: 'indian'},
    {id: 3, name: 'chiness'}
    {id: 4, name: 'french'},
    {id: 4, name: 'arabic'},
 ]
}

handleCuisineFilter = (e) => {
        if (e.target.checked) {
            const filter =
                this.state.restaurants.length &&
                this.state.restaurants.filter((rest) => rest.cuisine.includes(e.target.value));
            this.setState({ restaurants: filter });
        } else {
            Now when unchecked how i can get previous state???
        }
    };

render() {
  return (
<div>
   {this.state.cuisine.length && this.state.cuisine.map(
     cuisine=> (<li>
                   <input
                    id={cuisine.id}
                    type='checkbox'
                    onChange={this.handleCuisineFilter}
                    name='check'
                    value={cuisine.name}
                    />
              {cuisine.name }  {here will be count of number of restaurant}
               </li>
            ))}
     {this.state.restaurant.length && this.state.restaurant.map(rest=> <h5>rest.name</h5>)}
 </div>

I tried to explain best via my code . Help me please. Thank you in advance




Aucun commentaire:

Enregistrer un commentaire