How to create a controlled component form with React

In this tutorial we will go over how to build a controlled component form in react. A controlled component form is essentially a form that works through the React state.
The rationale for this is that all forms maintain their own state to some degree which is separate from the React state. To keep in line with React’s single source of truth principle we can make the form work through the React state.
The code below demonstrates how. The basic methodology is to have 2 properties of state. One for the form submit and one for the text change.
Then have 2 separate functions for each state change function. The text change function can be passed to the onChange event of the input tag and the submit function can be passed as a
reference to the onSubmit event of the form.
The text data for the text change function can be accessed by event.target.value from the input element.
The text data for the form submit can be accessed by event.target.text1.value where text1 is the id of the input element. We also want to include event.preventDefault() in order to prevent the browser from reloading when submitting the form. Since React is a single page app reloading the browser is unnecessary and will actually cause us to lose our state.
More information can be found here.
https://reactjs.org/docs/forms.html

iimport React, { useState } from ‘react’;


const HooksForm1 = () => {

    const [valueChangesetValueChange] = useState()

    const [valueSubmitsetValueSubmit] = useState()
    const handleChange = (event=> (
        setValueChange(event.target.value)
    );
    const handleSubmit = (event=> {
        event.preventDefault();
        setValueSubmit(event.target.text1.value)
    };
    return (
        <div>
            <h1> React Hooks Form </h1>
            <form data-testid=“form” onSubmit={handleSubmit}>
                <label htmlFor=“text1”>Input Text:</label>
                <input id=“text1” onChange={handleChange} type=“text” />
                <button type=“submit”>Submit</button>
            </form>
            <h3>React State:</h3>
            <p>Change: {valueChange}</p>
            <p>Submit Value: {valueSubmit}</p>
            <br />
        </div>
    )

Leave a Comment

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