~/reactjs/how-use-render-conditional-jsx-reactjs.md

ReactJS - How to use conditionals in render JSX

2 min readJune 23, 2020by Gorav Singal#reactjs
// TL;DR

Use ternary operators, logical && short-circuit evaluation, or extracted helper methods to conditionally render elements in React JSX based on component state or props.

ReactJS - How to use conditionals in render JSX

Introduction

In this post, I will show several ways to use conditionals while rendering html or component in jsx.

Consider we have a component, and based on a boolean flag we want to show or hide a paragraph

Below is a small component which receives props having book name and author name. Lets not concentrate on how the whole app works. We want to focus on conditional rendering.

import React, { Component } from 'react'

export default class Book extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false
        };
    }

    toggleInfo = () => {
        this.setState({show: !this.state.show});
    }

    render() {
        const {book, author} = this.props.info;
        return (
            <article>
                <h3>book: {book}</h3>
                <h5>author: {author}</h5>
            </article>
        )
    }
}

Objective

Lets include a button in this component, and on click lets toggle show or hide a paragraph.

Method-1 - Using inline boolean condition

import React, { Component } from 'react'

export default class Book extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false
        };
    }

    toggleInfo = () => {
        this.setState({show: !this.state.show});
    }

    render() {
        const {book, author} = this.props.info;
        return (
            <article>
                <h3>book: {book}</h3>
                <h5>author: {author}</h5>
                <button type="button" onClick={this.toggleInfo}>Toggle Paragraph</button>

                {
                    this.state.show && <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam, nobis!</p>
                }
            </article>
        )
    }
}

toggleInfo is self explanatory. We are just toggling a boolean flag in component’s state. In render() method, we are checking that boolean flag and showing the paragraph if this flag is true. Simple enough.

Method-2 - Using Ternary Operator

import React, { Component } from 'react'

export default class Book extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false
        };
    }

    toggleInfo = () => {
        this.setState({show: !this.state.show});
    }

    render() {
        const {book, author} = this.props.info;
        return (
            <article>
                <h3>book: {book}</h3>
                <h5>author: {author}</h5>
                <button type="button" onClick={this.toggleInfo}>Toggle Paragraph</button>

                {
                    this.state.show ? 
                    (<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam, nobis!</p>)
                    : null
                }
            </article>
        )
    }
}

Rest of the code is same. Note the ternary operator which is quite easy to understand.

Method-3 - By using a function

We can define a method(function) in the component which will take this decision whether to show the paragraph or not.

import React, { Component } from 'react'

export default class Book extends Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false
        };
    }

    toggleInfo = () => {
        this.setState({show: !this.state.show});
    }

    toShow = () => {
        if (this.state.show) {
            return <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam, nobis!</p>;
        }
        else {
            return null;
        }
    }

    render() {
        const {book, author} = this.props.info;
        return (
            <article>
                <h3>book: {book}</h3>
                <h5>author: {author}</h5>
                <button type="button" onClick={this.toggleInfo}>Toggle Paragraph</button>

                {this.toShow()}
            </article>
        )
    }
}

These three methods are simple to use, and you can use anyone.

Note: If you are having confusion that I did not use bind on the extra function I defined. Notice that I’m using ES6 arrow function, not the traditional function keyword.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS setState is Asynchronous setState() method in ReactJS class components…

ReactJS - How to restrict data type for different kind of data

ReactJS - How to restrict data type for different kind of data

Introduction Javascript is not a strict type language. We can use a variable to…

ReactJS - How to create ReactJS components

ReactJS - How to create ReactJS components

Introduction In this post, we will talk about basic of how to create components…

ReactJS - Basic Form Handling and Form submission

ReactJS - Basic Form Handling and Form submission

Introduction Lets take a look at how forms are being handled in ReactJS. We will…

ReactJS - How to pass method to component and how to pass arguments to method

ReactJS - How to pass method to component and how to pass arguments to method

Introduction In the ReactJS project, you are having aa parent component and a…

ReactJS - 3 ways to Import components in ReactJS

ReactJS - 3 ways to Import components in ReactJS

Introduction In this post, we will discuss 3 different ways to import a…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…