A Clean Way to Conditionally Render Components

anxiny

Anxiny

Posted on January 16, 2022

A Clean Way to Conditionally Render Components

Today, I want to share a clean way to conditionally render child components while using React. It's very simple.

Live Demo:
https://codesandbox.io/s/if-component-demo-9iipl?file=/src/App.js

Before

function App(){
  // ...
  return <div>
      {someCondition?
      <SomeChildA>
        <div>Some Contents</div>
        <div>Some Contents</div>
        <div>Some Contents</div>
      </SomeChildA>
      : 
      <SomeChildB>
        <div>Some Contents</div>
        <div>Some Contents</div>
        <div>Some Contents</div>
      </SomeChildB>}
    </div>
}

Enter fullscreen mode Exit fullscreen mode

After

function App(){
  // ...
  return <div>
      <If condition={someCondition}>
        <SomeChildA>
          <div>Some Contents</div>
          <div>Some Contents</div>
          <div>Some Contents</div>
        </SomeChildA>
      </If>
      <If condition={!someCondition}>
        <SomeChildB>
          <div>Some Contents</div>
          <div>Some Contents</div>
          <If condition={someOtherCondition}>
            <NestExample/>
          </If>
          <div>Some Contents</div>
        </SomeChildB>
      </If>
    </div>
}

Enter fullscreen mode Exit fullscreen mode

<If/> Component

function If(props) {
    return props.condition ? <>{props.children}</> : null;
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! Have a nice day!

💖 💪 🙅 🚩
anxiny
Anxiny

Posted on January 16, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related