Created
March 4, 2016 08:36
-
-
Save monty5811/b1a13cd695cd8ec80e59 to your computer and use it in GitHub Desktop.
React Higher Order Component to filter an array of objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
function obj2str(obj) { | |
if (obj === null) { | |
return ''; | |
} | |
const vals = Object.keys(obj).map( | |
key => { | |
let val = obj[key]; | |
if (typeof(val) === 'object') { | |
val = obj2str(val); | |
} | |
return val; | |
} | |
); | |
return vals.join(); | |
} | |
export const FilteringComponent = ComposedComponent => class extends Component { | |
constructor() { | |
super(); | |
this._onChange = this._onChange.bind(this); | |
this.state = { filterRegex: new RegExp('', 'img') }; | |
} | |
_onChange(e) { | |
this.setState({ filterRegex: new RegExp(e.target.value, 'img') }); | |
} | |
render() { | |
let filteredData = this.props.data; | |
filteredData = filteredData.filter( | |
(el) => { | |
const valsStr = obj2str(el); | |
return valsStr.search(this.state.filterRegex) > -1; | |
} | |
); | |
return ( | |
<div> | |
<div className="ui left icon large transparent fluid input"> | |
<input type="text" placeholder="Filter..." onChange={this._onChange} /> | |
<i className="violet filter icon"></i> | |
</div> | |
<ComposedComponent | |
{...this.props} | |
data={filteredData} | |
/> | |
</div> | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment