Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
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 ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!