React - Form handler example

less than 1 minute read

The following example shows the basic form submit handling with React

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React from "react"
import axios from "axios"

const Form = ({reloadPage}) => {
  const [text, setText] = useState('')

  const handleSubmit = async event => {
    event.preventDefault()

    const config = {
      headers: {
        "Content-type": "application/json"
      }
    }

    const {data} = await axios.post("/url", JSON.parse(text), config)
    setText('')
    reloadPage()
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Text</label>
      <input type="text" value={text} onChange={e => setText(e.target.value)}>
      <button>submit</button>
    </form>
  )
}

Categories:

Updated: