Home > Software engineering >  useNavigate hook with multiple choices?
useNavigate hook with multiple choices?

Time:06-17

this is my button component:

import React from "react";
import { useNavigate } from "react-router";
import { KeyboardArrowLeft } from "@material-ui/icons";
import { Button } from "@mui/material";
import "./Buttons.css";

export const BackButton = () => {
  const navigate = useNavigate();
  return (
    <Button
      onClick={() => navigate(-1)}
      className="back-button"
      size="large"
      startIcon={<KeyboardArrowLeft />}
    />
  );
};

It is currently used in every route that I have. In a few routes I want the button to navigate back to -2 pages (but I want -1 do be default), do I rewrite the code in the onClick event or how do I make this possible?

CodePudding user response:

You can get location with useLocation hook and use it in your onClick.

import { useLocation, useNavigate } from "react-router-dom";

export const BackButton = () => {
  const navigate = useNavigate();
  const location = useLocation();

  return (
    <Button
      onClick={() => (location.pathname === "x" ? navigate(-2) : navigate(-1))}
    />
  );
};

CodePudding user response:

You can create a prop with a default value of 1, then use that prop when you call navigate():

import PropTypes from 'prop-types';

const BackButton = ({navigateTo = 1}) => {
  const navigate = useNavigate();
  return (
    <Button
      onClick={() => navigate(-navigateTo)}
      className="back-button"
      size="large"
      startIcon={<KeyboardArrowLeft />}
    />
  );
};

BackButton.propTypes = {
  navigateTo: PropTypes.number
};

export BackButton;

The above uses destructuring assignment with a default value to set the navigateTo value to 1 if it isn't specified.

When you use your BackButton component, you can pass through the navigateTo amount:

<BackButton navigateTo={2} />

If you don't specify the navigateTo prop then it'll go back 1 by default

<BackButton />
  • Related