Search code examples
javascriptreactjscomponentscreate-react-app

React global component


I am coming from a vue.js background and I have just recently started looking into react.

I have a component: PageContent.jsx and I wish to use it without constantly having to import it to be able to use it inside the render function (JSX).

In vue it is possible to globalise a component using:

Vue.component(componentName, componentObject)

Is there anything similar in react?


Solution

  • Hmm, there isn't any kind of "global" component in React. Each component has to be imported or passed as a prop. You have a few options if you want to avoid adding an import to each file though:

    1) Create a Higher Order Component that renders the PageContent and the wrapped component.

    import PageContent from './PageContent';
    
    const withPageContent = WrappedComponent => {
      return class extends React.Component {
        render () {
          return (
            <PageContent>
              <WrappedComponent />
            </PageContent>
          )
        }
      }
    };
    
    export default withPageContent;
    
    // Usage
    
    import withPageContent from './withPageContent';
    
    class MyComponent extends React.Component {
      render () {
        return (
          <div>
            I'm wrapped in PageContent!
          </div>
        )
      }
    }
    
    export default withPageContent(MyComponent);
    

    2) Pass PageContent as a prop to a component:

    import PageContent from './PageContent';
    
    export default class App extends React.Component {
      render() {
        return (
          <React.Fragment>
            <Child1 content={PageContent} />
            <Child2 content={PageContent} />
          </React.Fragment>
        )
      }
    }
    
    // Usage
    
    export default class Child1 extends React.Component {
      render () {
        const PageContent = this.props.content;
        return (
          <PageContent>
            I'm wrapped in PageContent!
          </PageContent>
        )
      }
    }
    
    export default class Child2 extends React.Component {
      render () {
        const PageContent = this.props.content;
        return (
          <PageContent>
            I'm wrapped in PageContent!
          </PageContent>
        )
      }
    }