Skip to content

Instantly share code, notes, and snippets.

@mohandere
Last active May 12, 2019 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohandere/9cf333be708a0a0f55d0c973941db922 to your computer and use it in GitHub Desktop.
Save mohandere/9cf333be708a0a0f55d0c973941db922 to your computer and use it in GitHub Desktop.
Higher-Order Components
const withSearch = WrappedComponent => {
class WithSearch extends React.Component {
state = {
searchTerm: ""
};
handleSearch = event => {
this.setState({ searchTerm: event.target.value });
};
render() {
let { searchTerm } = this.state;
let filteredProducts = filterProducts(searchTerm);
return (
<>
<input
onChange={this.handleSearch}
value={searchTerm}
type="text"
placeholder="Search"
/>
<WrappedComponent data={filteredProducts} />
</>
);
}
};
WithSearch.displayName = `WithSearch(${getDisplayName(WrappedComponent)})`;
return WithSearch;
};
const getDisplayName = (WrappedComponent) => {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
// Render out products list with search feature
const ProductsListWithSearch = withSearch(ProductsList);
function App() {
return (
<div className="App">
<ProductsListWithSearch />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment