---
# System prepended metadata

title: react fruit filter
tags: [lessons]

---

# react fruit filter

# links

gitbook [notes](https://gasei.gitbook.io/sei/16-react/mood-points/lifting-state)

# code along

```javascript=
// Fruitcontainer.jsx
import { Component } from 'react'
import List from './List'
import Input from './Input' 

const fruits = ['mango', 'banana', 'kiwi', 'berry']

export default class FruitComponent extends Component {
  // I am the parent of both list and input
  state = {
    // initialize the fruit list to the full list passed in props
    fruitsToDisplay: fruits,
    // intialize the filter value to an empty string
    filterValue: '',
    // keep track of everything filtered out
    fruitsFiltered: []
  }
  handleFilterChange = (e) => {
    e.preventDefault()
    const filterValue = e.target.value
    // remove fruits that don't contain the filter value
    const filteredFruitList = fruits.filter(fruit => {
      return fruit.toLowerCase().includes(filterValue.toLowerCase())
    })
    // filter the reverse -- find everything that doesnt match
    const removedFruitsList = fruits.filter(fruit => {
      return !fruit.toLowerCase().includes(filterValue.toLowerCase())
    })
    this.setState({
        fruitsToDisplay: filteredFruitList,
        filterValue,
        fruitsFiltered: removedFruitsList
    })
  }

  render() {

    return (
      <>
        <Input 
          handleFilterChange={this.handleFilterChange} 
          value={this.state.filterValue} 
        />
        
        <List  
          fruits={this.state.fruitsToDisplay} 
          removed={this.state.fruitsFiltered} 
        />
      </>
    )
  }
}
```

```javascript=
// List.jsx
import { Component } from 'react'

export default class List extends Component {
  render() {
    const fruitItems = this.props.fruits.map((fruit, idx)=>{
      return <li key={`fruit-${idx}`}>{fruit}</li>
    })
    const removed = this.props.removed.map((fruit, idx)=>{
      return <li key={`removed-${idx}`}>{fruit}</li>
    })
    return (
      <>
        <h3>frutis that match</h3>
        <ul>
            {fruitItems}
        </ul>

        <h3>frutis that where removed</h3>
        <ul>
            {removed}
        </ul>
      </>
    )
  }
}
```

```javascript=
import { Component } from 'react'

export default class Input extends Component {
  render() {
    return (
      <div>
        <label htmlFor="fruit-filter">Filter these Fruits: </label>
        <input 
          type="text" 
          value={this.props.value} 
          onChange={this.props.handleFilterChange} 
          id="fruit-filter" 
        />
      </div>
    )
  }
}
```

###### tags: `lessons`