Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading