When working in the navigation aspect of a web application, is a common need to handle the back button event, in this situation knowing when the click was made is required.
In this example we use react-router
to create a simple application with navigation. We will create a new component that use the event handler window.onpopstate
inside useEffect
hook to detect the click on the button.
Matías Hernández: [0:00] This is a little application that use react-router to show different links and sections. It use a <Switch> over three routes. Each of them shows different content. To listen for the back button, we will create a component that we call BackButtonListener. We will use the useEffect and useState hook.
[0:24] First, we define the state using useState that returns a tuple. The first value of it is the state value that we call pressed, and the second one the dispatch function that we name it setPressed. The state is initialized with false. Now, we can use the useEffect hook to add the event handler onpopstate from the window object.
[0:46] Onpopstate is defined as handler function. We will use it to dispatch a state change using the setPressed function. Now, we just render the state using the value of pressed that is a Boolean. We use toString method to show it in the screen.