React router dom v5 history.push does not render new page

qwertyuiop

I need to redirect user to their profile page after logging in and tried using history.push() inside Axios then. This is my code for the sign in form. I use the onClick button to get the email and password of user, and then redirect them to the new page, ClientProfile:

SignIn.js

import React from 'react';
import {Form, Button} from 'react-bootstrap';
import { useState } from 'react';
import Axios from 'axios';
import { useHistory } from 'react-router-dom';

function SignIn() {

    const history = useHistory();

  const [userEmail, setEmail] = useState("");
  const [userPassword, setPassword] = useState("");

//after onClick
  const signIn = () => {

//get user input
    Axios.post("http://localhost:8800/signIn", {
      userEmail: userEmail,
      userPassword: userPassword,
    }).then((res) => {
        console.log(res);
        history.push('/clientprofile');
  })};

    return (
        <Form>
            <Form.Group className="mb-3" controlId="formBasicEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control type="email" placeholder="Enter your email here"  
                        onChange = {(event) => {
                          setEmail(event.target.value);
                        }}
                      />
            </Form.Group>

            <Form.Group className="mb-3" controlId="formBasicPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control type="password" placeholder="Enter your password here" 
                    onChange = {(event) => {
                      setPassword(event.target.value);
                    }}
                    />
            </Form.Group>
            
            <Button variant="primary" type="submit" onClick={ signIn }>
                Submit
            </Button>
        </Form>
    )
}

export default SignIn;

I define the route in app.js here:

import './App.css';
import { Navbar, Nav, Container, Image } from 'react-bootstrap';
import About from './Components/About';
import Services from './Components/Services';
import Help from './Components/Help';
import SignIn from './Components/SignIn';
import ClientProfile from './Components/ClientProfile';
import { Switch, Route, NavLink } from 'react-router-dom';

function App() {


  return (
    <div className="App">
      <Navbar className="mainNav">
                <Container>
                        <Nav className="right-side me-auto">
                            <Nav.Link as = {NavLink} to = '/' className="text-white p-3">About Us</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/ourservices' className="text-white p-3">Our Services</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/help' className="text-white p-3">Help</Nav.Link>
                            <Nav.Link as = {NavLink} to = '/signin' className="rounded-pill m-1 px-3 py-2 text-white signInBtn">Sign In</Nav.Link>
                        </Nav>
                </Container>
      </Navbar>
      <br/>
      
      <Switch>
        <Route exact path = "/"><About /></Route>
        <Route path = "/ourservices" ><Services /></Route>
        <Route path = "/help" ><Help /></Route>
        <Route path = "/signin"><SignIn /></Route>

//the route is being defined here
        <Route path = "/clientprofile"><ClientProfile/></Route>
      </Switch>
    </div>
  );
}

export default App;

however, it does not render a new page and instead it stays on the same page, which is Sign In page. can anyone help me?

Drew Reese

Issue

You are submitting the form but not preventing the default form action from occurring. This reloads the page before the POST request response can be handled and the UI redirected.

Solution

Move the onClick={signIn} to the Form component and switch it to the onSubmit handler, and in the signin handler consume the onSubmit event object and prevent the default form action.

function SignIn() {
  const history = useHistory();

  const [userEmail, setEmail] = useState("");
  const [userPassword, setPassword] = useState("");

  //after onClick
  const signIn = (e) => { // <-- onSubmit event object
    e.preventDefault();   // <-- preventDefault
    // get user input
    Axios.post("http://localhost:8800/signIn", {
      userEmail: userEmail,
      userPassword: userPassword
    }).then((res) => {
      console.log(res);
      history.push("/clientprofile");
    });
  };

  return (
    <Form onSubmit={signIn}> // <-- onSubmit event handler
      ...

      <Button variant="primary" type="submit"> // <-- remove onClick handler
        Submit
      </Button>
    </Form>
  );
}

Edit react-router-dom-v5-history-push-does-not-render-new-page

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to push to History in React Router v5?

react-router-dom : updates url but does not render the new component

Render multiple Route into a main Router in react-router-dom v5

React-Router v5 not redirecting if accessing specific route using history.push

React-router-dom v4 does not render the component

react router doesn't re-render after history push

React Router Dom History

react-router-dom v6 history push and useNavigate problem

history.push using react-router-dom

react-router-dom - Difference between link and history.push?

Is possible to override History.push method of React-Router-Dom

React router v5 with history - no content shown on routing

React router history push always route to 404 page

History.push a link to a new tab with react router

how to redirect to partical page using history object in react-router-dom v6

React Router V6 - page is not in history

history.push changes url but does not render form react hooks

Nested Routing in react-router-dom V5 not working

React router history not render correctly

React Testing Library render does not work with react router dom Navigate

React router V5 updating URL but not refreshing page

react-router-dom v6 rendering new page over current page

react-router-dom rendering new page over current page

How to push to History in React Router v4?

history.replace in react-router-dom v6

using history with react-router dom on v6

react router not working and no erros in console or compilation error is shown [ react router dom v5]

How to navgiate to a new page using react router dom with typescript

React-router-dom routing to a new page with props