Use Prompt for Page Exit Confirmations

## <br>Problem Sometimes you need to ask a user to confirm that they want to leave a page if they’re in the middle of editing something. This seemingly simple task can be complicated because it relies on spotting when the user clicks the Back button and then finding a way to intercept the move back through history and potentially canceling it. What if there are several pages in the application that need the same feature? Is there a simple way to create this feature across any component that needs it? ## <br>Solution The react-router-dom library includes a component called Prompt, which asks users to confirm that they want to leave a page. The only ingredient we need for this recipe is the react-router-dom library itself: ```js npm install react-router-dom ``` Let’s say we have a component called Important mounted at /important, which allows a user to edit a piece of text: ```js import React, { useEffect, useState } from 'react' const Important = () => { const initialValue = 'Initial value' const [data, setData] = useState(initialValue) const [dirty, setDirty] = useState(false) useEffect(() => { if (data !== initialValue) { setDirty(true) } }, [data, initialValue]) return ( <div className="Important"> <textarea onChange={(evt) => setData(evt.target.value)} cols={40} rows={12} > {data} </textarea> <br /> <button onClick={() => setDirty(false)} disabled={!dirty}> Save </button> </div> ) } export default Important ``` Important is already tracking whether the text in the textarea has changed from the original value. If the text is different, the value of dirty is true. How do we ask the user to confirm they want to leave the page if they click the Back button when dirty is true? We add a Prompt component: ```js return ( <div className="Important"> <textarea onChange={(evt) => setData(evt.target.value)} cols={40} rows={12} > {data} </textarea> <br /> <button onClick={() => setDirty(false)} disabled={!dirty}> Save </button> <Prompt when={dirty} message={() => 'Do you really want to leave?'} /> </div> ) ``` If the user edits the text and then hits the Back button, the Prompt appears. Try using the code and see what a great result you get. Sign up and share your coding ideas too. Use the application's markdown to extilize your text and code. Don't forget to leave a comment if you like this post. Thank you.

All comments
amargo85 amargo85

in this example I'm using React.js


wbd258 wbd258

what language is this?