Reputation: 7094
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.
Upvotes: 3
Views: 460
Reputation: 3107
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>
)
}
Upvotes: 3
Reputation: 2204
You have to use ternary operator:
{variable ?
<p style={{ color: 'black'}}> Hello</p>
:
<p> world </p>
}
Colon :
---> or
hello or
world
Look here: https://codepen.io/gaearon/pen/Xjoqwm?editors=0010
Documentation react rendering: https://reactjs.org/docs/conditional-rendering.html
if variable
is true
return <p> hello </ p>
if false
return <p> world </ p>
Upvotes: 0
Reputation: 6446
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.
Upvotes: 0
Reputation: 410
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>
}
)
Upvotes: -1
Reputation: 263
You can use ternary conditional operator(?)
return (
<p title={ 'Publish Checklist' }> TEST </p>
{
variable?<p> hello </p>:<p> world </p>
}
)
Upvotes: 0
Reputation: 1261
Error is use JSX syntax instead of if-statement
return (
<>
<p title={ 'Publish Checklist' }> TEST </p>
{
variable ? <p> hello </p>: <p> world </p>
}
</>
)
Upvotes: 0