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

243
Visualizações
ReactJS Router- How to use history push within function component with parameters?

I'm having problems using history.push("path/...") within a function component. My problem is when i try to use a function component's param in the button handler. I have the next code: Example.js

...
import {useHistory} from 'react-router-dom';
...

//This function works fine, but i would prefer something reusable
function Button() {
    const history = useHistory();
    function handle(){
        history.push("/path"); //The path is harcoded
    }
    return(
        <button onClick={handle}>
            Home //This text is harcoded
        </button>
    );
}

//This is what i'm looking for, because i would write it once.
function Button(path, text) {
    const history = useHistory();
    function handle(){
        history.push(path); //This doesn't work
    }
    return(
        <button onClick={handle}>
            {text} //This throws an error "no valid react child"
        </button>
    );
}

//this component is being render as a child of BrowserRouter
class Example extends Component{
    render(){
        return(
            <div>
                <Button path="path/..."/>
            </div>
        );
    }
}

export ...

This is my actual code, just removed repeated lines. With the first function component i have no problems, but, I'm in the need to create a new function component for every button. Instead i'm looking for a way to write this functions once and use it to create many buttons.

The second function does nothing when the path is being passed through props, and if I add console.log(path) in the handle(), the path value is printed as it is passing correctly, but history.push(path) does not take it.

I want to add that, the only clue I have is the push method documents, where the types this method takes are string, but any is being passed.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

React components receive only a single argument that is the props object. You are assuming two.

function Button(path, text) {
  const history = useHistory();
  function handle(){
    history.push(path); // This doesn't work
  }
  return(
    <button onClick={handle}>
      {text} // This throws an error "no valid react child"
    </button>
  );
}

should be

function Button({ path, text }) {
  const history = useHistory();
  function handle(){
    history.push(path); // This should work now
  }
  return(
    <button onClick={handle}>
      {text} // This should render now
    </button>
  );
}

Notice here the passed props are destructured from the props object.

about 4 years ago · Juan Pablo Isaza Relatório

0

Send path and name as props and use those inside your button function.

<Button path="path/..."/ name="Home">

function Button({path,name}) {
    const history = useHistory();
    function handle(){
        history.push(path); 
    }
    return(
        <button onClick={handle}>
           {name}
        </button>
    );
}
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