Building forms using React can be done in a variety of ways. The two most common would be controlled components and uncontrolled components. You can also add state management using Redux and Mobx but for this tutorial will be using just plain React. We’ll be covering controlled forms because of the limited use cases of where uncontrolled would be appropriate. You can access the full Github Code Snippet here and gain access to our courses here.

React Forms with Controlled Components

Controlled Components are the most common way of building out a form using React. You take a value of a form element, set it as the state and if you want to apply any updates, you set an event handler to that input field and change it.

Inside of my form, I have a name attribute for each input field and an event handler.

render(){
        return(
            <Form onSubmit={this.handleSubmit}>
                <FormGroup row>
                    <Label for="title" sm={2}>Title</Label>
                    <Col sm={10}>
                        <Input type="text" name="title" id="title" placeholder="Title" onChange={this.handleInputChange}/>
                    </Col>
                </FormGroup>
                <FormGroup row>
                    <Label for="body" sm={2}>Body</Label>
                    <Col sm={10}>
                        <Input type="textarea" name="body" id="body" placeholder="Body" onChange={this.handleInputChange}/>
                    </Col>
                </FormGroup>
                <FormGroup check row>
                    <Col sm={{ size: 10, offset: 2 }}>
                        <Button>Submit</Button>
                    </Col>
                </FormGroup>
            </Form>
        )
    }

Once you have a form built out, you can add your logic for changing your component state based on input field changes.

handleInputChange(event) {
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;

        const name = target.name;

        this.setState({
            [name]: value
        });
        //this.setState({post: {[name]: value}})

    }

If you look above, the code handleInputChange method takes in the event as a parameter. We then get the target which is the field currently being modified. We take the target and get that value, this can be from a radio button or a text field and any other type of input field. We also get the name of the target. Name sure that the name in your input field matches the name of the key that you want to be in your component state. Having the name being generated off of the target.name is a way to practice DRY and not create a new event handler for every input field in your component.

Submitting a React Form

Next, we have to submit our form using another event handler.

handleSubmit(event) {
        var post = {title: this.state.title, body: this.state.body, userId: this.props.userid };
        createPost(post).then(res => console.log(res));
        event.preventDefault();
    }

What this does is create an object based on your specified state. In this case, we are creating a post. Then underneath we have a method that takes in that post variable and creates in using an outside service. Once that is done, we prevent the default action which in the case of a form submit is a page refresh.

Here is the full code snippet

import React, {Component} from 'react';
import { Col, Button, Form, FormGroup, Label, Input, FormText } from 'reactstrap';
import {createPost} from "../../services/PostsService";

class PostForm extends Component{
    constructor(props){
        super(props)
        this.state = {post: {title: "Blank Title", body: "Blank Body"}}

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleInputChange(event) {
        const target = event.target;
        const value = target.value;

        const name = target.name;

        this.setState({
            [name]: value
        });

    }

    handleSubmit(event) {
        
        var post = {title: this.state.title, body: this.state.body, userId: this.props.userid };
        createPost(post).then(res => console.log(res));
        event.preventDefault();
    }

    render(){
        return(
            <Form onSubmit={this.handleSubmit}>
                <FormGroup row>
                    <Label for="title" sm={2}>Title</Label>
                    <Col sm={10}>
                        <Input type="text" name="title" id="title" placeholder="Title" onChange={this.handleInputChange}/>
                    </Col>
                </FormGroup>
                <FormGroup row>
                    <Label for="body" sm={2}>Body</Label>
                    <Col sm={10}>
                        <Input type="textarea" name="body" id="body" placeholder="Body" onChange={this.handleInputChange}/>
                    </Col>
                </FormGroup>
                <FormGroup check row>
                    <Col sm={{ size: 10, offset: 2 }}>
                        <Button>Submit</Button>
                    </Col>
                </FormGroup>
            </Form>
        )
    }
}

export default PostForm;
Create React Form

Create React Form

Conclusion

Creating forms using React are simple. You can even extend them by adding state management like Redux and React. You can see the full GitHub code example here as well as several courses here.

Codebrains Newsletter

Get weekly dev news and tutorials.

Powered by ConvertKit