The Most Simple React Form Example

Quin’darius Lyles-Woods
2 min readApr 13, 2021

Setup

  • in a terminal enter: npx create-react-app reactformexample
  • delete everything in the src and public folder
  • add index.html to the public folder
  • add index.js to the src folder

Code

index.js

import react, {useState} from 'react';
import reactdom from 'react-dom';

function Form() {
const [value, setValue] = useState("");
const handleSubmit = (submittedValue) =>
{
alert(`You Submitted: ${value}`)
}

return (

<form onSubmit={(handleSubmit)}>

<label>
Value:

<input
type="text"
value={value}
onChange={e => setValue(e.target.value)}
/>

</label>

<input type="submit" value="Submit" />

</form>
);
}

reactdom.render
(
<Form/>,
document.getElementById('root')
)

index.html

<div id="root"></div>

Running the Application

  • Within the reactformexample folder in the terminal
  • enter the command: npm start

Code Breakdown

import React, { useState } from 'react';

UseState

The name of the hook the is bundled with react

import reactdom from 'react-dom';

What allows react to write to the DOM

function Form()
{
.
.
.
}

A reusable react component that returns some JSX

const [value, setValue] = useState("");

this declares a new variable that we can change over time.

value = name of the variable

setCount = a State that you can set

const handleSubmit = (submittedValue) => 
{
alert(`You Submitted: ${value}`)
}

Shows an alert message

<form onSubmit={(handleSubmit)}>

onSubmit is something to put a function in to do what we need.

You might be tempted to put the function right in the form but it doesnt work well.

onChange={e => setValue(e.target.value)}

Whenever something is changed set the value

<input type="submit" value="Submit" />

A button to submit to

return(
.
.
.
);

Gives the content of the function to the whatever is calling it.

reactdom.render
(
.
.
.
);

Puts the JSX into our index.html, with the proper contents.

document.getElementById('root')

This is the content that puts the html in our index.html.

--

--

Quin’darius Lyles-Woods
0 Followers

CS Major at Kennesaw State, building application and taking domains