How to make POST form with React and axios
I have wrote how to implement “ajax” with React before. At this time, I will write how to post the content in view to server. Using axios makes it easier to do it.
Preparation
I will prepare code before main contents. That is below. It is not so difficult.
import React from "react"
import PropTypes from "prop-types"
import axios from "axios"export default class FormComponent extends React.Component { constructor(props){
super(props)
this.state = {
text: ""
}
}
render(){
return(
<div>
</div>
)
}
}
Form View
Firstly, I add form view. That is below.
import React from "react"
import PropTypes from "prop-types"
import axios from "axios"export default class FormComponent extends React.Component { constructor(props){
super(props)
this.state = {
text: ""
}
} handleChange(){
}
postContent(){ } render(){
return(
<div>
<input type="text" value={this.state.text} onChange={this.handleChange.bind(this)}></input>
<button onClick={this.postContent.bind(this)}post</button>
</div>
)
}
}
At any rate, You can see the form. However, it doesn’t act properly. We must implement postContent and handleChange.
How to deal with posted contents
Next, I insert contents into the database. That is below.
handleChange(e){
this.setState({text: e.target.value})
}postContent(){
axios.post("URL", {
title: this.state.text,
})
}
If textfield’s contents is changed, state is changed too. Also, postContents has a role to send parameter to server. We can use axios here. axios’ method is post and parameter name put as “title” to state.text. “URL” is where these parameters are sent to.
Deleting contents after post
After sending contents into database, those should not be remained in the text field. Therefore, we must delete them. How to do it is below.
postContent(){
self = this
axios.post("URL", {
title: this.state.text
})
.then(function (response) {
self.deleteText()
})
}deleteText(){
this.setState({text: ""})
}
“self = this” is added. Why? It is because “this” becomes undefined after “.then”. deleteText has a role to replace contents with null string. By doing so, input contents’ value becomes null.
Wrap up
The completed code is below.
import React from "react"
import PropTypes from "prop-types"
import axios from "axios"export default class FormComponent extends React.Component {constructor(props){
super(props)
this.state = {
text: ""
}
}handleChange(){
this.setState({text: e.target.value})
}
postContent(){
self = this
axios.post("URL", {
title: this.state.text
})
.then(function (response) {
self.deleteText()
})
}deleteText(){
this.setState({text: ""})
}render(){
return(
<div>
<input type="text" value={this.state.text} onChange={this.handleChange.bind(this)}></input>
<button onClick={this.postContent.bind(this)}post</button>
</div>
)
}
}
Axios makes it easier to connect front with back. That is great!