Conditionally render a div

16 February 23

In certain circumstances you would like to render a div but only when a certain condition is true. Here’s one approach on how to do that in React:

ConditionalWrapper.tsx

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

The code is simple: if the condition is true, render the wrapper and pass the children as the argument. When condition is false, just return the children.

It can be used like this:

Example.tsx

export const Example = () => (
	<ConditionalWrapper
		condition={isDoormat}
		wrapper={children => <div className="foo">{children}</div>}
	>
		<a href="#foo">Foo</a>
	</ConditionalWrapper>
);