React: Render with an If-Else Condition
Randy Rivera
Posted on November 15, 2021
- Another way of using JavaScript to control your rendered view is to tie the elements that are rendered to a condition. When the condition is true, one view renders. When it's false, it's a different view. We can do this with the basic if/else statement.
- FreeCodeCamp has a class MyComponent which contains a
boolean
in its state which tracks whether you watn to display some element in the UI or not. Thebutton
toggles the state of this value. Right now, it render the same UI everytime. Let's rewrite therender()
method with anif/else
statement so that ifdisplay
istrue
, you return the current markup. Otherwise, return the markup without theh1
element. - Code:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: true
}
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
this.setState((state) => ({
display: !state.display
}));
}
render() {
// Change code below this line
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
<h1>Displayed!</h1>
</div>
);
}
};
- Answer:
render() {
if (this.state.display === true) {
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
<h1>Displayed!</h1>
</div>
);
} else {
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
</div>
)
}
}
};
Use && for a More Brief Conditional
- You can also use the
&&
logical operator to perform conditional logic in a more concise way. This is possible because you want to check if a condition is true, and if it is, return some markup. - Ex:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
display: true
}
this.toggleDisplay = this.toggleDisplay.bind(this);
}
toggleDisplay() {
this.setState(state => ({
display: !state.display
}));
}
render() {
return (
<div>
<button onClick={this.toggleDisplay}>Toggle Display</button>
{this.state.display === true && <h1>Displayed!</h1>}
</div>
);
}
};
- If the
condition
istrue
, the markup will be returned. If the condition isfalse
, the operation will immediately returnfalse
after evaluating the condition and return nothing. You can include these statements directly in your JSX and string multiple conditions together by writing && after each one.
💖 💪 🙅 🚩
Randy Rivera
Posted on November 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.