Xero
Xero

Reputation: 4175

React router callback when leaving the page

I want to know if the user is leaving the page

I tried :

componentWillMount() {
  this.props.router.setRouteLeaveHook(
    this.props.route,
    this.routerWillLeave
  )
},

But I get :

this.props.router is undefined

I saw some solutions, but I don't want to use this react way :

React.createClass

Version of react-router :

"react-dom": "^16.3.1",
"react-router-dom": "^4.2.2",

And how I implemented the router :

root.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import { App } from '../components/app'
import { BrowserRouter } from 'react-router-dom'

// Render component with data
document.addEventListener('DOMContentLoaded', () => {

    const node = document.getElementById('app');

    ReactDOM.render(
        (<BrowserRouter>
            <App />
        </BrowserRouter>),
        node )
});

app.jsx

import React from 'react'

import CompanyList from './company/company_list'
import CompanyDetails from './company/company_details'
import { CompanyNew } from "./company/company_new";
import { Error404 } from "./common/error_404";

import { Route, Switch } from 'react-router-dom'

export const App = () => {
    return (
        <Switch>
            <Route path='/' exact component={CompanyList}/>
            <Route path='/companies' component={CompanyList}/>
            <Route path='/company/new' component={CompanyNew}/>
            <Route path='/company/:id' component={CompanyDetails}/>
            /* 404 if not found : */
            <Route component={Error404}/>
        </Switch>
    )
};

EDIT :

I tried with :

import { withRouter } from 'react-router'

class CompanyDetails extends React.Component {

    constructor(props) {
        super(props);
    }

    componentWillMount() {
        this.props.router.setRouteLeaveHook(
            this.props.route,
            this.routerWillLeave
        )
    }
}

export default withRouter(CompanyDetails)

But I get the same error

Upvotes: 1

Views: 1313

Answers (1)

Vaibhav Agrawal
Vaibhav Agrawal

Reputation: 752

You can get history off context or create it outside the Router and pass it in as a history prop.

Upvotes: 1

Related Questions