React js Class Component
Conditional Statement in Class Component
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 && operatorimport 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 userif (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 operatorimport 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;
- 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