I'm new to react and I'm learning react programmatic navigation using typescript.since most of the tutorials are with java script, I'm not able to resolve issue with programmatic navigation using typescript
As in most of the tutorials i tried
this.props.history.push("/page");
which shows an error 'history' does not exist on type
i tried several solutions like
const history=createBrowserHistory();
history.push("/page")
This method will change url path but component will not load as mentioned here https://github.com/ReactTraining/react-router/issues/4059
i also tried another solutions
this.context.push("/page");
which gives me below error TypeError: _this.context.push is not a function
My full code
import * as queryString from 'query-string';
import * as React from 'react';
interface IrentalProps{
name:string,
}
class Rental extends React.Component<IrentalProps, any> {
public extracturl=()=>{
const stringfy=queryString.parse(location.search);
return stringfy.id;
}
public handleClick=()=>{
this.context.push("/page"); //issue
}
public render() {
return (
<div style={{paddingTop:100}}>
{this.extracturl()}
<button onClick={this.handleClick}>navigate</button> //calling the function
</div>
);
}
}
export default Rental;
I only need to navigate to another page on a button click as in SPA using typescript and browserrouter
Note:redirect is working and hashrouter with createhashhistory() is also working .
答案 0 :(得分:0)
you need the react-router types. at the root of the project install them (package.json)
npm install --save @types/react-router
and
npm install --save @types/react-router-dom
答案 1 :(得分:0)
创建自己的历史记录时,您需要使用Router而不是BrowserRouter。
import createBrowserHistory from 'history/createBrowserHistory'
const History = createBrowserHistory()
export default History;
并将历史记录传递给路由器的道具
感谢BTM