Home > other >  React nested ternary in render for JSX?
React nested ternary in render for JSX?

Time:01-13

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>
  );
}

CodePudding user response:

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>;
}

CodePudding user response:

You add an extra {}. It should be :

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

CodePudding user response:

This should do the job:

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

CodePudding user response:

I personally find it easier to read when using React.Fragments, for example:

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

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

But you can omit the second pair of braces and the React.Fragment to make it more compact:

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

  return (
    <div>
     {toggle
       ? <div>true</div>
       : toggle2
          ? <div>false, true</div>
          : <div>false, false</div>
     }
    </div>
  );
}
  • Related