What is Conditional rendering?
- Conditional rendering is the ability to render different UI markup based on certain conditions.
- 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 return statement and JSX
- You can use if/else statement in render()
- Instead of this, you can use use ternary operator or logical && operator
import React, { Component } from 'react'
class Conditional extends Component {
constructor (props){
super(props)
this.state = {
userIsViraj : true,
}
}
render() {
if(this.state.userIsViraj){
return(
<div>Welcome Viraj!</div>
)
} else{
return(
<div>Welcome Guest!</div>
)
}
}
}
export default Conditional;
2. Element Variables:
- Element variables is a simple variable which can hold the JSX element and it can be rendered when required.
import React, { Component } from 'react'
class Conditional extends Component {
constructor (props){
super(props)
this.state = {
isUserViraj : true,
}
}
render() {
let user
if (this.state.isUserViraj) {
user = <div>Welcome Viraj!</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.
- Hence, if you want to use if/else statement in JSX then you can use ternary conditional operator
import React, { Component } from 'react'
class Conditional extends Component {
constructor (props){
super(props)
this.state = {
userIsViraj : true,
}
}
render() {
return (
<div>
{ this.state.userIsViraj ? (
<div> Welcome Viraj! </div>
) :
<div> Welcome Guest! </div>
}
</div>
)
}
}
export default Conditional;
4. Short Circuit Operator:
- Short Circuit Operator includes the JavaScript logical && operator.
- Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.
import React, { Component } from 'react'
class Conditional extends Component {
constructor (props){
super(props)
this.state = {
isUserViraj : true,
}
}
render() {
return (
<div>
{ this.state.isUserViraj &&
<div>
Welcome Viraj!
</div> }
</div>
)
}
}
export default Conditional;
Here, the message "Welcome Viraj!" will render only if this.state.isUserViraj is true otherwise it will render nothing.
Top comments (6)
Really good tutorial. Helped me better my simple understanding of React.
Thank You 😀
Please add the JavaScript tag to the codebooks
Sure!
{this.state.isUserViraj &&
Welcome Viraj!
}
Lovely article, thank you.
Thank You 😃