Conditional rendering: React
2 min readJan 11, 2022
What is Conditional rendering?
- It is a way to render different elements or components based on a condition.
- Conditional rendering in React works the same way conditions work in JavaScript.
What are the types of Conditional rendering?
- if/else
- Element Variables
- Ternary Conditional Operator
- Short Circuit Operator
1. if/else:
- if/else cannot be used inside the return statement and JSX
- You can use the if/else statement in render()
- Alternatively, you can use a ternary or logical
&&
operator instead.
class Conditional extends React.Component {
constructor (props){
super(props)
this.state = {
isLoggedIn : true,
}
}
render() {
if (this.state.isLoggedIn) {
return (
<div>Hello, JRADNESS!</div>
)
} else {
return (
<div>Welcome Guest!</div>
)
}
}
}
export default Conditional;
2. Element Variables:
- Element variables are variables which can hold the JSX element that can be rendered when required.
class Conditional extends React.Component {
constructor (props){
super(props)
this.state = {
isLoggedIn : true,
}
}
render() {
let user; if (this.state.isLoggedIn) {
user = <div>Hello, JRADNESS!</div>
} else {
user = <div>Welcome Guest!</div>
}
return(
<div>{user}</div>
)
}
}
export default Conditional;
3. Ternary Conditional Operator:
- You can use JavaScript in JSX, but it becomes difficult when using statements like if/else within JSX.
- If you want to use an if/else statement in JSX, you can use ternary conditional operator instead.
class Conditional extends React.Component {
constructor (props) {
super(props)
this.state = {
isLoggedIn : true,
}
}
render() {
return (
<div>
{this.state.isLoggedIn ?
(
<div>Hello, JRADNESS!</div>
): <div>Welcome Guest!</div>
}
</div>
)
}
}
export default Conditional;
4. Short Circuit Operator:
- Short Circuit Operators include the JavaScript logical
&&
operator. - If the condition is true, the element right after
&&
will display in the output. If it is false, React will ignore and skip it.
class Conditional extends React.Component {
constructor (props){
super(props)
this.state = {
isLoggedIn : true,
}
}
render() {
return (
<div>
{this.state.isLoggedIn && <div>Hello, JRADNESS!</div> }
</div>
)
}
}
export default Conditional;
Here, “Hello, JRADNESS!” will render only if this.state.isLogged
is true, otherwise it will render nothing.
Me personally, I find the ternary and short circuit operators my go to - they have a clean and easy to read syntax. Thanks for reading!