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

React nested ternary in render for JSX?

Was trying out nested ternary render, but the syntax doesn’t seem to be valid?

export default function App() {
  const toggle = true;
  const toggle2 = true;

  return (
    <div className="App">
      {toggle ? (
        <div>true</div>
      )
      : (
        {toggle2 ? (
          <div>false, true</div>
        ): (
          <div>false, false</div>
        )}
      )}
    </div>
  );
}

Single level works though:

export default function App() {
  const toggle = true;
  const toggle2 = true;

  return (
    <div className="App">
      {toggle ? (
        <div>true</div>
      )
      : (
        <div>false</div>
      )}
    </div>
  );
}

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 :

you got lost with all these parenthesis and curly braces. I don’t know who started wrapping every piece of JSX in parenthesis but you don’t need it and to me it’s usually just noise.

export default function App() {
  const toggle = true;
  const toggle2 = true;

  return <div className="App">
    {
      toggle ? <div>true</div>
        : toggle2 ? <div>false, true</div>
          : <div>false, false</div>
    }
  </div>;
}

with some parenthesis:

export default function App() {
  const toggle = true;
  const toggle2 = true;

  return <div className="App">
    {toggle ? (
      <div>true</div>
    ) : toggle2 ? (
      <div>false, true</div>
    ) : (
      <div>false, false</div>
    )}
  </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