DEV Community

Cover image for Conditional Wrap in React
Henrique Ramos
Henrique Ramos

Posted on Edited on

Conditional Wrap in React

If you ever played around with React, you probably found a situation where you'd need to conditionally wrap a component. If it matches some condition, it should be rendered inside a given tag, if not, leave it as is. Here's a small snippet for that:

import { FC, ReactNode, createElement } from 'react';

interface WrapProps {
    if?: boolean;
    with: typeof createElement.arguments[0];
    wrapperProps: typeof createElement.arguments[1];
    children: NonNullable<ReactNode>;
}

const Wrap: FC<WrapProps> = ({
    if: condition,
    with: wrapper,
    wrapperProps,
    children,
}) =>
    condition ? createElement(wrapper, wrapperProps, [children]) : <>{children}</>;

export default Wrap;
Enter fullscreen mode Exit fullscreen mode

Usage:

const condition = useMemo(() => index % 2 === 0, [index]);

<Wrap if={condition} with="a" wrapperProps={{ 'data-testid': 'wrapper' }}>
    <p>Wrapped text</p>
</Wrap>
Enter fullscreen mode Exit fullscreen mode

This component uses React.createElement because it allows dynamic component creation. It means that, instead of providing a function like (children) => <p>{children}</p> for Wrap, it is possible to pass a React Component instance or a HTML node name.

Top comments (0)