Using React to send FORM data to any given server.
I will show an example with 1 input in the form.
Need the name of our input in state
state = {
name: ''
}
We now need event handlers to set our state and the actual post request.
In the handleSubmit, we want to fetch the endpoint that we set our server to be at. For example localhost:3000.
handleChange = (e) => {
this.setState({[e.target.name]: e.target.value})
}
headers = {
'Content-Type': 'application/json',
Accept: 'application/json'
}
handleSubmit = (e) => {
e.preventDefault()
fetch('your server endpoint here', {
method: 'POST,
headers: headers,
body: JSON.stringify({
name: name
})
)}
.then(response => response.stringify())
.then(data => console.log("successfully sent: ", data)
}
How the form looks
<form onSubmit={this.handleSubmit}>
<label>Name:</label>
<input
type="text"
value={this.state.value}
name="name"
onChange={this.handleOnChange}
/>
<input type="submit" value="submit" />
</form>
Top comments (0)