In React, conditional rendering refers to the functionality of show elements and components based on the conditions. There are many way’s to do conditional rendering. below are the few examples
How to use IF Else Condition in React ?
1. Using normal If / Else condition
2. Using Turnery operator
import React from "react"; export default function App() { let isLoggedIn = true; return isLoggedIn ? (<h1> Welcome User Name </h1>) : (<h1> Welcome Guest </h1>) }
3. If you want to render only if condition without else condition – Using Logical &&
(Short Circuit Evaluation)
import React, { Component } from 'react' class UserGreeting extends Component { constructor(props) { super(props) this.state = { isLoggedIn: false } } render() { return ( this.state.isLoggedIn && (<h1> Welcome User Name </h1>) ) } } export default UserGreeting
4. Using Element Variables.
Element variables are similar to the approach to extract the conditional rendering into a function.
import React, { Component } from "react";
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: true
};
}
render() {
let { isLoggedIn } = this.state;
let loginMessage;
if (isLoggedIn) {
loginMessage= <h1> Welcome UserName</h1>;
} else {
loginMessage= <h1> Welcome UserName</h1>;
}
return (
<div className="App">
{loginMessage}
</div>
);
}
}
export default App;