Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
useNavigate hook with multiple choices?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 />
about 4 years ago · Juan Pablo Isaza Report

0

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))}
    />
  );
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!