React routes for if you've already read all the other blogs on react routes
Sebastian Spiegel
Posted on March 24, 2021
This one is for beginners, so everybody else be warned.
I lost track of how many articles and blog posts I read while trying to set up an auto re-route, and absolutely none of them helped me. I kept getting bogged down by too many options and technicalities. They all included so much information about protecting your data, a million booleans to check authentications, just way more than what I was trying to do. If you want to do anything more complicated than 'click button, different web page', you should go read some of those other articles. This is more of an 'I honestly can no longer be bothered I just want you to do this one simple thing.'
The steps are:
- First page loads
- User clicks a button/link/whatever you wanna try adding an event listener to
- The page redirects to the Second page
I used this to redirect from a submit to an index page (with no errors or backend authentications).
First, import Redirect like so:
import { Redirect } from "react-router";
Next, you'll need a function similar to this one, that will be in charge of adding a redirect key to state and setting the boolean to 'true'.
setRedirect = () => {
this.setState({
...this.state,
redirect: true
})
}
If you haven't dealt with state much or are just starting to use React, that spread operator is a very important habit to get into. Even if you're not doing anything else at all in this component, get used to putting ...this.state every time you setState().
So now you need a function that will check that boolean. Something like this:
renderRedirect = () => {
if (this.state.redirect) {
return <Redirect to='/seeds' />
}
}
Short and sweet, if you need no other validations before you redirect that's all you need.
The next step is to call renderRirect() in your return. If you are in a class component (it would be called something like class MyClassComponent extends React.Component
) you'll do this inside the return of your render function. It will look like this:
render(){
return(
<div>
{this.renderRedirect()}
{/* Whatever link/button/etc you are putting your event listener on */}
</div>
)
}
So now, when the page loads it will run the renderRedirect function, which in turn will check state and see if the Redirect is valid. The last step is to go to your event listener function and call setRedirect(). If you are in a class component make sure you're calling it using this:
this.setRedirect()
The page will re-render as it is want to do when an event listener is triggered, and the user will be automatically redirected!
If you are trying to redirect from a functional component (something like export default function FunctionalComponent(props)
) there is also a very simple option, using history.push().
This is what I did for redirecting from an index to a show page. The user would be taking the same steps as before. The props I passed into my function were the objects (in this case a users gardens) being displayed, which included the object id.
First, import useHistory:
import {useHistory} from 'react-router-dom';
Then set a variable to call the useHistory() hook you've imported:
const history = useHistory()
Then in your event listener, you can call history.push. Here's what mine looks like:
function handleClick(){
history.push(`/gardens/${props.gardenId}`)
}
So you're basically telling your application "this is where I want to go when this event listener is fired".
To read more about these hooks you should check out this documentation: reactrouter.com. You'll the same exact code as before for useHistory, but less breakdown.
Again, this is all for beginners. Hi, hello, let's hold each other's hands and baby step our way through the most basic things until we understand them fully and completely. Otherwise, what's the point in even trying to tackle the harder stuff?
Also, so many things that happen when a user is interacting with a web app are invisible, so it can be very exciting to code something that actually an immediate visual result. I don't see why we don't celebrate every successful page render!
There are many, many ways to use routes and redirects in React. Probably better ways than this! To me, however, the best way is the way that 1) gets the job done and 2) that the programmer understands. If you just start copying and pasting from some article without knowing what any of it does, you'll be lost when you inevitably need to debug.
Posted on March 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024