Created
January 8, 2024 17:37
-
-
Save torressam333/35c9991c23ac7c154f272ede5d451680 to your computer and use it in GitHub Desktop.
Higher Order Component with Configuration Example in React
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
/** | |
* This way, configuring a Higher-Order Component is essentially just the addition of another wrapping function around it. | |
* We accept custom messages for loading, no data or empty from the Wrapped Component | |
* OR, we provide default/generic fallback states if wrapped component doesn't provide them. | |
* @param {*} dataEmptyFeedback | |
* @param {*} noDataFeedback | |
* @param {*} dataEmptyFeedback | |
* @returns | |
*/ | |
const withConditionalFeedback = | |
({ loadingFeedback, noDataFeedback, dataEmptyFeedback }) => | |
(Component) => | |
(props) => { | |
if (props.isLoading) return <div>{loadingFeedback || "Loading data."}</div>; | |
if (!props.data) | |
return <div>{noDataFeedback || "No data loaded yet."}</div>; | |
if (!props.data.length) | |
return <div>{dataEmptyFeedback || "Data is empty."}</div>; | |
return <Component {...props} />; | |
}; | |
export default withConditionalFeedback; | |
// --------------------------------- Example useage of HOC --------------------------------- | |
const TodoItem = ({ item }) => { | |
return ( | |
<li> | |
{item.task} {item.completed.toString()} | |
</li> | |
); | |
}; | |
// Data can be an arr of objects coming from api/db etc... | |
const BaseTodoList = ({ data }) => { | |
return ( | |
<ul> | |
{data.map((item) => ( | |
<TodoItem key={item.id} item={item} /> | |
))} | |
</ul> | |
); | |
}; | |
// To do specific states provided in this "instantation" of the HOC + wrapped component | |
// States passed in as obj to avoid individual null checks if we want to pass in loadingFeedback but | |
// not noDataFeedback etc... | |
const TodoList = withConditionalFeedback({ | |
loadingFeedback: "Loading Todos.", | |
noDataFeedback: "No Todos loaded yet....", | |
dataEmptyFeedback: "Todos are empty, sorryy." | |
})(BaseTodoList); | |
// Call "<TodoList />" in another component |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment