From React Class component to Functional component with hooks

How to create a Controlled Form with React ?

Now that we know how to  Toggle an element and Create a Simple Counter, Control an Input, learn how to create a Controlled Form. This sixth episode, has been inspired by a freeCodeCamp challenge I have a little bit modified by adding a Reset button and displaying the input value in a added paragraph instead of in a heading.

We will discover what is a controlled form before building one in class and functional components.

We will see how a controlled form can help us to consume less memory comparing to having a controlled input only.

Summary

Reminder: as usual, before starting coding, just check that React, React.Dom libraries and Babel preprocessor have been installed.

What is a controlled form?

React controlled form definition

A form is controlled by React when the submit button state is moved into the component state. Obviously, the input and textarea are also controlled.

The React controlled form structure

  • The component state has input (, textarea) and submit properties initialized with an empty string as the value representing what the user types in the input.
  • A method is triggered when the input value changes.
  • This method updates the state input property value with the event value received as argument.
  • Another method is triggered when the submit button is clicked.
  • This second method updates the submit state property by assigning it the modified input value.

In this article, we will display the state submit property value to prove that the input and the form are controlled by React!

Create a Controlled Form in a React Class component.

Before creating a Controlled Form in a React Functional component, let’s create it in a class component.

Steps to create a controlled form 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 “controlled-form”.
  3. Create a class component which extends React.Component. Name it Myform, for example.
  4. Add the internal state in the constructor with this.state.
  5. Initialize the state input property at ” (empty string).
  6. Initialize the state submit property at ” (empty string).
  7. Create a handler method named handleChange and pass it the event as argument so when the input value is modified by the user the state input value is set with the event.input.target.
  8. Create a handler method named handleSubmit and pass it the event as argument so when the form is submitted by the user the state submit value is set with the state input value. Remark: do not forget to call the event.preventDefault() to prevent the default form submit behaviour which will refresh the web page!
  9. Do not forget to add the necessary bindings for the above created methods in the constructor.
  10. In the render, create the form.
  11. Assign it the onSubmit attribute to trigger the handleSubmit method when the user submit the form.
  12. Insert an input field.
  13. Assign the state input property to its value attribute.
  14. Assign an onChange attribute to trigger the handleChange method when the user types something inside the input field.
  15. In the render, below the form, add a heading h2 which contains the “Controlled Form” text.
  16. In the render, below the heading, add a paragraph which displays the state submit property value once the form has been submitted.

A Controlled Form React class component code

The final code of a Controlled Form in a React class component

class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
         input: ”,
            submit: ”
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(event) {
        this.setState({
            input: event.target.value
        });
    }
    handleSubmit(event) {
        event.preventDefault(),
        this.setState(state => ({
            submit: state.input
        }))
    }
    render() {
        return (
            <div>
                <form onSubmit={this.handleSubmit}>
                    <input
                        value={this.state.input}
                        onChange={this.handleChange}
                    />
                    <button type=’submit’>Submit</button>
                </form>
                <h2>Controlled form</h2>
                <p>{this.state.submit}</p>
            </div>
        );
    }
}
ReactDOM.render(<MyForm />, document.getElementById(‘controlled-form’));

View the final code of a controlled form in a React class component in a pen

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

Create a Controlled Form in a React Functional component with the hook useState

Let’s create this Controlled Form in a React.js functional component whose structure is close to the newly-created one in a class component. I have added a reset button in this component…

Steps to create a Controlled form 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 “input”.
  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 MyForm.
  5. Add an internal state property with the useState() hook. Name it input, for example.
  6. Initialize the state at ” (empty string).
  7. Add a second internal state property named submitted with the useState() hook.
  8. Initialize it at too.
  9. In the return of the component function, add a form.
  10. Assign an onSubmit attribute which trigger the handleSubmit function.
  11. Create the handleSubmit function and pass it an event as argument. Call the setSubmitted function to update the submitted state property and pass it the input state property value. Remark: Do not forget to call event.preventDefault() to avoid the default form submit behavior which will refresh the web page.
  12. Insert an input field in the form.
  13. Assign it the state input as value attribute.
  14. Add the onChange attribute which will trigger the handleChange function when the user types something in the input field.
  15. Create the handleChange function and pass it an event as argument. Call the setInput function and pass it the event.target.value to update the input state property value.
  16. Add the submit button.
  17. Just to add some difficulty and fun, add a second button named Reset.
  18. Add the onClick attribute which will trigger the handleReset function when the user clicks on the Reset button.
  19. Create the handleReset function and pass it an event as argument.
  20. This function will reset not only the paragraph but also the input field. Both of them must be void after the resetting. To void the paragraph, the submitted value must equals ”. To void the input, the input value must be ” too. One solution is to create a constant named initialValue which equals ”. Then initialize both input and submitted state properties with initialValue.
  21. Finally inside the handleReset function call the setInput and setSubmitted function and pass them the initialValue as argument.
  22. In the render, below the form, add a heading h2 element whose text is “Controlled form”.
  23. In the render, below the heading, add a paragraph element to display the input current state value once the form has been submitted.

A Controlled Form React Functional component Code

The final code of a controlled form in a react functional component

const {useState } = React;
const MyForm = () => {
    const initialInput = “”;
    const [input, setInput] = useState(initialInput);
    const [submitted, setSubmitted] = useState(initialInput);
   
    const handleChange = (event) => {
        setInput(event.target.value);
    };
    const handleSubmit = (event) => {
        event.preventDefault();
        setSubmitted(input);
    };
   
    const handleReset = (event) => {
        setInput(initialInput); // reset input
        setSubmitted(initialInput); // reset <p></p>
    }
    return (
        <div>
            <form onSubmit={handleSubmit}>
                <input
                    value={input}
                    onChange={handleChange}
                />
                <button type=”submit” className=”submit”>Submit</button>
                <button className=”reset” onClick={handleReset}>Reset</button>
            </form>
            <h2>Controlled Form</h2>
            <p>{submitted}</p>
        </div>
    )
}
ReactDOM.render(<MyForm />, document.getElementById(‘controlled-form’));

View the final code of a Controlled Form in a react functional component in a pen

See the Pen
React tricks: Create a controlled form with the hooks useState and useEffect
by Coding-Tricks (@coding-tricks)
on CodePen.

In conclusion

Once again, we have proved that it is possible to create a Controlled Form either in a class or a functional React component.

In this controlled form, every time a new letter is typed the state is updated and the letter displayed in the input. But, if we compare to the previous challenge/article, the letters are not displayed one by one but at one go after the form is submitted. As a matter of fact, we consume less memory than in the previous article talking about the controlled inputs. However there are other solutions we will discover later…

In the next episode, we will discover a new hook: useEffect.

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