How to use react-router useHistory hook with TypeScript
Asked Answered
A

2

7

In my func component I am trying to use history.push in this way:

import React, { useEffect } from 'react';
import { useHistory } from 'react-router-dom';

interface Props {
  question: Question;
  selectedAnswer: SelectedOption | undefined;
}

const LastScreen: React.FC<Props> = (props: Props) => {
  const history = useHistory();
  ...
  
  useEffect(() => {
    if (progress === 100) {
      const id = uuid();
      history.push({
        pathname: `/p/${id}`,
        state: { userAnswers },
      });
    }
  }, [progress, userAnswers, history]);
  ...
};

but it gives an error:

Argument of type '{ pathname: string; state: { userAnswers: UserAnswers | undefined; }; }' is not assignable to parameter of type 'To'. Object literal may only specify known properties, and 'state' does not exist in type 'PartialPath'.ts(2345)

How to fix it?

Amigo answered 8/7, 2020 at 10:0 Comment(2)
after trying to fix it I found the problem appears when using custom history, like import history from 'history'; and then <Router history={history}>...</Router> So when I replaced it with <BrowserRouter>...</BrowserRouter> the problem disappeared.Amigo
Note: useHistory is old (v5), now (v6), const navigate = useNavigate(); navigate('/') is used. Reference: https://mcmap.net/q/378009/-how-to-properly-use-usehistory-from-react-router-domZildjian
A
0

The useHistory hook gives you access to the history instance that you may use to navigate.

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

let history = useHistory();
Amatory answered 8/7, 2020 at 10:0 Comment(0)
B
0

The react-router documentation says the following on the history.push function:

push(path, [state]) - (function) Pushes a new entry onto the history stack

I'm not sure what variable type userHistory is, but it needs to be a state variable. I can tell it isn't because you aren't importing useState. Import useState with useEffect like this:

import React, { useEffect, useState } from 'react';

And declare the variable like this:

const [ userHistory, setUserHistory ] = useState();

Then you can set userHistory:

setUserHistory("foo");

Sources:

React Router history doucmentation

ReactJS useState documentation

Bonesetter answered 12/6, 2023 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.