Last active
May 12, 2019 14:56
-
-
Save mohandere/9cf333be708a0a0f55d0c973941db922 to your computer and use it in GitHub Desktop.
Higher-Order Components
This file contains hidden or 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
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