Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda