The useNavigate
hook is part of the react-router-dom
package that allows programmatic routing inside a React application. The method returns a function that can be invoked with a Router
instance.
The code snippet below demonstrates the use of the useNavigate
hook inside a React application.
The example application defines two pages, the LoginPage
on the /
route and the HomePage
on the /home
route inside the index.js
file. When the user enters the SECRET_KEY
(Educative Rocks!
) inside the text box, they are navigated to the HomePage
.
LoginPage
Line 1: Imports the useNavigate
hook from the react-router-dom
package
Line 3: Defines the SECRET_KEY
through which the user can switch to the HomePage
.
Line 7: Invokes the useNavigate
hook to get the navigate
function.
Lines 9–13: Defines the function handleChange
that checks whether the user has entered the correct secret key; if so, then the navigate
function is invoked with the /home
path to route the user to the HomePage
.
Lines 15–21: Defines the layout of the LoginPage
with a heading, some text, and a textbox with which the handleChange
function is attached (causing it to be invoked whenever the user updates text inside the text box).
HomePage
Line 1: Imports the useNavigate
hook from the react-router-dom
package
Line 5: Invokes the useNavigate
hook to get the navigate
function.
Lines 7–13: Defines the layout of the HomePage
with a heading, some text, and a button to go back to the LoginPage
(this is achieved by attaching () => navigate('/')
as the onClick
method for the button).
Free Resources