How to Filter Data in React JS

Filter with React JS. Simple tutorial on how to use Filter and Map to work with your Application. Learn How to Filter

Most of the time when working with React JS you will need to filter some kind of data to display what meets your needs.

JSX syntax does not introduce any new methods we can still use filter() provided by JS.

For example, you can filter an array of numbers and return those greater than 60:

function App(){
  const array = [ 23, 45, 67, 89, 12 ]
  const largerThanSixty = array.filter( number => {
    return number > 60
  })

  return (
    <ul> Number greater than 60:
      { largerThanSixty.map(number => <li>{number}</li>) }
    </ul>
  )
}

The filter() function accepts a callback function and use it to test the value of each element. It will then return an array with the elements that pass the test. If no elements pass the test, an empty array will be returned. You can then use the map() function to render the new array.

function App(){
  const array = [ 23, 45, 67, 89, 12 ]

  return (
    <ul>
      { 
        array
        .filter(number => number > 60)
        .map(number => <li>{number}</li>) 
      }
    </ul>
  )
}

Filter an Array of Objects

You can filter an array of objects by checking on the object value. For example, let’s say you have an array of tasks:

const tasks = [
  {
    taskId : 1,
    taskName : 'Clean the bathroom',
    taskStatus: 'Complete'
  },
  {
    taskId : 2,
    taskName : 'Learn filtering data in React',
    taskStatus: 'To do'
  },
  // ... the rest of the data
]
function App(){
  const tasks = [
    {
      taskId : 1,
      taskName : 'Clean the bathroom',
      taskStatus: 'Complete'
    },
    {
      taskId : 2,
      taskName : 'Learn filtering data in React',
      taskStatus: 'To do'
    },
    {
      taskId : 3,
      taskName : 'Fix the bug on React project',
      taskStatus: 'To do'
    },
    {
      taskId : 4,
      taskName : 'Fix the car',
      taskStatus: 'Complete'
    }
  ]

  return (
    <ul> To-do list:
      { 
        tasks
        .filter(task => task.taskStatus === 'To do')
        .map(task => <li key={task.taskId}>{task.taskName}</li>) 
      }
    </ul>
  )
}

Filtering in React JS is a very useful and needed way to work with data.