Search code examples
reactjsuse-stateconditional-operator

Error while conditional rendering of state value using ternary operator inside jsx in Reactjs 18.0


import "./styles.css";
import { useState } from "react";

export default function App() {
  const [points, setPoints] = useState({ playerOne: 0, playerTwo: 0 });
  const [state, setState] = useState(true);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h3> value is {points.playerOne} & {points.playerTwo} </h3>
      <h3> points of player one is {state === true ? 1 : 2} </h3>
      <h3> points of player one is {state === true ? {points.playerOne} : {points.playerTwo}} </h3>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

I can't understand why I am facing an error due to the third h3 tag

<h3> points of player one is {state === true ? {points.playerOne} : {points.playerTwo}} </h3>

if I comment this above line of code then output is rendering fine

Use the link to run the code -- https://codesandbox.io/s/silly-grass-wdoq68?file=/src/App.js

please help!


Solution

  • Remove the curly braces in Conditional (ternary) operator Do this:

      <h3> points of player one is {state  ? points.playerOne : points.playerTwo} </h3>
    

    https://codesandbox.io/s/wizardly-voice-crbtjp