Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally wrap a React component?

People also ask

How do you wrap content in React JS?

To wrap React Native text on the screen, we can set flexWrap to 'wrap' .

What is wrapper element React?

Wrapper components are components that surround unknown components and provide a default structure to display the child components. This pattern is useful for creating user interface (UI) elements that are used repeatedly throughout a design, like modals, template pages, and information tiles.

Can you conditionally add attributes to components in React?

Add attributes in React component conditionally. It is very easy in React. For certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. This is actually very useful, especially when adding many properties conditionally.

Which operator can be used to conditionally render a React component?

Logical && Operator Another way to conditionally render a React component is by using the && operator.


Just use a variable.

var component = (
    <i className={styles.Icon}>
       {this.props.count}
    </i>
);

if (this.props.link) {
    return (
        <a href={this.props.link} className={baseClasses}>
            {component}
        </a>
    );
}

return component;

or, you can use a helper function to render the contents. JSX is code like any other. If you want to reduce duplications, use functions and variables.


Create a HOC (higher-order component) for wrapping your element:

const WithLink = ({ link, className, children }) => (link ?
  <a href={link} className={className}>
    {children}
  </a>
  : children
);

return (
  <WithLink link={this.props.link} className={baseClasses}>
    <i className={styles.Icon}>
      {this.props.count}
    </i>
  </WithLink>
);

Here's an example of a helpful component I've seen used (not sure who to accredit it to) that does the job:

const ConditionalWrap = ({ condition, wrap, children }) => (
  condition ? wrap(children) : children
);

Use case:

<ConditionalWrap condition={someCondition}
  wrap={children => (<a>{children}</a>)} // Can be anything
>
  This text is passed as the children arg to the wrap prop
</ConditionalWrap>

There's another way you could use a reference variable

let Wrapper = React.Fragment //fallback in case you dont want to wrap your components

if(someCondition) {
    Wrapper = ParentComponent
}

return (
    <Wrapper parentProps={parentProps}>
        <Child></Child>
    </Wrapper>

)

const ConditionalWrapper = ({ condition, wrapper, children }) => 
  condition ? wrapper(children) : children;

The component you wanna wrap as

<ConditionalWrapper
   condition={link}
   wrapper={children => <a href={link}>{children}</a>}>
   <h2>{brand}</h2>
</ConditionalWrapper>

Maybe this article can help you more https://blog.hackages.io/conditionally-wrap-an-element-in-react-a8b9a47fab2