Home > other >  How to open a page with react-router-dom without any event?
How to open a page with react-router-dom without any event?

Time:11-11

I want to open homepage only if login data is correct i.e. getting success in response

<form>
//inputs
<button type="submit" onClick={(e) => sendData(e)}> Sign-In </button>
</form>

 const sendData = (e) => {
    e.preventDefault();
    axios({ method: "POST", url: url, data: data, headers: header })
      .then((res) => {
        if (res.data.status === "success") {

          props.sethistory(res.data.data.user.history);//getting data from response
          props.setsignedIn(true);  

          //what to do here to open homepage
        }
      })
      .catch((err) => console.log(err));
  };

CodePudding user response:

this will surely help you,

import { useHistory } from 'react-router-dom';
const history = useHistory();

then use it programatically, when your login is success, put this code, will take you to that URL component home for example in your case

history.push("/YOURURL");

CodePudding user response:

Depending on which version of react-router-dom you are using the process is basically the same: issue an imperative navigation action.

Versions 3/4/5

In versions 3/4/5 this is accomplished via the history object, accessed via injected route props (history, location, and match) or with React hooks (useHistory, useLocation, useParams).

Example:

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

...

// in function body "unpack" history object
const history = useHistory();

...

const sendData = (e) => {
  e.preventDefault();
  axios({ method: "POST", url: url, data: data, headers: header })
    .then((res) => {
      if (res.data.status === "success") {
        props.sethistory(res.data.data.user.history);
        props.setsignedIn(true);  

        history.push("/homepage"); // <-- imperative navigation
      }
    })
    .catch((err) => console.log(err));
};

useHistory

Version 6.x

In version 6 the API was significantly updated, and route props no longer exist and the same "values" are accessible via React hooks. The history object is also no longer directly exposed, but rather you are given a navigate function to invoke with the target path.

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

...

// in function body "unpack" navigate function
const navigate = useNavigate();

...

const sendData = (e) => {
  e.preventDefault();
  axios({ method: "POST", url: url, data: data, headers: header })
    .then((res) => {
      if (res.data.status === "success") {
        props.sethistory(res.data.data.user.history);
        props.setsignedIn(true);  

        navigate("/homepage"); // <-- imperative navigation
      }
    })
    .catch((err) => console.log(err));
};

useNavigate

  • Related