Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
August 25, 2022 01:51 pm GMT

Learn from useHistory()

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.

Image description

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!

Image description

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.

Image description

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:

Image description

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


Original Link: https://dev.to/kelan6/learn-from-usehistory-110o

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To