Kelan6
Posted on August 25, 2022
Recently, while working on a React/Ruby project, I found myself asking, "How cool would it be if I clicked this button on the log in page, and if the log in was correct, it automatically navigated me to the Home Page"?
While we have to fetch the Ruby database in React to verify the log in, the idea of this auto-link was escaping me. So...
TO GOOGLE !
I quickly came across the useNavigate() hook.
This was perfect! "OnClick" I wanted to navigate to ('/Home') from the Login component. I kept scrolling to learn more.
Importing the useNavigate() from "react - router - dom" at the top of the page? Sounded good, but it made me think of day 1 of setting up this project. I had installed specifically "npm install react-router-dom@5". Meaning I purposely installed V5 instead of the current V6.
I realized then, that the useNavigate Hook was created in React Router V6 to replace a previous Hook, useHistory().
I was a little disappointed that I had spent so much time on the useNavigate() Hook, and it wouldn't be able to help me with this project. But, I continued down the rabbit hole of useHistory(), determined to get this auto-link working.
Luckily, they are almost identical!
So what is useHistory()?
"The useHistory hook gives you access to the history instance that you may use to navigate." - v5.reactrouter
Similarly to useNavigate(), we import useHistory () from "react - router - dom" at the top of the page.
Then we set a variable, 'history' equal to the useHistory Hook.
Now we have the power of useHistory() down in our component!
The simple syntax is: {history.push('/Which_Route_We_Want')
In the code above, I set a boolean statement with useState "isSubmitted". If the proper input is submitted to the username and password, then push the client to the /Home page. If not, continue to render the form above with helpful error messages (not shown).
Once I figured out how simple this auto-linking was with useHistory(), I set up my page with similar links like below:
Just remember to add your 'onClick' listeners below in your JSX!
This was my quick guide on the useHistory() Hook. Hope this helps someone in the future to learn from useHistory(), or we'll be doomed to repeat it š.
SOURCES
https://v5.reactrouter.com/web/api/Hooks
https://www.geeksforgeeks.org/reactjs-usenavigate-hook/
https://github.com/almickle/Phas3r-FrontEnd
Posted on August 25, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.