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

983
Visualizações
Proper use of useNavigate() function in Reactjs

I'm very new to react and don't understand quite all of the restrictions yet. I'm trying to do a simple page switch after a button is clicked. After researching I figured useNavigate() would be used best for this situation. After trying to implement it into my code I realized what I had, did absolutely nothing. My goal is to send the user to a home page once the register button is clicked. As of right now, when I click the button nothing happens. This could be some small detail I missed or just me being completely oblivious. Please let me know if you think you see anything of importance, thanks in advance.

Here is my apps main page with my path being src/components/login/register:

import React from "react";
import "react-datepicker/dist/react-datepicker.css";
import { useNavigate } from "react-router-dom";
import axios from 'axios';

const api = axios.create({
    ...
})

const sendDetailsToServer = (payload) => {
    ...
}

const GoToLogin = () => {
    let navigate = useNavigate();
    navigate('/home');
}



export class Register extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.onInputchange = this.onInputchange.bind(this);
    this.onSubmitForm = this.onSubmitForm.bind(this);
  }

  onInputchange(event) {
    this.setState({
        [event.target.name]: event.target.value
    });
  }


  onSubmitForm() {
    let registerInfo = {
        user_name : this.state.username,
        password : this.state.password,
        email_id : this.state.email
    }

    sendDetailsToServer(registerInfo);
    GoToLogin();
  }

  render() {
      
    return (
        <div className="base-container" ref={this.props.containerRef}>

            <h1>Welcome!</h1>
            <link rel="stylesheet" href="" />
            <div className="header">Please Enter Your Account Information</div>
            <div className="content">
                
            ...

            <div className="footer">
                <button type="button" className="btn" onClick={this.onSubmitForm}>
                    Register
                </button>
            </div>
            <div className="footer-fill"></div>
        </div>
        );
    }
}

Here is my home page found under my path src/components/login/home:

import React from "react";

const Home = () => {
  return(
    <div>
      <h1>Login</h1>
    </div>
  );
};
export default Home;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

useNavigate hook is added to version 6, and it can be used only in functional component. If you want to use it in class component, create a HOC(withRouter).

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

export const withRouter = (Component) => {
  const Wrapper = (props) => {
    const navigate = useNavigate();

    return <Component navigate={navigate} {...props} />;
  };

  return Wrapper;
};

and use it in your register.js like this

export default withRouter(Register)

here is the complete code.

import React from "react";
import "react-datepicker/dist/react-datepicker.css";
import axios from 'axios';

const api = axios.create({
    ...
})

const sendDetailsToServer = (payload) => {
    ...
}

class Register extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.onInputchange = this.onInputchange.bind(this);
    this.onSubmitForm = this.onSubmitForm.bind(this);
  }

  onInputchange(event) {
    this.setState({
        [event.target.name]: event.target.value
    });
  }


  onSubmitForm() {
    let registerInfo = {
        user_name : this.state.username,
        password : this.state.password,
        email_id : this.state.email
    }

    sendDetailsToServer(registerInfo);
    this.props.navigate('/home');

  }

  render() {
      
    return (
        <div className="base-container" ref={this.props.containerRef}>

            <h1>Welcome!</h1>
            <link rel="stylesheet" href="" />
            <div className="header">Please Enter Your Account Information</div>
            <div className="content">
                
            ...

            <div className="footer">
                <button type="button" className="btn" onClick={this.onSubmitForm}>
                    Register
                </button>
            </div>
            <div className="footer-fill"></div>
        </div>
        );
    }
}

export default withRouter(Register)

sample code

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