Reputation: 5150
Im using BrowserRouter
to manage the routing. I have a function that when its called I want to change the route without a page refresh.
import React from 'react';
const myPage: React.FC = (props) => {
function loadPage(event: any) {
if (event.target.id) {
window.history.push('/' + event.target.id)
}
return (
<div id='home' onClick={loadPage}><div/>
<section> {props.children} </section>
)
...
The error im getting is Property 'push' does not exist on type 'History'.ts(2339)
Note: the router is a child of this element and is being passed into props.children
Upvotes: 1
Views: 2059
Reputation: 5150
The fix that worked was...
window.location.href = '/'+event.target.id;
Upvotes: 0
Reputation: 4394
There is no function push on history object in window. I suggest you use react-router-dom's history or Redirect.
import React from 'react';
import { withRouter } from 'react-router-dom';
const myPage: React.FC = (props) => {
function loadPage(event: any) {
if (event.target.id) {
props.history.push('/' + event.target.id)
}
return (
<div id='home' onClick={loadPage}><div/>
)
then at the end, you should wrapp your component before exporting it in withRouter component
export default withRouter(myPage);
Wrapping it like this will make history accessible through props
Upvotes: 1
Reputation: 83
If the myPage
component is being passed as a prop to the <Route>
component for eg: <Route exact path="/myPage" component={myPage}>
then you could use the React-Router props that are received by the myPage
component for navigation.
import React from 'react';
import { RouteComponentProps } from 'react-router';
const myPage: React.FC = (props:RouteComponentProps) => {
function loadPage(event: any) {
if (event.target.id) {
props.history.push('/' + event.target.id)
}
return (
<div id='home' onClick={loadPage}><div/>
)
Upvotes: 0