Filtering Data in ReactJS - Kevin Uriel Fonseca


I’m currently fetching data from my db but for the simplicity of this Q, I have decided to manually create an example with fake data.

I’m building a search-bar for my users to look through all of the data coming from db and everything seems to be working fine when looking for a specific document, however, I want to reset the state to its original data when the input is empty.

const objects = [
  {
    _id: 0,
    title: 'Title One',
  },
  {
    _id: 1,
    title: 'Title Two',
  },
  {
    _id: 2,
    title: 'Title Three',
  },
]
const [keyword, setKeyword] = useState('')
const [list, setList] = useState([])
useEffect(() => {
  setList(objects)
}, [objects])
useEffect(() => {
  if (keyword !== '') {
    const result = objects.filter((object) => {
      return object.title.toLowerCase().startsWith(keyword.toLowerCase())
    })
    setList(result)
  } else {
    setList(objects)
  }
}, [keyword])
const handleChange = () => (e) => {
  e.preventDefault()
  setKeyword(e.target.value)
}
/*
 *
 * INPUT
 *
 */
;<input
  type="text"
  placeholder="Search..."
  name="keyword"
  id="keyword"
  onChange={handleChange('keyword')}
  value={keyword}
  className="form-control mb-3"
/>
/*
 *
 * HTML
 *
 */
return list?.length > 0 ? (
  <ul>
    {list.map((data, index) => (
      <li key={data._id}>{data.title}</li>
    ))}
  </ul>
) : (
  <p>Nothing found</p>
)

You can see the example in action by clicking here.

Bye Bye 🙂

SIDEBAR
FOOTER