DEV Community

Discussion on: A Clean Way to Conditionally Render Components

Collapse
 
anxiny profile image
Anxiny • Edited

Thanks for the feedback!
I'm not sure if I understand you reply correctly, but here is demo that shows the child component will not be rendered unless the condition is true.

codesandbox.io/s/if-component-demo...

export default function App() {
  const [data, setData] = useState(null);

  return (
    <div className="App">
      {data ? <Child name="A" /> : <Child name="NO DATA" />}
      <If condition={data}>
        <Child name="Has Data" />
      </If>
      <If condition={data}>
        <ChildNeedsData data={data} />
      </If>
    </div>
  );
}

function Child(props) {
  useEffect(() => {
    console.log(`Child ${props.name} is rendered`);
    return () => console.log(`Child ${props.name} is unmounted`);
  }, []);
  console.log(`Child ${props.name} is rendering`);
  return <div>Child {props.name}</div>;
}

function ChildNeedsData(props) {
  return <h4>{props.data.name}</h4>;
}

Enter fullscreen mode Exit fullscreen mode

Output

Child NO DATA is rendering 
Child NO DATA is rendered 
// No Error while running is demo
Enter fullscreen mode Exit fullscreen mode

If you change the code to this:

      <If condition={!data}>
        <ChildNeedsData data={data} />
      </If>
Enter fullscreen mode Exit fullscreen mode

You will get a error.