156

I have a component that will sometimes need to be rendered as an <anchor> and other times as a <div>. The prop I read to determine this, is this.props.url.

If it exists, I need to render the component wrapped in an <a href={this.props.url}>. Otherwise it just gets rendered as a <div/>.

Possible?

This is what I'm doing right now, but feel it could be simplified:

if (this.props.link) {
    return (
        <a href={this.props.link}>
            <i>
                {this.props.count}
            </i>
        </a>
    );
}

return (
    <i className={styles.Icon}>
        {this.props.count}
    </i>
);
3
  • You can also move const baseClasses = into that if (this.props.link) branch. As you are using ES6, so you can also simplify a bit by const {link, className} = this.props; and then using link and className as local variables.
    – Sulthan
    Commented Nov 14, 2015 at 17:36
  • Man, I love it. Learning more and more about ES6 and it always just improves readability. Thanks for the extra tip! Commented Nov 14, 2015 at 17:47
  • 2
    What's a "final lockup"? Commented Jan 14, 2019 at 14:13

12 Answers 12

151

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.

5
  • This code will unmount component and recreate it on next render. You can add key="theSameKey" but this will change nothing. React.useMemo cannot cache you component and it will be unmounted. medium.com/@cowi4030/…
    – sytolk
    Commented Sep 21, 2021 at 10:01
  • @sytolk Not really. That will happen only if your hierarchy changes. And that's only to be expected. The article you mention calls it an antipattern which it is not. And that article is also blatantly wrong about react DOM diffing.
    – Sulthan
    Commented Sep 21, 2021 at 11:08
  • yes this is anti pattern - look at JSX <component> exist twice and if you change props.link on next render React will unmount component. For this case its acceptable but what about if component is a heavy?
    – sytolk
    Commented Sep 21, 2021 at 15:39
  • 1
    @sytolk Wrapping or not wrapping by link means you have to change hierarchy and there is no way around it. It's something you have to think about when designing your hierarchy but that does not mean it's an antipattern. I would argue that in many cases it's actually the only viable option.
    – Sulthan
    Commented Sep 21, 2021 at 16:10
  • 1
    @sytolk the article you mentioned is talking about conditional rendering of children but here we are talking about the wrapper/parent. these are two different things.
    – Mustkeem K
    Commented Feb 22, 2022 at 5:41
51

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>
);
2
  • 13
    HOC should die slowly :P Commented Oct 18, 2019 at 10:59
  • 9
    This is not an HOC. From the React Docs: "Concretely, a higher-order component is a function that takes a component and returns a new component." Here, WithLink is simply a component. This example makes it seem as if it is being declared within another component which is almost always a bad idea since it will be recreated on every render, meaning children will be constantly remounted. Commented Jul 13, 2021 at 22:57
50

Here's an example of a helpful component I've seen used before (not sure who to accredit it to). It's arguably more declarative:

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

Use case:

// MaybeModal will render its children within a modal (or not)
// depending on whether "isModal" is truthy
const MaybeModal = ({ children, isModal }) => {
  return (
    <ConditionalWrap
      condition={isModal}
      wrap={(wrappedChildren) => <Modal>{wrappedChildren}</Modal>}
    >
        {children}
    </ConditionalWrap>
  );
}
11
  • 8
    Credit should likely go here: gist.github.com/kitze/23d82bb9eb0baabfd03a6a720b1d637f
    – Roy Prins
    Commented Nov 19, 2019 at 16:05
  • I saw that from kitze. But I wasn't sure he got the idea from someone else
    – antony
    Commented Nov 20, 2019 at 14:40
  • Neither am I. This was the first result that popped up and I assumed it to be the source - or at least closer to it ;).
    – Roy Prins
    Commented Nov 22, 2019 at 21:46
  • You should use the wrap declaratively and not as a function to keep things more "React"-spirit
    – vsync
    Commented Jul 1, 2020 at 10:32
  • How would you make it more declarative @vsync? I thought render props were within the spirit of React?
    – antony
    Commented Jul 1, 2020 at 12:12
26

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>

)
5
  • 4
    You can condense the first half to let Wrapper = someCondition ? ParentComponent : React.Fragment
    – mpoisot
    Commented Apr 10, 2020 at 22:09
  • This is awesome, but sometimes you want to keep the code declarative, meaning it returns only JSX
    – vsync
    Commented Jul 1, 2020 at 11:54
  • 1
    I get an error React.Fragment can only have 'key' and 'children' because I pass some props to "<Wrapper>" like "className" and so
    – vsync
    Commented Jul 1, 2020 at 14:28
  • @vsync you need to add a condition for props as well something like propId={someCondition? parentProps: undefined} ..
    – Avinash
    Commented Jul 1, 2020 at 16:33
  • 1
    I know :) I was writing this for the sake of documentation for others who come here with this issue, so Google will cache this page in its search results for those keywords
    – vsync
    Commented Jul 1, 2020 at 16:46
8
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

0

You should use a JSX if-else as described here. Something like this should work.

App = React.creatClass({
    render() {
        var myComponent;
        if(typeof(this.props.url) != 'undefined') {
            myComponent = <myLink url=this.props.url>;
        }
        else {
            myComponent = <myDiv>;
        }
        return (
            <div>
                {myComponent}
            </div>
        )
    }
});
0

You could also use a util function like this:

const wrapIf = (conditions, content, wrapper) => conditions
        ? React.cloneElement(wrapper, {}, content)
        : content;
0

Using react and Typescript

let Wrapper = ({ children }: { children: ReactNode }) => <>{children} </>

if (this.props.link) {
    Wrapper = ({ children }: { children: ReactNode }) => <Link to={this.props.link}>{children} </Link>
}

return (
    <Wrapper>
        <i>
            {this.props.count}
        </i>
    </Wrapper>
)

0

I'm personally using this kind of code (ComponentChildren is Preact, you should be able to use ReactNode for React):

const Parent = ({ children }: { children: ComponentChildren }) => props.link != null ?
        <a href={ props.link }>{ children }</a> :
        <>{ children }</>

return (
    <Parent>
        <i className={ styles.Icon }>
            { props.count }
        </i>
    </Parent>
)
0

This is old, but the answers here will be buggy in 90% of cases because when the parent re-renders the child components will be unmounted / remounted. Heres a component you can use instead:


type ConditionallyWrapProps<T extends React.FC<any>> = {
  condition: boolean | undefined;
  children: ReactNode;
  Wrapper: T;
} & Omit<React.ComponentProps<T>, "condition" | "Wrapper">;

export const ConditionallyWrapV2 = <T extends React.FC<any>>({
  condition,
  children,
  Wrapper,
  ...wrapperProps
}: ConditionallyWrapProps<T>) => {
  return (
    <>
      {condition ? (
        <Wrapper {...(wrapperProps as any)}>{children}</Wrapper>
      ) : (
        children
      )}
    </>
  );
};


4
  • You're wrong, and may want to delete your misleading comments. It's different in that it allows you to pass the props through the Wrapper component, which means that you don't need to define the Component inline, which will cause it to be blown away whenever the parent re-renders. If you can't understand the name ConditionallyWrapV2, then that's on you.
    – Sid
    Commented Jun 10 at 15:12
  • It's not "on me". people copy-paste codes into large codebases where many co-author. meaningful naming is extremely beneficial. Please enlighten me how is your answer different than mine, kind sir, as both solutions pass the props from the component down to the wrapper. I'm trying to be kind, please be patient with me here.
    – vsync
    Commented Jun 10 at 17:45
  • Nobody is telling people to copy and paste code directly from the internet, that's not my responsibility. It's interesting how people think they can make demands from other people on here whilst being so impolite, it's quite obvious how our answers are different, I suggest you take another look.
    – Sid
    Commented Jun 12 at 1:31
  • First of all, I know you voted my answer down. Second, I've taken a very deep look at your code and only then posted my findings. please I ask you very nicely to explain to me where is the different. I would like you to teach me if you are kind and willing to.
    – vsync
    Commented Jun 12 at 7:51
0

I've made a robust wrapper component which is very intuitively-named, easy to understand, and also support native HTML tags as wrappers:

<WrapIf>:

const WrapIf = ({ condition, With, children, ...rest }) => {
  if (typeof With === 'string') {
    return condition 
      ? React.createElement(With, rest, children)
      : children
  } else {
    // 'With' is a React component
    return condition ? <With {...rest}>{children}</With> : children;
  }
}
    
const Wrapper = ({children, ...rest}) => <h1 {...rest}>{children}</h1>

// demo app: with & without a wrapper
const App = () => [
   // works
  <WrapIf condition={true} With={Wrapper} style={{color:"red"}}>
    {`Wrapped with <Wrapper>`}
  </WrapIf>
  ,
   // will not work because `h1` is not a React component
  <WrapIf condition={true} With="h2" style={{color:"blue"}}>
    {`wrapped with native HTML <h2>`}
  </WrapIf>
  ,
  // will not wrap the children
  <WrapIf condition={false} With={Wrapper}>
    Wrapper is disabled
  </WrapIf>
]

ReactDOM.render(<App/>, document.body)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>

-1

With provided solutions there is a problem with performance: https://medium.com/@cowi4030/optimizing-conditional-rendering-in-react-3fee6b197a20

React will unmount <Icon> component on the next render. Icon exist twice in different order in JSX and React will unmount it if you change props.link on next render. In this case <Icon> its not a heavy component and its acceptable but if you are looking for an other solutions:

https://codesandbox.io/s/82jo98o708?file=/src/index.js

https://thoughtspile.github.io/2018/12/02/react-keep-mounted/

3
  • 1
    Please avoid link only answers. Answers that are "barely more than a link to an external site” may be deleted.
    – Quentin
    Commented Sep 21, 2021 at 10:37
  • @Quentin I have publish answer for this question why its important and users needs to keep in mind this. I think that description is enough and its not link only answer but if you want to say something more.. feels free to Edit it.
    – sytolk
    Commented Sep 28, 2021 at 6:58
  • Icon gets unmounted in any case since the parent will be changed Commented Oct 11, 2021 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.