🚀 Introducing Actions: Simplifying Form Handling in React 19 💪💪
Hi!, Get ready for a game-changer in form handling with React 19’s new addition: Actions! 🎉
What are Actions?
Actions will revolutionize how we interact with forms. They allow you to integrate actions with the <form/>
HTML tag, replacing the traditional onSubmit
event. This means you can now execute actions directly from your form elements.
Before Actions:
In the past, we relied on the onSubmit
event to trigger actions like searching. However, this was limited to client-side operations only. For example:
<form onSubmit={search}>
<input name="query" />
<button type="submit">Search</button>
</form>
After Actions:
With the introduction of server components, Actions can be executed on the server side. In our JSX, with <form/>, we can drop the onSubmit event and use the action attribute. The value of the action attribute will be a method to submit the data either on the client or server side.
<form action={submitData}>
<label>Name</label>
<input type="text" name='username'/>
<label>Email</label>
<input type="text" name="email" />
<button type='submit'>Submit</button>
</form>
Here, submitData is the action method that can handle data submission either on the client or server side.
You can execute both synchronous and asynchronous operations with actions, streamlining data submission management and state updates. The goal is to make the working with forms and handling data easier.
"use server"
const submitData = async (userData) => {
const newUser = {
username: userData.get('username'),
email: userData.get('email')
}
console.log(newUser)
}
const Form = () => {
return <form action={submitData}>
<label>Name</label>
<input type="text" name='username'/>
<label>Email</label>
<input type="text" name="email" />
<button type='submit'>Submit</button>
</form>
}
export default Form;
In the above code, submitData is the action in the server component. form is a client-side component which is using the submitData as action. submitData will be executed on the server. The communication of the client (form), and server (submitData) components is only possible because of the action attribute.
Stay tuned for more updates, and in the Enhanced Hooks section, we’ll explore three new hooks that will further enhance your form handling experience. Happy coding! 👩💻👨💻