Progressively Enhance Handling Your Forms With React.js Server Actions
Progressively Enhance Handling Your Forms With React.js Server Actions
By Dave Bitter
6 min read
A large part of adding interactivity to your applications is through forms. Single Page Applications SPAs have not always handled this part the best. Let’s have a look at how we can use React.js Server Actions to handle your forms progressively enhanced.
- Authors
- Name
- Dave Bitter
- linkedinDave Bitter
- twitter@dave_bitter
- Github
- githubDaveBitter
- Website
- websiteBlog
The issue with the rise of SPAs in the past
When we moved to SPAs in the past we introduced a big issue to our web applications. It didn’t work without JavaScript. Whilst this has been disregarded by many as “our users run the JavaScript on their device”, there is a serious fault in this view.
As Jake Archibald pointed out (back in 2012!), there is a variety of situations where your JavaScript is not available to the user. It may not have been downloaded yet, your CDN might be down and more.
Frameworks like Next.js render your React.js web applications on the server so it will at least render the HTML. Regardless of whether your client-side JavaScript loads, the user will still be able to view the information on the page. This is a must-have feature as before, you would simply see a white page if the React.js bundle did not load.
For some reason, developers seem to think that now we use server-side rendering, our applications are good enough. For static pages without much user interaction, this may be true, but as soon as there is input required from the user, these pages fully rely on the client-side JavaScript. Why is this?
As with SPAs, we just had an empty static HTML file where a JavaScript bundle would inject the whole web application, there was no way of handling a form request. There was no server to handle it. So what did we do? We created a separate API where we would be able to receive and handle requests made from our front end. The added benefit is the performance of not having a full page reload as well. In our front-end, we would intercept the submit event of the form element, gather the data, create the request and finally submit it to our API. In practice, I even saw that developers stopped using the form element altogether as they had no real use for it anymore. Instead, we ended up with a bunch of client-side state to hold the latest data the user inputted and even more to sanitize, validate and send over this data. What a shame!
Using the web platform instead of fighting against it
The big issue I noticed was how much we were fighting against the web as a platform. The web has a standardized way to work with sending over data to a server. Forms! So why would we so actively prevent the default behaviour and implement our own way?
Well, we kind of had to. SPA frameworks were designed to just be a thing static layer that makes requests to APIs. Remember the term Jamstack? Whilst this had advantages like, for instance, making it easier to deploy and work on, it also brought the downsides I mentioned before.
As frameworks like Next.js got popular, we’ve solved the server-side rendering issue of our web applications, but never really focused on the form handling issues. The first time I used a real solution for this was back when I looked into Remix. They provided an elegant way for developers to not just handle forms, but handle them progressively enhanced.
In essence, this approach is simple. Start with making sure you offer a solution that will work for every user. Next, when more functionality is available for the users, enhance the user experience. In the case of forms, being able to submit them to a back-end without the need for any client-side JavaScript. Then, when it is available, handle the request client-side and update the UI.
In my opinion, Remix action functions handle this very well. It offers developers the tools to make it easy to work with the platform and it will make sure to optimize the user experience once client-side JavaScript is available. But providing developers with the tools to work with the web platform shouldn’t be up to Remix, this should already be possible in React.js itself.
React.js Server Actions
The React.js team has been working hard on server-side React.js for the past years. Next to being able to render your components server-side using React.js Server Components, we are finally getting a way in React.js to handle forms on the server properly!
Imagine this form in your React.js web application:
With just the HTML and CSS for this form, the browser will try to submit this to the back-end where no server is handling this POST request. The browser will reload the page and the submitted form data will be in the URL as query parameters:
So what do you do as a developer? You listen for the handle submit event and call preventDefault
on the submit event to handle it yourself:
// page.js
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
const handleSubmit = (event) => {
event.preventDefault()
const formData = new FormData(event.target)
const data = Object.fromEntries(formData)
// Do something with data. Most likely, send it to the server using fetch
// Redirect the user to the new page
router.push('/thank-you')
}
return <form onSubmit={handleSubmit}>...</form>
}
Oh no! Our page is now fully reliant on client-side JavaScript. This is how quickly these things sneak in. So what if we can pass a server-side React.js function to the form to handle the actual form POST request? First, we create an action.js
file with the "use server"
directive where we export our server-side function that handles the form submission.
// actions.js
'use server'
import { redirect } from 'next/navigation'
export async function handleSubmit(formData) {
const data = Object.fromEntries(formData)
// Do something with data. Most likely, store it in your database
// Redirect the user to the new page
redirect('/thank-you')
}
Then, we use that as the callback for the action attribute on the form.
// page.js
import { handleSubmit } from './submit.js'
export default function Page() {
return <form action={handleSubmit}>...</form>
}
That’s it, by slightly altering the way we handle the form, we can now make use of React.js Server Actions and provide Progressive Enhancement out of the box!
Once stable, make this the standard
React.js Server Actions are coming with the upcoming release of React.js 19. You can already use it from Next.js 14. We finally have a solid solution to handling forms in React.js. Make sure to spend an afternoon learning how to use this. Besides handling basic form requests, there are a few other features to improve the user experience surrounding forms. Make sure to read up on these resources to get an overview of what is possible:
- React.js Server Actions: https://react.dev/reference/react/use-server
- Next.js Server Actions: https://nextjs.org/docs/app/api-reference/next-config-js/serverActions
Upcoming events
Drupal CMS Launch Party
Zoals sommigen misschien weten wordt op 15 Januari een nieuwe distributie van Drupal gelanceerd. Namelijk Drupal CMS (ook wel bekend als Starshot). Om dit te vieren gaan we op onze campus een klein eventje organiseren. We gaan die dag samen de livestream volgen waarbij het product gelanceerd wordt. De agenda is als volgt: 17u – 18u30: Drupal CMS livestream met taart 18u30 – 19u00: Versteld staan van de functionaliteiten 19u – 20u: Pizza eten en verder versteld staan van de functionaliteiten Laat ons zeker weten of je komt of niet door de invite te accepteren! Tot dan!
| Coven of Wisdom Herentals
Go to page for Drupal CMS Launch PartyCoven of Wisdom - Herentals - Winter `24 edition
Worstelen jij en je team met het bouwen van schaalbare digitale ecosystemen of zit je vast in een props hell met React of in een ander framework? Kom naar onze meetup waar ervaren sprekers hun inzichten en ervaringen delen over het bouwen van robuuste en flexibele applicaties. Schrijf je in voor een avond vol kennis, heerlijk eten en een mix van creativiteit en technologie! 🚀 18:00 – 🚪 Deuren open 18:15 – 🍕 Food & drinks 19:00 – 📢 Building a Mature Digital Ecosystem - Maarten Heip 20:00 – 🍹 Kleine pauze 20:15 – 📢 Compound Components: A Better Way to Build React Components - Sead Memic 21:00 – 🙋♀️ Drinks 22:00 – 🍻 Tot de volgende keer? Tijdens deze meetup gaan we dieper in op het bouwen van digitale ecosystemen en het creëren van herbruikbare React componenten. Maarten deelt zijn expertise over het ontwikkelen van een volwassen digitale infrastructuur, terwijl Sead je laat zien hoe je 'From Props Hell to Component Heaven' kunt gaan door het gebruik van Compound Components. Ze delen praktische inzichten die je direct kunt toepassen in je eigen projecten. 📍 Waar? Je vindt ons bij iO Herentals - Zavelheide 15, Herentals. Volg bij aankomst de borden 'meetup' vanaf de receptie. 🎫 Schrijf je in! De plaatsen zijn beperkt, dus RSVP is noodzakelijk. Dit helpt ons ook om de juiste hoeveelheid eten en drinken te voorzien - we willen natuurlijk niet dat iemand met een lege maag naar huis gaat! 😋 Over iO Wij zijn iO: een groeiend team van experts die end-to-end-diensten aanbieden voor communicatie en digitale transformatie. We denken groot en werken lokaal. Aan strategie, creatie, content, marketing en technologie. In nauwe samenwerking met onze klanten om hun merken te versterken, hun digitale systemen te verbeteren en hun toekomstbestendige groei veilig te stellen. We helpen klanten niet alleen hun zakelijke doelen te bereiken. Samen verkennen en benutten we de eindeloze mogelijkheden die markten in constante verandering bieden. De springplank voor die visie is talent. Onze campus is onze broedplaats voor innovatie, die een omgeving creëert die talent de ruimte en stimulans geeft die het nodig heeft om te ontkiemen, te ontwikkelen en te floreren. Want werken aan de infinite opportunities van morgen, dat doen we vandaag.
| Coven of Wisdom Herentals
Go to page for Coven of Wisdom - Herentals - Winter `24 editionThe Test Automation Meetup
PLEASE RSVP SO THAT WE KNOW HOW MUCH FOOD WE WILL NEED Test automation is a cornerstone of effective software development. It's about creating robust, predictable test suites that enhance quality and reliability. By diving into automation, you're architecting systems that ensure consistency and catch issues early. This expertise not only improves the development process but also broadens your skillset, making you a more versatile team member. Whether you're a developer looking to enhance your testing skills or a QA professional aiming to dive deeper into automation, RSVP for an evening of learning, delicious food, and the fusion of coding and quality assurance! 🚀🚀 18:00 – 🚪 Doors open to the public 18:15 – 🍕 Let’s eat 19:00 – 📢 First round of Talks 19:45 – 🍹 Small break 20:00 – 📢 Second round of Talks 20:45 – 🍻 Drinks 21:00 – 🙋♀️ See you next time? First Round of Talks: The Power of Cross-browser Component Testing - Clarke Verdel, SR. Front-end Developer at iO How can you use Component Testing to ensure consistency cross-browser? Overcoming challenges in Visual Regression Testing - Sander van Surksum, Pagespeed | Web Performance Consultant and Sannie Kwakman, Freelance Full-stack Developer How can you overcome the challenges when setting up Visual Regression Testing? Second Round of Talks: Omg who wrote this **** code!? - Erwin Heitzman, SR. Test Automation Engineer at Rabobank How can tests help you and your team? Beyond the Unit Test - Christian Würthner, SR. Android Developer at iO How can you do advanced automated testing for, for instance, biometrics? RSVP now to secure your spot, and let's explore the fascinating world of test automation together!
| Coven of Wisdom - Amsterdam
Go to page for The Test Automation Meetup