javascript - How to use a custom component with react-router route transitions? -


the article confirming navigation explains how use browser confirmation box in transition hook. fine. want use own dialog box. if use methods history module think possible. possible setrouteleavehook in react-router?

the core problem setrouteleavehook expects hook function return result synchronously. means don't have time display custom dialog component, wait user click option, , then return result. need way specify asynchronous hook. here's utility function wrote:

// asynchronous version of `setrouteleavehook`. // instead of synchronously returning result, hook expected // return promise. function setasyncrouteleavehook(router, route, hook) {   let withinhook = false   let finalresult = undefined   let finalresultset = false   router.setrouteleavehook(route, nextlocation => {     withinhook = true     if (!finalresultset) {       hook(nextlocation).then(result => {         finalresult = result         finalresultset = true         if (!withinhook && nextlocation) {           // re-schedule navigation           router.push(nextlocation)         }       })     }     let result = finalresultset ? finalresult : false     withinhook = false     finalresult = undefined     finalresultset = false     return result   }) } 

here example of how use it, using vex show dialog box:

componentwillmount() {   setasyncrouteleavehook(this.context.router, this.props.route, this.routerwillleave) } ​ routerwillleave() {   return new promise((resolve, reject) => {     if (!this.state.textvalue) {       // no unsaved changes -- leave       resolve(true)     } else {       // unsaved changes -- ask confirmation       vex.dialog.confirm({         message: 'there unsaved changes. leave anyway?' + nextlocation,         callback: result => resolve(result)       })     }   }) } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -