React part 16
This is the last part of this Blog mock-up project. Today we learn how to do redirects after we add a new blog and how to delete the blogs as well.
Start it up like this:
npx json-server — watch data/data.json — port 8000
npm start or yarn start
So we start with redirecting. We will be using a hook called “useHistory.”
That allows us to go back and forth in history, and it also allows us to redirect people after submitting:
OK, first thing we need to do is import “useHistory” hook on the top of the page from react-router-dom.
After that, we need to assign the hook to a variable for easier use, which I do on line 9.
Then we just say “history.push” method, and it takes in argument of where you want to go. I use the “/” to go to the home page after we add/push the blog.
If it all worked, you should be redirected to the homepage like so:
Ok, this should be simple as well. We will use the “useHistory” hook again and fetch method of delete. Lets hop into “BlogDetail.js” component…
On line 3, we import “useHistory” hook again, then on line 9 again we make a variable called “history”.
We also add a button tag to the blog details, and I do this on line 29. Through a onClick event we are able to fire a function called handleDelete. That will fire when someone clicks on that button tag.
In our handleDelete function, we do a fetch method to the blogs data in our JSON file. We also need to associate it with a blog.id, which we get from our fetch hook. Then we show what method we want with this fetch , which is Delete. Then we slap on a “.then”, it fires a anonymous function and redirect them to the homepage or “/” after they delete it! walla…..It should delete the blog by Id.
Handeling error in URL:
Last thing I swear, This will through an error page if anyone messes up the URL.
First, make a NotFound.js file in src folder. We throw an “h2” with “sorry” in there, and then a “p tag” with “that page can't be found”. After that, we import the “Link tag” from react-router-dom which allows us to make a link to wherever we want. In our case we want to go to forward slash to the home page.
We need to go into where we have the router information. If you followed this entire project, it will be in your App .js component.
When you are in your App.js component, all we have to do is add another “Route tag”, and it has to be on the bottom of all the other routes. For reasons, it will look through all the Routes, and if nothing matches it will go to our new Notfound component. (Don't forget to add the path property and a value of “*” all that means is basically all other URL routes essentially!)
OK, that is the end of our tutorial for making a Blog! I am going to go through all this and edit everything to make sure it makes sense. That was a lot but, I wanted to make sure that I went through every single section and that it made sense. Instead of just throwing something at you and saying ok here is the blog, The End!
The Social Media…