react js-tutorial

React Conditional Rendering

The technique of presenting widgets and components based on specific situations is known as conditional rendering in React.

In React, conditional rendering may be applied in a number of different ways. Like with most things in programming, depending on the issue you’re attempting to solve, some things are more appropriate than others.

In this article, we’ll discuss several recommendations and best practises as well as the most popular techniques to handle conditional rendering in React.

We’ll construct a component with view and edit functionality to show how all these techniques operate. This component looks like the gif below:

To follow along, you can fork each example in JSFiddle. We’ll begin with the most basic implementation—an if—then—else block—and work our way up from there.

How to write if…else in React

Create a component with the following state:

import React from "react"

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "",
      inputText: "",
      mode: "view",
    };
  }
}

You’ll use one property for the saved text and another for the text that is being edited. A third property will indicate if you are in edit or view mode.

Next, add some methods for handling input text, then save and edit events as follows:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {text: '', inputText: '', mode:'view'};

    this.handleChange = this.handleChange.bind(this);
    this.handleSave = this.handleSave.bind(this);
    this.handleEdit = this.handleEdit.bind(this);
  }

  handleChange(e) {
    this.setState({ inputText: e.target.value });
  }

  handleSave() {
    this.setState({text: this.state.inputText, mode: 'view'});
  }

  handleEdit() {
    this.setState({mode: 'edit'});
  }
}

Now, for the render method, check the mode state property to either render an edit button or a text input and a save button, in addition to the saved text:

class App extends React.Component {
  // …
  render () {
    if(this.state.mode === 'view') {
      return (
        <div>
          <p>Text: {this.state.text}</p>
          <button onClick={this.handleEdit}>
            Edit
          </button>
        </div>
      );
    } else {
      return (
        <div>
          <p>Text: {this.state.text}</p>
            <input
              onChange={this.handleChange}
              value={this.state.inputText}
            />
          <button onClick={this.handleSave}>
            Save
          </button>
        </div>
      );
    }
}

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.