DEV Community

Cover image for All about router guards in react js
Amrita-padhy
Amrita-padhy

Posted on

All about router guards in react js

What is router guard
In React applications, a router guard is a mechanism for controlling navigation based on certain conditions or requirements. The goal is to prevent or allow navigation to specific routes based on certain criteria. This is often used to implement features such as
1-authentication checks,
2-form submission confirmation,
3-preventing users from navigating away with unsaved changes.

How to implement
react-router-dom library is commonly used for handling routing. The Route component from react-router-dom allows you to render different components based on the current URL. A router guard can be implemented by using the useNavigate hook.

Use case
Here is a small usecase example for implementing router guards . whenever user is filling a form , and user did not submit it and click cancel then user can not redirect directly to previous route.
IN this case a conformation modal will show and ask the user wheather you want to leave the page or continue

// Guard.js
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Dialog } from "primereact/dialog";
import { Button } from "primereact/button";

const Guard = ({ showModal, setShowModal }) => {
  const [confirmNavigation, setConfirmNavigation] = useState(false);
  const navigate = useNavigate();

  const onOkClick = () => {
    if (confirmNavigation) {
      setShowModal(false);
      navigate("/");
    }
  };

  const onDialogCancel = () => {
    setShowModal(false);
    setConfirmNavigation(false);
  };

  const onDialogProceed = () => {
    setConfirmNavigation(true);
    onOkClick();
  };

  return (
    <div>
      <Dialog
        header="Confirmation"
        visible={showModal}
        onHide={onDialogCancel}
        style={{ padding: "15px", width: "600px" }}
        footer={
          <div>
            <Button
              label="No"
              icon="pi pi-times"
              onClick={onDialogCancel}
              className="p-button-text"
              style={{ padding: "5px" }}
            />
            <Button
              label="Yes"
              text
              icon="pi pi-check"
              onClick={onDialogProceed}
              style={{ padding: "5px" }}
            />
          </div>
        }
      >
        <p style={{ padding: "15px" }}>Do you want to leave the page?</p>
      </Dialog>
    </div>
  );
};

export default Guard;

Enter fullscreen mode Exit fullscreen mode

On cancel button click this Guard component will show. and it will prevent the user to directly go back to previous route .

Top comments (0)