Post HTML Form with Ajax in React

Here in this blog, I am going to show you how you can post HTML form with ajax in React. As react is a UI component framework, we have to use some third party library to post form with ajax. I am using react-axios for this example. You may find more about axios here https://www.npmjs.com/package/react-axios . Please note you have installed this package npm install react-axios

Below is the file PostForm.js. For this example, I am using dummy rest API https://reqres.in/ . You may also use this dummy REST API for quick testing.

In below for there are two controls 1. Name 2. Food

Food is multi-select and we manage reactjs state variable to manage HTML control values. Below are the steps that are required to manage HTML control

  1. Define the state variable, because HTML control state managed by reactjs state variables. We have defined food[] as an array because food is multi-select.
  2. We need to define the change handler that would set the state variable. For multi-select see handleChange. When a value changes this handler updates values in food[] array.
  3. set value attribute to a variable. value={food} set value back to select control.

handleSubmit is form submit handler and here we have used axios for the POST request. If the request is a success (201 created in this case) then show the success message in div. We have used state variable message for this purpose.

import React , { Component } from 'react'
import axios from 'axios'

class PostForm extends Component{

    constructor(props){
        super(props)
        this.state= {
            name:'',
            food:[],
            message:''
        }
       
    }

    handleHtmlControlChange = (event) => {
        this.setState({ [event.target.name]:event.target.value   })
    }

    handleChange = (event) => {
        this.setState({food: Array.from(event.target.selectedOptions, (item) => item.value)});
      }

    handleSubmit  = (event) => {
        console.log(this.state);
        event.preventDefault();
        axios.post('https://reqres.in/api/users',this.state).
        then( response => {
            console.log(response)
            this.setState({message:"User created successfuly."})
        }).catch( error => {
            console.log(error)
        })
    }

    render(){
        const { name,food,message} = this.state
        return(
            <div>
                <div className="success">{message}</div>
                <form onSubmit={this.handleSubmit}>
                    <div>
                        <label className='label'>Name : </label>
                        <input type='text' name="name" value={name} onChange={this.handleHtmlControlChange} />
                    </div>
                    <div>
                        <label  className='label'>Your Favorite Food : </label>
                        <select name="food" value={food} multiple={true} onChange={this.handleChange}>
                            <option value="pizza">Pizza</option>
                            <option value="pasta">Pasta</option>
                            <option value="burger">Burger</option>
                            <option value="sandwich">Sandwich</option>
                        </select>
                    </div>
                    <button type='submit'>Submit</button>
                </form>
            </div>
        )
    }
}

export default PostForm

In App.js import PostForm class using import PostForm from './components/PostForm' . I have created this class inside the component folder. Finally, create a tag <PostForm></PostForm> in App.js

This is how you can post ReactJS HTML Form with Ajax. Here is the snapshot of form.

Post HTML form with AJAX in React

That’s it. This is how you can post HTML form with ajax in React.

For other helping, code snippets have a look at our Articles List.

Please share this post:
Distinguished Engineer Java, PHP, Spring, Mysql
Posts created 11

One thought on “Post HTML Form with Ajax in React

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: