'Short circuiting not working in react render div

I want to start multiple components when a variable is true and I am using as follow:

return (
        <div className="report">
            {conditionalVariable &&
            <ComponentA/> &&
            <ComponentB/>
            }
         </div>
    )

However, when the variable is true, only component A is getting up but not component B.What is wrong with this ?



Solution 1:[1]

I'm surprised you're getting any output. Those conditional components once you've worked out the logic, need to have a parent - either with a fragment, or a div, or something.

You would have seen something similar to this error:

SyntaxError: Inline Babel script: Adjacent JSX elements must be wrapped in an enclosing tag

const { Fragment, useState } = React;

function Example() {

  const [ conditional, setConditional ] = useState(false);

  function handleClick() {
    setConditional(!conditional);
  }

  return (
    <div>
      {conditional && (
        <Fragment>
          <Test text="Bob" />
          <Test text="Sue" />
        </Fragment>
      )}
      <button onClick={handleClick}>
        Click me
      </button>
    </div>
  );

}

function Test({ text }) {
  return <p>{text}</p>;
}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<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>
<div id="react"></div>

Solution 2:[2]

Your curly braces are set rather strange. Try it like this:

return (
    <div className="report">
        {conditionalVariable &&
            <>
                <ComponentA />
                <ComponentB />
            </>
        }
    </div>
)

This solution uses the short syntax of React.Fragment to group the two components you want to display under the same condition.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2