how to conditionally load a wrapping component in react in javascript

You can conditionally load a wrapping component in React by using a Higher Order Component (HOC) that accepts a component as a parameter and returns a new component that wraps it with additional functionality.

Here's an example of an HOC that conditionally renders a wrapping component based on a boolean prop called "condition":

import React from 'react';

const withWrapper = (WrappedComponent, WrapperComponent) => {
  return (props) => {
    const { condition, ...rest } = props;
    
    if(condition) {
      return <WrapperComponent><WrappedComponent {...rest} /></WrapperComponent>;
    }
    
    return <WrappedComponent {...rest} />;
  };
};

export default withWrapper;
352 chars
16 lines

In this example, the withWrapper HOC takes in two parameters: the WrappedComponent that we want to render conditionally and the WrapperComponent that we want to use as the wrapper. The HOC returns a new component that renders the WrappedComponent wrapped in the WrapperComponent only if the condition prop is true.

To use this HOC, you can simply pass in your component and conditional prop like this:

import withWrapper from './withWrapper';

const MyComponent = (props) => {
  const { text } = props;
  return <p>{text}</p>;
};

const MyWrapper = (props) => {
  const { children } = props;
  return <div className="wrapper">{children}</div>;
};

const WrappedComponentWithWrapper = withWrapper(MyComponent, MyWrapper);

const App = () => {
  return (
    <div>
      <h1>Conditional Rendering Example</h1>
      <WrappedComponentWithWrapper text="This will be wrapped" condition={true} />
      <MyComponent text="This will not be wrapped" />
    </div>
  );
};

export default App;
583 chars
26 lines

In this example, we defined our MyComponent and MyWrapper components, and then wrapped our MyComponent with the MyWrapper by using the withWrapper HOC. We can pass condition={true} to tell the HOC to wrap the component, or omit the prop to render the MyComponent component without wrapping it.

gistlibby LogSnag