Categories
React Answers

How to conditionally render multiple child components with React?

Spread the love

Sometimes, we want to conditionally render multiple child components with React.

In this article, we’ll look at how to conditionally render multiple child components with React.

How to conditionally render multiple child components with React?

To conditionally render multiple child components with React, we can render components in an array.

And then we can use a state to control when the components are displayed.

For instance, we write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [visible, setVisible] = useState(true);

  return (
    <>
      <button onClick={() => setVisible((v) => !v)}>toggle</button>
      {visible ? [<p>foo</p>, <p>bar</p>, <p>baz</p>] : null}
    </>
  );
}

We define the visible state with the useState hook.

And we render 3 p elements if visible is true and null otherwise.

Finally, we add a button that calls setVisible to toggle the value of visible when we click on it.

Conclusion

To conditionally render multiple child components with React, we can render components in an array.

And then we can use a state to control when the components are displayed.

Leave a Reply

Your email address will not be published. Required fields are marked *