Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.