From React Class component to Functional component with hooks

How to create a React Simple Counter ?

Now that we know how to create React class and functional stateful components, we can try to create a Simple Counter which keeps track of a count value in state which is modified when clicking on decrement, increment and reset buttons. This episode has been inspired by a freecodeCamp challenge I have lightly modified.

To create this counter we need to:

  • create a component,
  • create and initialize a state,
  • writing methods that set state,
  • assigning click handlers to trigger these methods.

So, let’s create the Simple Counter 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 Simple Counter in a React Class component.

Before creating a Simple Counter in a React Functional component, let’s create it in a class 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 “counter”.
  3. Create a class component which extends React.Component. Name it Counter.
  4. Add the internal state in the constructor with this.state.
  5. Initialize the state count property at 0.
  6. Create a handler method named increment so when the decrement button is clicked, the counter value is increment by 1.
  7. Create a handler method named decrement so when the decrement button is clicked, the counter value is decrement by 1.
  8. Create a reset() method so when the reset button is clicked, the count is set to 0.
  9. Do not forget to add the necessary bindings for the created methods in the constructor.
  10. In the render, create the three buttons: Decrement, Increment and Reset.
  11. Add a className to every button and write a little bit of CSS (change the color of the background depending on the button, for example).
  12. Assign click handlers to trigger the appropriate method when the button is clicked.
  13. In the render, add a <p> element to display the current state count property value.

A Simple Counter React class component code

The final code of a Simple Counter in a React class component

class Counter extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        count: 0
      };
      this.increment = this.increment.bind(this);
      this.decrement = this.decrement.bind(this);
      this.reset = this.reset.bind(this);
    }
    increment() {
      this.setState(state => ({count: state.count +1}))
    };
    decrement() {
      this.setState(state => ({count: state.count -1}))
    };
    reset() {
      this.setState(state => ({count: 0}))
    };
    render() {
      return (
        <div>
          <button className=’decrement’ onClick={this.decrement}>Decrement</button>
          <button className=’increment’ onClick={this.increment}>Increment</button>
          <button className=’reset’ onClick={this.reset}>Reset</button>
          <p>Current Count: {this.state.count}</p>
        </div>
      );
    }
};

View the final code of simple counter in a React class component in a pen

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

Create a Simple counter in a React Functional component with the hook useState

Let’s create this Simple Counter in a React.js functional component has been inspired by the Create a application with React.js published on the OpenClassrooms platform. Then we will create it in a way whose structure is closer to the newly-created one in a class component.

Steps to create a Simple Counter 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 “counter”.
  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 named Counter.
  5. Add the initialState which equals 0 in constant at the top of the functional component. Remark: this variable is added because of the Reset button. If this button is not added to the counter there is no need to add it.
  6. Add the internal state with the useState() hook. Name it count, for example.
  7. Initialize the state at initialState (the newly-added constant) to be sure that the initial count value is 0 the first time the component is rendered. Remark: when there is no Reset button, 0 can be be directly declared in the useState().
  8. Create the updating function and name it updateCount. This function should modify the current state every time a button is clicked.
  9. In the return of the component function, add three button elements: Increment, Decrement and Reset. Remark: in the below code, I have replaced “Increment” by “+”, “Decrement” by “-“; that’s another possibility…
  10. Add a className to every button and write a little bit of CSS (change the color of the background depending on the button, for example).
  11. In the render, add the onClick attribute on the button element and call the updateCount function passing it count +1, count -1 or initialState to trigger the appropriate state modification when the button is clicked.

A Simple Counter React Functional component Code

The final code of a simple Counter in a react functional component

import { useState } from ‘react’;
function Counter() {
  const initialState = 0;
  const [count, updateCount] = useState(initialState);
  return (
    <div>
      <button
        id=”decrement”
        className=”decrement”
        onClick={() => updateCount(count – 1)}>
        –
      </button>
      <button
        id=”increment”
        className=”increment”
        onClick={() => updateCount(count + 1)}>
        +
      </button>
      <button
        id=”reset”
        className=”reset”
        onClick={() => updateCount(initialState)}>
        Reset
      </button>
      <p> Count : {count}</p>
  </div>
  )
}
ReactDOM.render(<Counter />, document.getElementById(‘counter’));

View the final code of a Simple Counter in a react functional component in a pen

See the Pen
React tricks: write a simple counter with the hook useState
by Coding-Tricks (@coding-tricks)
on CodePen.

Create a Simple counter in a React Functional component – another possibility

This second solution, closer to the class component structure, has been inspired by the following article.

Steps to create a Simple Counter 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 “counter”.
  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 named Counter.
  5. Add the internal state with the useState() hook. Name it count, for example.
  6. Initialize the state at 0.
  7. Create the updating function and name it updateCount. This function should modify the current state every time a button is clicked.
  8. Create three functions below the useState() hook. Name them increment, decrement and reset. Call the updateCount function inside and modify the state passing it count +1, count -1 or 0 to trigger the appropriate state modification depending on the function name.
  9. In the return of the component function, add three button elements: Increment, Decrement and Reset. Remark: in the below code, I have replaced “Increment” by “+”, “Decrement” by “-“; that’s another possibility…
  10. Add a className to every button and write a little bit of CSS (change the color of the background depending on the button, for example).
  11. In the render, add the onClick attribute on the button element and call the corresponding function increment(), decrement() or reset() to trigger the appropriate state modification when the button is clicked.

A Simple Counter React Functional component Code

The final code of a simple Counter in a react functional component

const { useState } = React;
function Counter() {
    const [count, updateCount] = useState(0);
    const increment = () => {
        updateCount(count => count + 1);
    };
     
    const decrement = () => {
        updateCount(count => count – 1);
    };
     
    const reset = () => {
        updateCount(0)
    }
    return (
      <div>
        <button
          id=”decrement”
          className=”decrement”
          onClick={decrement}>
          –
        </button>
        <button
          id=”increment”
          className=”increment”
          onClick={increment}>
          +
        </button>
        <button
          id=”reset”
          className=”reset”
          onClick={reset}>
          Reset
        </button>
        <p> Count : {count}</p>
    </div>
    )
  }
ReactDOM.render(<Counter />, document.getElementById(‘counter’));

In conclusion

As a result, we can say that it is possible to create a Simple Counter 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 build a controlled input in a class component and… in a functional component!

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