Glen Pinheiro Glen Pinheiro - 1 month ago 12
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.
-->
</div>

<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?

Answer

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{
  constructor(props){
    super(props)
    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)
  }
  onChange(e){
    this.setState({
      searchTerm: e.target.value //set the new serah term to the state
    })
  }
  render(){
    const items = this.state.items.map((item)=>{
      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'/>
      <div>
        {items}
      </div>
    </div>
  }
}

ReactDOM.render(<Search/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>