Your Cart

Simple Input Form in React

Here’s how to create a basic form that takes in some user input and sends it off to a backend server. I’ve kept the sample up to date for React’s best practices in 2021, along with some comments to help you customize it for your needs.

import React, { useState, useEffect } from "react";import * as ReactDOM from 'react-dom'const axios = require('axios');const App = () => {  // One state variable will hold the users input, and one for  // the servers response  const [input, setInput] = useState("placeholder input");  const [status, setStatus] = useState("");  const handleSubmit = (evt) => {      evt.preventDefault();      axios.get('https://BACKENDAPI.URL?input='+input)      .then(function (response) {        if ( {          setStatus("Request sent successfully and server sent us a response at");        } else {          setStatus("Server didn't respond with anything");        }      })      .catch(function (error) {        if (error.response) {          // request failed, most likely a 400-500 response          setStatus(;        } else {          setStatus("An error occured connecting to the server.")        }      })  }    return (    <div>     <h1>Sample Input Form</h1>     <form onSubmit={handleSubmit}>        <label>          Please enter in a word:           <input             type="text"             name="word"            value={input}            onChange={e => setInput(}            aria-label="accessibility label"            required            aria-required="true"          />        </label>        <input type="submit" value="Submit"/>      </form>	  // Where the response could go      <div id="status">         {status}      </div>    </div>  );}// boilerplate codeReactDOM.render(  <div className="App">    <App />  </div>,  document.getElementById('root'));