1

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

Xero
  • 3,951
  • 4
  • 41
  • 73
  • Please check the duplicate, since you are using react-router v4 you would need to make use of Prompt, let me know if it still doesn't solve your problem – Shubham Khatri Apr 18 '18 at 09:27
  • @ShubhamKhatri if I understand well, Prompt is for showing an alert when user leaves the page. I don't want that. I want to execute some code when the user leaves the page. – Xero Apr 18 '18 at 09:38
  • 1
    I updated my answer here, please check https://stackoverflow.com/questions/32841757/detecting-user-leaving-page/45869459#45869459 – Shubham Khatri Apr 18 '18 at 09:46

1 Answers1

1

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

Vaibhav Agrawal
  • 714
  • 2
  • 6
  • 10