Home > Net >  How to use value of state in a JSX expression in a functional React component?
How to use value of state in a JSX expression in a functional React component?

Time:11-10

I would like to use a value of a state variable in a JSX expression and cannot figure out the syntax. Here is simplified code:

function App() {
  const [isLoading, setIsLoading] = useState(false);
  const [page, setPage] = useState(1);

  return (
    <div>
          {isLoading ? `Loading...` : 'Load Page '   {page}}
    </div>
  );
}

export default App;

If isLoading is false, I would like the output to say Load Page 1.

As of now it says Load Page [object Object] and I am stuck on the syntax.

Thanks.

CodePudding user response:

{isLoading ? `Loading...` : 'Load Page '   page}

stop adding {} everywhere

CodePudding user response:

try this

{isLoading ? `Loading...` :`Load Page ${page}`}

CodePudding user response:

Try this

    function App() {
      const [isLoading, setIsLoading] = useState(false);
      const [page, setPage] = useState(1);

      return <div>{isLoading ? `Loading...` : `Load Page ${page}`}</div>;
    }

    export default App;
  • Related