Home > Software design >  Short circuiting not working in react render div
Short circuiting not working in react render div

Time:03-18

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 ?

CodePudding user response:

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>

CodePudding user response:

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.

  • Related