In react, how do I do an if statement

Viewed 175

I react, have this:

return (
   <p title={ 'name' }> TEST </p>
)

And I want to do an if statement within the return. I tested this:

return (
   <p title={ 'name' }> TEST </p>
   if (variable) {
      <p> hello </p>
   } else {
      <p> world </p>
   }
)

Obviously, I have no idea what I'm doing. What's the correct approach? Sorry about the entry-level question.

6 Answers

You could use the ternary operator (?), and you also have to have a wrapper element to contain the two separate paragraphs (title and content), so a simple return would be:

render() {

    return (
        <div>
            <p title={'name'}> TEST </p>
            <p> { variable ? "hello" : "world" } </p>
        </div>
    )
}

For readability, it's better to split the "one-liner":

// ...
<p>
{ 
    variable ? (
        <em style={{color: 'black'}}>hello</em>
    ) : (
        <em>world</em> 
    )
}
</p>
// ...

However, it's not always that simple, so I'd recommend using a placeholder variable, e.g.:

render() {

    var $content;
    if(variable) {
        $content = (<p>hello</p>);
    }
    else {
        $content = (<p>world</p>);
    }


    return (
        <div>
            <p title={'name'}> TEST </p>
            {$content}
        </div>
    )
}

Error is use JSX syntax instead of if-statement

return (
   <>
   <p title={ 'Publish Checklist' }> TEST </p>
    {
        variable ? <p> hello </p>: <p> world </p>
    }
   </>
)

You can use ternary conditional operator(?)

return (
   <p title={ 'Publish Checklist' }> TEST </p>
   {
      variable?<p> hello </p>:<p> world </p>
   }
)

You want to use a ternary operator. It acts the same as an if/else statement, where ? is the if, and : is the else:

condition
  ? // code where condition is true
  : // code where condition is false

Here's how you would implement it:

return (
   <>
     <p title='name'> TEST </p>
     {variable ? <p> hello </p> : <p> world </p>}
   </>
)

Note, I noticed you used title={'name'}. This works fine, but you can write it as normal html: title='name'. Also, react components only take one child component when rendering, so you can wrap your returned nodes in a React fragment or just a div.

You can use conditional rendering within react. Read more on this here: https://reactjs.org/docs/conditional-rendering.html

In your case, a ternary operator would work well. The syntax of which is as follows:

condition ? if : else

In your case you could use it like this:

return (
   <p title={ 'name' }> TEST </p>
  {variable ?
      <p> hello </p>
   :
      <p> world </p>
   }
)
Related