React http Post Request Example

04-Apr-2023

.

Admin

React http Post Request Example

Hello Guys,

This article is focused on react native http post request. This article goes in detailed on react send http post request. if you want to see example of react api post method then you are a right place. if you have question about react fetch post api then i will give simple example with solution.

First you have to create form for send data in post method. then you have to define state and defind all the fields name in state. after that you have to create change event function for store data in state. when you submit form at that time create submit function for fire post api using fetch function. in this function we must pass headers "Content-type": "application/json; charset=UTF-8".

React js Post Request API Example


/src/App.js file

import React from 'react';

import './App.css';

import PostApi from './PostApi';

function App() {

return (

<div>

<PostApi />

</div>

);

}

export default App;

/src/PostApi.js file

import React from 'react'

class PostApi extends React.Component{

constructor(){

super();

this.state = {

title:null,

body:null,

userId:1,

}

this.handleInputChange = this.handleInputChange.bind(this);

}

handleInputChange(event) {

const target = event.target;

var value = target.value;

const name = target.name;

this.setState({

[name]: value

});

}

submit(){

let url = "https://jsonplaceholder.typicode.com/posts";

let data = this.state;

fetch(url,{

method:'POST',

headers: {

"Content-type": "application/json; charset=UTF-8"

},

body:JSON.stringify(data)

}).then((result)=>{

result.json().then((res)=>{

console.warn('res',res)

})

})

}

render(){

return(

<div>

<div class="row">

<div class="col-md-6 offset-md-3">

<br /><br />

<h3>Post Request Form</h3><br />

<div class="form-row">

<div class="form-group col-md-6">

<label>Title :</label>

<input type="text" class="form-control" name="title" onChange={this.handleInputChange} />

</div>

</div>

<div class="form-row">

<div class="form-group col-md-12">

<label>Body :</label>

<textarea name="body" class="form-control" onChange={this.handleInputChange} />

</div>

</div>

<div class="form-row">

<div class="col-md-12 text-center">

<button type="submit" class="btn btn-primary" onClick={()=>this.submit()}>Submit</button>

</div>

</div>

</div>

</div>

</div>

)

}

}

export default PostApi;

I hope it can help you...

#React.js