Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda