Conditional Rendering in React

import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: true
};
}
render() {
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
<button>Login</button>
<button>Logout</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

⚫ If / else Statment

// index.js
...
render() {
let {isLoggedIn} = this.state;
const renderAuthButton = ()=>{
if(isLoggedIn){
return <button>Logout</button>
} else{
return <button>Login</button>
}
}
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{renderAuthButton()}
</div>
);
}
...

Multiple return statements

// AuthButton.jsimport React from "react";const AuthButton = props => {
let { isLoggedIn } = props;
if (isLoggedIn) {
return <button>Logout</button>;
} else {
return <button>Login</button>;
}
};
export default AuthButton;
// index.js
...
import AuthButton from "./AuthButton";
...
render() {
let { isLoggedIn } = this.state;
return (
<div className="App">
...
<AuthButton isLoggedIn={isLoggedIn} />
</div>
);
}
...

⚫ Using Element Variables

// index.js
...
render() {
let { isLoggedIn } = this.state;
let AuthButton;
if (isLoggedIn) {
AuthButton = <button>Logout</button>;
} else {
AuthButton = <button>Login</button>;
}
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{AuthButton}
</div>
);
}
...

⚫ Using a Switch Statement

// AuthButton.js
import React from "react";
const AuthButton = props => {
let { isLoggedIn } = props;
switch (isLoggedIn) {
case true:
return <button>Logout</button>;
break;
case false:
return <button>Login</button>;
break;
default:
return null;
}
};
export default AuthButton;

⚫ Ternary Operators

// index.js
...
render() {
let { isLoggedIn } = this.state;
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{isLoggedIn ? <button>Logout</button> : <button>Login</button>}
</div>
);
}
...

⚫ Logical &&

// index.js
...
render() {
let { isLoggedIn } = this.state;
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{isLoggedIn && <button>Logout</button>}
</div>
);
}
...

⚫ Using IIFEs

//index.js
...
render() {
let { isLoggedIn } = this.state;
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{(function() {
if (isLoggedIn) {
return <button>Logout</button>;
} else {
return <button>Login</button>;
}
})()}
</div>
);
}
...

SOFTWARE ENGINEER — WEB DEVELOPER WITH HEART FOR FRONT-END, MINIMALISM AND RASMENTALISM.