Just like any other web application, in React Js, the primary ways to interact with users are through forms and user input. In this article, I will guide you through handling user input and forms in React JS with detailed explanations and code examples.
In HTML, form elements such as
Let's start by creating a simple form with an input field for a user's name:
import { useState } from "react"
export const Input = () => {
const [value, setValue] = useState()
const handleInputChange = (event) => {
setValue(event.target.value)
}
const handleFormSubmit = (event) => {
alert("You entered : " + value)
event.preventDefault()
}
return (
<form onSubmit={handleFormSubmit}>
<label>
Name: <input type="text" value={value} onChange={handleInputChange} />
</label>
<input type="submit" value="Submit"/>
</form>
)
}
In the above example, the
When handling multiple controlled input elements, you can add a
import { useState } from "react"
export const SignupForm = () => {
const state = {name: '', subscribe: false}
const [value, setValue] = useState(state)
const handleInputChange = (event) => {
const target = event.target
const value = target.type === 'checkbox' ? target.checked : target.value
setValue((oldValue) => {
return {...oldValue, [target.name]: value}
})
}
const handleFormSubmit = (event) => {
alert(value.name + " -> " + value.subscribe)
event.preventDefault()
}
return (
<form onSubmit={handleFormSubmit}>
<label>
Name: <input type="text" name="name" value={value.name} onChange={handleInputChange} />
</label>
<label>
Subscribe: <input type="checkbox" name="subscribe" checked={value.subscribe} onChange={handleInputChange} />
</label>
<input type="submit" value="Submit"/>
</form>
)
}
In this example, the
Also, please pay attention to how I update the state in every input change. The
Form validation is crucial to prevent invalid data submission. Let's modify the previous example and include some form validation.
import { useState } from "react"
export const SignupForm = () => {
const state = {name: '', subscribe: false, errorMessage: ''}
const [value, setValue] = useState(state)
const handleInputChange = (event) => {
const target = event.target
const value = target.type === 'checkbox' ? target.checked : target.value
setValue((oldValue) => {
return {...oldValue, [target.name]: value, errorMessage: validateInput(target)}
})
}
const validateInput = (target) => {
if (target.type !== 'checkbox' && /\d/.test(target.value)) {
return 'Name should not contain numbers'
}
}
const handleFormSubmit = (event) => {
if(!value.errorMessage){
alert("Form submitted")
}
event.preventDefault()
}
return (
<form onSubmit={handleFormSubmit}>
{value.errorMessage && <p>{value.errorMessage}</p>}
<label>
Name: <input type="text" name="name" value={value.name} onChange={handleInputChange} />
</label>
<label>
Subscribe: <input type="checkbox" name="subscribe" checked={value.subscribe} onChange={handleInputChange} />
</label>
<input type="submit" value="Submit"/>
</form>
)
}
In the above example, I validate the name to avoid any digits. If the name contains digits, a message is displayed on the top, preventing the user from submitting the form.
Typically, form data is sent to a server when a form is submitted. That is done using either a
const handleFormSubmit = (event) => {
fetch('saveSubscription/', {
method: 'POST',
body: JSON.stringify(value),
headers: {
'Content-Type': 'application/json'
},
})
event.preventDefault()
}
Note that I Stringify the state value using