From React Class component to Functional component with hooks

How to toggle an element in a React component ?

Now that we know how to create React class and functional stateful components, we can try to toggle an element when clicking on a button.

This episode is inspired by  a freecodeCamp challenge. However, I have made some modifications like replacing the button instruction “Click Me” by “Hide” or  “Show” depending on the fact the toggled element is displayed or not. It is a little bit more complicated but the accessibility is improved.

To do that we need to :

  • create a class or functional stateful component,
  • use condition when rendering.

So, let’s create the toggle element in a class component and then let’s try to create it in a functional component.

Summary

Before starting coding, just check that React, React.Dom libraries and Babel preprocessor have been installed.

Create a toggle element in a React Class component.

First, create the toggle element in a React class component. Then, we will try to do the same in a functional component.

Steps to create a toggle element in a React Class component

  1. Install React locally or create a new pen on codepen.
  2. Create the HTML element onto render the component. Give it the id “toggle”.
  3. Create a class component which extends React.Component.
  4. Add the internal state in the constructor with this.state.
  5. Initialize the state visibility property at false to be sure that the toggled element is not displayed the first time the component is rendered.
  6. Create handler method named toggleVisibility. This method should modify the current state to its contrary every time the button is clicked.
  7. Do not forget to bind the handler method.
  8. In the render, add an if else condition to display the toggled element when the current state is set to true. Reminder: the button must always be displayed. Remark: each statement as a return().
  9. In the render, add the onClick attribute on the button element and call the toggleVisibility.

A toggle element React class component code

The final code of a toggle element in a react class component

class MyComponent extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        visibility: false
      };
      this.toggleVisibility = this.toggleVisibility.bind(this);
     }
    toggleVisibility() {
      this.setState(state => ({
        visibility: !state.visibility
      }));
    }
    render() {
      if (this.state.visibility) {
        return (
          <div>
            <button onClick = {this.toggleVisibility}>Hide</button>
            <h1>Now you see me!</h1>
          </div>
        );
      } else {
        return (
          <div>
            <button onClick = {this.toggleVisibility}>Show</button>
          </div>
        );
      }
    }
  };
  ReactDOM.render(<MyComponent />, document.getElementById(‘toggle’));

View the final code of a toggle element in a react class component in a pen

See the Pen
React tricks: toggle a class component element
by Coding-Tricks (@coding-tricks)
on CodePen.

Other rendering condition possibilities

Ternary Expression

    render() {
        return (
            <div>
            {this.state.visibility ?
            <div>
                <button onClick = {this.toggleVisibility}>Hide</button>
                <h1>Now you see me!</h1>
            </div>
            : <button onClick = {this.toggleVisibility}>Show</button> }
            </div>
        )
    }

Condition &&

    render() {
        return (
            <div>
            {this.state.visibility == true &&
                <div>
                <button onClick = {this.toggleVisibility}>Hide</button>
                <h1>Now you see me!</h1>
                </div>
            }
            {this.state.visibility == false &&
                <button onClick = {this.toggleVisibility}>Show</button>
            }
            </div>
        )
    };

Create a Toggle element in a React Functional component with the hook useState and some conditional rendering

We have created a toggle element in a React class component. Let’s try to do the same in a functional component now.

Steps to create a toggle element in a React Functional component

  1. Install React locally or create a new pen on codepen.
  2. Create the HTML element onto render the component. Give it the id “toggle”.
  3. Import the useState hook at the beginning of the file import { useState } from 'react';. Remark: when using codepen the import is not allowed, write const { useState } = React; instead.
  4. Create a functional component.
  5. Add the internal state with the useState() hook. Name it isVisible, for example.
  6. Initialize the state visibility at false to be sure that the toggled element is not displayed the first time the component is rendered.
  7. Create the updating function and name it setIsVisible. This method should modify the current state to its contrary every time the button is clicked.
  8. In the return of the component function, add a ternary expression to display the toggled element when the current state is set to true. Remark: he button must always be displayed.
  9. In the render, add the onClick attribute on the button element and call the setIsVisble function passing it false as argument when the element is displayed, and true when the element is not displayed.

A toggle element React Functional component Code

The final code of a toggle element in a react functional component

import { useState } from ‘react’;
const MyComponent = () => {
    const [isVisible, setIsVisible] = useState(false);
    return isVisible ? (
        <div>
        <button onClick={() => setIsVisible(false)}>Hide</button>
            <h1>Now you see me!</h1>
        </div>
    ) : (
        <div>
            <button onClick={() => setIsVisible(true)}>Show</button>
        </div>
    )
}
ReactDOM.render(<MyComponent />, document.getElementById(‘toggle’));

View the final code of a toggle element in a react functional component in a pen

See the Pen
React tricks: toggle an element with the hook useState
by Coding-Tricks (@coding-tricks)
on CodePen.

In conclusion

As a result, we can say that it is possible to create a toggled element either in a class or a functional React component. Obviously, the structures are different. finally, it seems that the functional structure is shorter.

In the next episode, we will learn  how to create a simple counter in both types of React components.

comment

There is no comments. Leave the first one!

Leave a Reply

Your email address will not be published. Required fields are marked *

Haut de page