30 Days Of React: Conditional Rendering

Twitter Follow Author: Asabeneh Yetayeh
October, 2020
[<< Day 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_React_Project_Folder_Structure/10_react_project_folder_structure.md) ![30 Days of React banner](../images/30_days_of_react_banner_day_9.jpg) # Conditional Rendering As we can understand from the term, conditional rendering is a way to render different JSX or component at different condition. We can implement conditional rendering using regular if and else statement, ternary operator and &&. Let's implement a different conditional rendering. ## Conditional Rendering using If and Else statement In the code below, we have an initial state of loggedIn which is false. If the state is false we inform user to log in otherwise we welcome the user. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { render() { const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

{welcome}

{title}

{subtitle}

{firstName} {lastName}

{date}

Select a country for your next holiday

) } } class App extends React.Component { state = { loggedIn: false, } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } // conditional rendering using if and else statement let status if (this.state.loggedIn) { status =

Welcome to 30 Days Of React

} else { status =

Please Login

} return (
{status}
) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` Let's add a method which allow as to toggle the status of the user. We should have a button to handle event for logging in and logging out. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // class based component class Header extends React.Component { render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

{welcome}

{title}

{subtitle}

{firstName} {lastName}

{date}
) } } class App extends React.Component { state = { loggedIn: false, } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } let status let text if (this.state.loggedIn) { status =

Welcome to 30 Days Of React

text = 'Logout' } else { status =

Please Login

text = 'Login' } return (
{status}
) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` How about if our condition is more than two? Like pure JavaScript we can use if else if statement. In general, conditional rendering is not different from pure JavaScript conditional statement. ## Conditional Rendering using Ternary Operator Ternary operator is an an alternative for if else statement. However, there is more use cases for ternary operator than if else statement. For example, use can use ternary operator inside styles, className or many places in a component than regular if else statement. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // class based component class Header extends React.Component { render() { const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

{welcome}

{title}

{subtitle}

{firstName} {lastName}

{date}
) } } class App extends React.Component { state = { loggedIn: false, } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } let status = this.state.loggedIn ? (

Welcome to 30 Days Of React

) : (

Please Login

) return (
{status}
) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` In addition to JSX, we can also conditionally render a component. Let's change the above conditional JSX to a component. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // class based component class Header extends React.Component { render() { const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

{welcome}

{title}

{subtitle}

{firstName} {lastName}

{date}
) } } const Login = () => (

Please Login

) const Welcome = (props) => (

Welcome to 30 Days Of React

) class App extends React.Component { state = { loggedIn: false, } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } const status = this.state.loggedIn ? : return (
{status}
) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## Conditional Rendering using && Operator The && operator render the right JSX operand if the left operand(expression) is true. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // A button component const Button = ({ text, onClick, style }) => ( ) // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // class based component class Header extends React.Component { render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

{welcome}

{title}

{subtitle}

{firstName} {lastName}

{date}
) } } const Login = () => (

Please Login

) const Welcome = (props) => (

Welcome to 30 Days Of React

) class App extends React.Component { state = { loggedIn: false, techs: ['HTML', 'CSS', 'JS'], } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } // We can destructure state const { loggedIn, techs } = this.state const status = loggedIn ? : return (
{status}
) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` In the previous section, we used alert box to greet people and also to display time. Let's render the greeting and time on browser DOM instead of displaying on alert box. ```js // index.js import React from 'react' import ReactDOM from 'react-dom' // class based component class Header extends React.Component { render() { console.log(this.props.data) const { welcome, title, subtitle, author: { firstName, lastName }, date, } = this.props.data return (

{welcome}

{title}

{subtitle}

{firstName} {lastName}

{date}
) } } const Message = ({ message }) => (

{message}

) const Login = () => (

Please Login

) const Welcome = (props) => (

Welcome to 30 Days Of React

) // A button component const Button = ({ text, onClick, style }) => ( ) // TechList Component // class base component class TechList extends React.Component { render() { const { techs } = this.props const techsFormatted = techs.map((tech) =>
  • {tech}
  • ) return techsFormatted } } // Main Component // Class Component class Main extends React.Component { render() { const { techs, greetPeople, handleTime, loggedIn, handleLogin, message, } = this.props console.log(message) const status = loggedIn ? : return (

    Prerequisite to get started react.js:

    {techs.length === 3 && (

    You have all the prerequisite courses to get started React

    )}
    ) } } // CSS styles in JavaScript Object const buttonStyles = { backgroundColor: '#61dbfb', padding: 10, border: 'none', borderRadius: 5, margin: '3px auto', cursor: 'pointer', fontSize: 22, color: 'white', } // Footer Component // Class component class Footer extends React.Component { constructor(props) { super(props) } render() { return (

    Copyright {this.props.date.getFullYear()}

    ) } } class App extends React.Component { state = { loggedIn: false, techs: ['HTML', 'CSS', 'JS'], message: 'Click show time or Greet people to change me', } handleLogin = () => { this.setState({ loggedIn: !this.state.loggedIn, }) } showDate = (time) => { const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] const month = months[time.getMonth()].slice(0, 3) const year = time.getFullYear() const date = time.getDate() return `${month} ${date}, ${year}` } handleTime = () => { let message = this.showDate(new Date()) this.setState({ message }) } greetPeople = () => { let message = 'Welcome to 30 Days Of React Challenge, 2020' this.setState({ message }) } render() { const data = { welcome: '30 Days Of React', title: 'Getting Started React', subtitle: 'JavaScript Library', author: { firstName: 'Asabeneh', lastName: 'Yetayeh', }, date: 'Oct 9, 2020', } return (
    ) } } const rootElement = document.getElementById('root') ReactDOM.render(, rootElement) ``` ## Exercises ### Exercises: Level 1 1. What is conditional rendering? 2. How do you implement conditional rendering? 3. Which method of conditional rendering do you prefer to use? ### Exercises: Level 2 1. Make a single page application which changes the body of the background based on the season of the year(Autumn, Winter, Spring, Summer) 2. Make a single page application which change the body of the background based on the time of the day(Morning, Noon, Evening, Night) ### Exercises: Level 3 1. Fetching data takes some amount of time. A user has to wait until the data get loaded. Implement a loading functionality of a data is not fetched yet. You can simulate the delay using setTimeout. 🎉 CONGRATULATIONS ! 🎉 [<< Day 8](../08_Day_States/08_states.md) | [Day 10 >>](../10_React_Project_Folder_Structure/10_react_project_folder_structure.md)