Reactjs How to write the greater than 0 in jsx?

Viewed 791

Reactjs How to write the greater than 0 in jsx?

this is my current code

return (
    {num > 0 ? (
       console.log('greater than 0')
    ):(console.log('less than zero')}
  )
4 Answers
 export default function App() {
  const num = 2;
  return (
   <div>
    {num > 0 ? <h1> Greater than Zero </h1> : <h1> Zero</h1>}
   </div>
  );
 }

You mean you wanna display the evaluation on screen? There is a clean way to do that.

const App = () => {
...// logic you want

    const comment = num > 0 ? 'greater than 0' : 'less than zero';
    return <p>{comment}</p>
}

Replace > by &gt and replace < by &lt

You can use the following code as a replacement :

return (
    {num &gt 0 ? (
       console.log('greater than 0')
    ):(console.log('less than zero')}
  )

We have to first validate num exists and then do the conditional checking if it exists.

return (
{num && num > 0 ? (
   console.log('greater than 0')
):(console.log('less than zero'))})

Also you were missing a ')' at the end, which was a syntactical error

Related