DEV Community

Justin Bermudez
Justin Bermudez

Posted on

1 1

POST React Form to Server

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: ''
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay