How to Conditionally Wrap a React Component?

Sometimes, we want to conditionally wrap a React component.

In this article, we’ll look at how to conditionally wrap a React component.

Conditionally Wrap a React Component

To conditionally wrap a React component, we can create our own higher-order component.

For instance, we write:

import React from "react";

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

export default function App() {
  return (
    <>
      <p>
        <WithLink link="https://example.com" className="link">
          example
        </WithLink>
      </p>
      <p>
        <WithLink className="link">example</WithLink>
      </p>
    </>
  );
}

We create the WithLink component that takes the link, className and children props.

If link is set, then we return an a element with children as its content.

Otherwise, we return children as is.

In App, we use WithLink with and without the link prop.

If link is set, then we see a link rendered.

Otherwise, the content inside WithLink is rendered as is.

Conclusion

To conditionally wrap a React component, we can create our own higher-order component.