Randy_Johnson's avatar

Reactjs Generic Component, Inhertitance?

In Reactjs, say I have components which are quite generic in basically creating something, but I don't want to keep writing components for say, user, project etc. What is the best way to reuse components. Typically you would inherit a class but of course things are done different here.

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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.

1 like

Please or to participate in this conversation.