Rob E.
Rob E.

Reputation: 194

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

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.

Upvotes: 0

Views: 62

Answers (3)

Prince Sodhi
Prince Sodhi

Reputation: 2955

Try this

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

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

    export default App;

Upvotes: 2

Konrad
Konrad

Reputation: 24661

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

stop adding {} everywhere

Upvotes: 2

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41417

try this

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

Upvotes: 2

Related Questions