ReactJS REST API POST Example

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. The full documentation is available at https://reactjs.org/. In this tutorial I will show you how to create new resource (REST API POST) using React JS framework. The article, ReactJS REST API GET Example, will use sample ready made available REST API https://jsonplaceholder.typicode.com/posts for testing purpoase. You can also create and deploy your own service using PHP, Codeigniter or Spring, Jersey etc. and call using React JS framework. Here you will see only POST example (other HTTP verbs are GET, PUT, DELETE, HEAD, OPTIONS etc.).

You may also like to read ReactJS REST API GET Example ReactJS REST API PUT Example ReactJS REST API DELETE Example

Prerequisites

Knowledge of HTML and JavaScript

Creating React application

Please read the tutorial Create React JS Application before moving forward.

Example

Now we will see step by step how to implement the example using React JS or React framework.

Now delete everything from the directory <drive/folder>/react-rest/src but do not delete src directory.

Create RestController.js file under src directory with below content. Notice that you need to import the required module or component such as import React from 'react'. I have also declared user array to fill later with REST response data from https://jsonplaceholder.typicode.com/posts. Learn about componentDidMount() here at https://reactjs.org/docs/react-component.html.

The POST URI creates a new resource in the server and returns a response in the below format

{
  id: , //id of the new post -> coming from server
  title: '', //title of the new post -> user has input
  body: '', //body of the new post -> user has input
  userId: //user id of the new post -> who input
}

RestController.js

import React from 'react';

class RestController extends React.Component {
	constructor(props) {
		super(props);
		this.state = {user: []};
	}
	
	componentDidMount() {
		fetch('https://jsonplaceholder.typicode.com/posts', {
			method: 'POST',
			body: JSON.stringify({
				title: 'New title added',
				body: 'New body added. Hello body.',
				userId: 2
			}),
			headers: {
				"Content-type": "application/json; charset=UTF-8"
			}
		}).then(response => {
				return response.json()
			}).then(json => {
				this.setState({
					user:json
				});
			});
	}
	render() {                            
		return (
			<div>
				<p><b>New Resource created in the server as shown below</b></p>
				<p>Id : {this.state.user.id}</p>
				<p>Title : {this.state.user.title}</p>
				<p>Body : {this.state.user.body}</p>
				<p>UserId : {this.state.user.userId}</p>
			</div>
		)
	}
}

export default RestController;

Export the RestController at the end of the RestController class so that we can use this class in other modules such as we have used it in below index.js file.

Finally create index.js file under src directory to start up the application.

Here we have called <RestController /> component and writing the output of the RestController to the div id marked as “root”.

Open the file <drive/folder>/react-rest/src/public/index.html, you will find a div with “root” id. Update the title in this file as “React – REST API POST Example”.

import React from 'react';
import ReactDOM from 'react-dom';
import RestController from './RestController'

ReactDOM.render(
                ,
                document.getElementById('root')
);

Now execute the command npm start from command prompt and you will see the response data after creating the new resource in the server from https://jsonplaceholder.typicode.com/posts in browser at http://localhost:3000

New Resource created in the server as shown below

Id : 101
Title : New title added
Body : New body added. Hello body.
UserId : 2

Final result on the browser

react rest post example

Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin

Leave a Reply

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