Build a simple modal with backhandler using hook and react-responsive-modal in next.js (and react.js)
Modals are large UI elements that sit on top of an application’s main window — often with a layer of transparency behind them to give users a peek into the main app.
We were building a custom modal in our Next.js project. There was a problem with customizing the modal. When the users click the browser’s back button the route changed but the modal is still open. I’m going to explain how we fixed this issue.
We used Next.js and typescript in this project.
example: demo
Step 1) Install react-responsive-modal package:
yarn add react-responsive-modal
Step 2) Building modal component:
create a new file, custom-modal.tsx
and declare stateless functional modal component with three argument children
, visible
and closeModal
. The argument visible
is show property on your state.
step 3) set backHandler
When the users open modal the first thing we do is adding a hash to our url, and then we setShow
to true. With this hash and the show state we can detect the modal is open or not, when we have hash the modal is open, so when user click on browser’s back button or close the modal we just need to remove this hash.
- Can we use query string instead of #?
We can use query string too, but there is a problem.
When query string has changed, it will scroll to top of the page. To avoid this, we used hash(#) instead of query string. - What will happen if I refresh my page when modal is open?
Modal will be closeed but still we have a hash in our url :(
For handle this problem you must add another condition to your useEffect. - How can I handle backhandler in React?
The only difference between React.js and Next.js is router.
In react you use react-router-dom instead of next router.
In the end, I want to thank Niloofar Sadeghi for her cooperation throughout this article.