How to use the useActionData hook in React Router
The useActionData hook is a route action React hook, which provides a mechanism to manipulate data using plain HTML and HTTP. The complexity pertaining to asynchronous UI and validation is abstracted away by the React Router. This hook returns a value from either the data from the previous navigation’s action result or undefined if no submission was made. Data can be submitted through various methods like post, put, or patch. This hook is useful during form validation: it can raise an error if the form isn’t correctly filled and prompt the user to try again.
General syntax
The following code snippet shows how to use the useActionData hook in any component (it’s used in a way similar to other React hooks):
import { useActiondata } from "react-router-dom";function my_favourite_place_component(){const form_action_data = useActionData();}
Use cases of the useActionData hook
In the coming section, we’ll see the use cases of useActionData.
1. useActionData for form input validation
React provides a number of ways to perform form input validation. In React, input validation is possible through the useFormContext hook’s register function. However, we’ll see how to do this in the coming sections with the useActionData hook. It allows us to access our submitted form data and corresponding errors inside a component. Before user-entered data can be further manipulated, we must ensure that the input data is correct and valid. For validation purposes, we can add multiple constraints on the data. For example, an employee’s age should not exceed a hundred years could be a constraint. This way, useActiondata hook provides server-side input validation.
2. Redirection
After the form is submitted, the useActionData hook can redirect the user to another page. For example, after form submission, we might want the user to return to the home page. For this purpose, we’ll include a redirect("/home_page_path") statement at the end of our action function. This way, not only is a user’s data validated, but the user can return to other activities on the home page at the end of the form submission.
Example
Let’s look at a more widely used use case of the useActionData hook, form input validation.
The following example demonstrates how to perform form input validation using the useActionData hook. It contains two components:
EducativeForm(): It renders a form for entering employee details and displays any errors.EducativeFormAction(): It handles form submissions, validates input, and returns errors, if any.
Both components use useActionData and Form from react-router-dom.
import './App.css';
import { EducativeForm, EducativeFormAcion } from './EducativeForm';
import {Route,createBrowserRouter,createRoutesFromElements, RouterProvider} from "react-router-dom";
import Layouts from './layouts/Layouts';
function App() {
const educative_router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<Layouts /> } >
<Route path="/educative_forms" element= {<EducativeForm/>} action={EducativeFormAcion}/>
</Route>
)
)
return (
<>
<div className="App">
<RouterProvider router={educative_router} />
</div>
</>
);
}
export default App;Code explanation
In the EducativeForm.jsx file:
Lines 2–4: We access the errors generated with
useActionData, if any, after the user enters data. TheuseActionDatahook saves the errors in theeducative_errorsobject insideEducativeForm.Lines 6–12: We create a form to display to the user. The form has two input tags, one for taking the name as input and the other for age.
Lines 16–17: We verify whether the
educative_errorsis not null; if true, we access any error associated with the employee’s name usingeducative_errors.educative_employee_name. Similarly, we useeducative_errors.educative_employee_ageto display the error generated while inputting age.Lines 22–26: We create an async function called
EducativeFormAction()that handles form data and input validation. It receives a request object as an argument and retrieves the form data with therequest.formData()method. The stored data, which is saved ineducative_data, is used to save the employee’s name and age in theeducative_employee_nameandeduactive_employee_ageobjects, respectively. We also initialize an emptyeducative_errorsobject to store all our error messages. These error messages will be displayed to a user when he/she inputs the wrong name or address.Lines 27–32: We create custom input validation for the form input. In the first
ifcondition, we check ifeducative_employee_nameis a number or empty. If true, we assign the error message"Name must be a string, enter your name!"toeducative_errors.educative_employee_name. Similarly, if age is not a number or not between18to70, or if the field is empty, we assign"Invalid age, must be a number between 18 and 70"toeducative_errors.educative_employee_age. These errors will be shown to the user within the form.Lines 33–36: This condition checks if there are any errors stored in the
educative_errorsobject. If there are errors, it returns the object containing them. Otherwise, it returnsnull.
In App.js , we have:
Lines 6–13: We create our router object called
educative_router. It contains a path/educative_forms. Against this, we display theEducativeFormcomponent and the action function that runs after form submission isEduactiveFormAction.
Conclusion
useActionData is a simple and effective way of accessing form data after submission. We can return this data to other components, for example, to display it back to the user or for input validation, as shown above.
Free Resources