One way to reuse components in React is to create a higher-order component (HOC) that takes in a component as a parameter and returns a new component with additional functionality.
Here's an example of a HOC that adds a "loading" state to any component:
const withLoading = (WrappedComponent) => {
return class extends React.Component {
state = {
isLoading: true
}
componentDidMount() {
// simulate loading data
setTimeout(() => {
this.setState({ isLoading: false })
}, 2000)
}
render() {
if (this.state.isLoading) {
return <div>Loading...</div>
}
return <WrappedComponent {...this.props} />
}
}
}
To use this HOC, simply pass in your component as an argument:
const MyComponent = () => {
return <div>Hello World</div>
}
const MyComponentWithLoading = withLoading(MyComponent)
Now MyComponentWithLoading has the additional "loading" state and can be used just like any other component.
You can create other HOCs to add other functionality to your components, such as authentication, data fetching, or styling. By using HOCs, you can create reusable components that can be easily customized and extended.