DEV Community


Posted on


Displaying Validation Errors on Frontend (React & Rails)

Image description


Do you want to know how to display your validation errors on the frontend of your application? Then, follow along! If you have your backend set up properly, you should have a private method in your application controller that displays an object with the key, errors. It should look something like this:

class ApplicationController < ActionController::API
    rescue_from ActiveRecord::RecordInvalid, with: :invalid



def invalid(e)
    render json: { errors: e.record.errors.full_messages }, 
    status: :unprocessable_entity
Enter fullscreen mode Exit fullscreen mode

Displaying Errors on Frontend

Now that you have your backend set up, we can move to the frontend to display these errors for the user. In the component where we would like our errors to be shown, we will need set a state for these errors with an initial value as an empty array ([]).

import React, {useState, useEffect} from 'react';

export default function OurComponentFunction() {
   const [errors, setErrors] = useState([])
Enter fullscreen mode Exit fullscreen mode

Then, wherever you are fetching the data for which you want the errors to be displayed, you will need to create an if statement. The if statement will state that if there are errors associated with the data, then you will set the errors state with those specific errors. If there are no errors, then the frontend will carry on as expected and display the data needing to be displayed. In the example below, we fetching from "food" and trying to create a new food post.

function handle Submit(e) {
  fetch("/food", {
     method: "POST", 
            headers: {
               "Content-Type": "application/json",
                accepts: "application/json",
            body: JSON.stringify({
               name: name, 
               category: category
            .then((r) => r.json())
            .then((data) => {
                if(data.errors) {
                } else {
Enter fullscreen mode Exit fullscreen mode

Now, that we have our errors being set in the errors state, we need to render it so that it can be shown on the application browser for the user. We will need to map through all the errors in the errors state so that we can return each error individually in an element tag of your choice. In the example below, we are using the 'p' tag.

return (
   { => {
       return <p>{error}</p>
Enter fullscreen mode Exit fullscreen mode


Finally, you have the tools and knowledge to try displaying your own errors on your application browser for the user to see! Go ahead and give it a try!

Oldest comments (0)

Advice For Junior Developers

Advice from a career of 15+ years for new and beginner developers just getting started on their journey.