Skip to content
Advertisement

How can I render multiple elements after an inline condition using short circuit evaluation?

Using a short circuit evaluation in a functional component (with hooks):

const Filters = () => {
  const [options, setOptions] = useState([]);

  return (
    <div className="row">
      {options.length > 0 && (
        <div className="col-md-3">
          <CustomComponent />
        </div>
      )}
    </div>
  )
}

Is there a way to render multiple elements right after an inline if condition?

{options.length > 0 && (
  <div className="col-md-3">
    <CustomComponent />
  </div>
  <div className="col-md-3">
    <SecondComponent />
  </div>
)}

Code above doesn’t work, react throws an error. options array is filled after a promise resolved from useEffect(). That’s why i’ve added this check, to display elements only when a promise resolved.

UPDATED CODE for @wentjun:

return (
  {options.length > 0 && (
    <div className="row">
      <div className="col-md-3">
        <CustomComponent />
      </div>
    </div>
  )}
  )

This throws a syntax error.

Advertisement

Answer

You should wrap the elements in React Fragments. The reason being, React elements are rendered via a single root node element. Wrapping it in Fragments will allow you to group the elements without adding additional nodes.

return (
  <div className="row">
    {options.length > 0 && (
      <>
      <div className="col-md-3">
        <CustomComponent />
      </div>
      <div className="col-md-3">
        <SecondComponent />
      </div>
    </>
  )}
  </div>
)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement