DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Conditional Wrap in React
Henrique Ramos
Henrique Ramos

Posted 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:

<Wrap if 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.

Latest comments (0)

🌱 DEV runs on 100% open source code that we started called Forem.

You can contribute to the codebase or host your own.