Glen Pinheiro Glen Pinheiro - 5 months ago 44
React JSX Question

Angular JS ng-repeat filter alternative in React JS

In Angular JS I found ng-repeat's 'filter' option which comes handly with live search. For example:

<div ng-repeat="std in stdData | filter:search">
Std Items go here.

<input type="text" placeholder="Search std items" ng-model="search.$" />

So that any items we type in the search box will be filtered. I like to know is there any alternative feature for this in React JS?


There is no out of the box solution from React.

But, you can create your own search box. See the following example.

The snippet is well addressed with comments. This should help you.

class Search extends React.Component{
    this.state = {
      items: ['car', 'mango', 'stackoverflow', 'computer'], //declare the items to be listed
      searchTerm: null //initial search term will be null
    this.onChange = this.onChange.bind(this)
      searchTerm: //set the new serah term to the state
    const items =>{
      if(!this.state.searchTerm) return <div>{item}</div> //return the items without filter when searchterm is empty
      const regEx = new RegExp(this.state.searchTerm, 'g') //create regex based on search term to filter the items 
      return regEx.test(item) && <div>{item}</div> //if the item passes the regex text, return that item
    return <div>
      <input type="text" onChange={this.onChange} placeholder='search'/>

ReactDOM.render(<Search/>, document.getElementById('app'))
<script src=""></script>
<script src=""></script>
<div id="app"></div>