Morning:
Afternoon:
RoutesThe Redirect component provided by React Router allows us to cause the user to navigate to a new location. Just drop in a Redirect component and pass it a to prop to tell it where to redirect, and you’re good to go!
<Redirect to='/widgets' />
A common use case for a Redirect is to send a user to different locations based on whether they are logged in or not.
import { Route, Redirect } from 'react-router'
<Route exact path="/" render={() => (
loggedIn ? (
<Redirect to="/dashboard"/>
) : (
<PublicHomePage/>
)
)}/>
The code above translates to: “If the path is at the root route (‘/’), redirect to ‘/dashboard’ if the user is logged in. Otherwise, render the PublicHomePage.”
Here’s a basic Route that renders a Stuff component when the path matches '/stuff':
<Route path="/stuff" component={Stuff} />
When Stuff is rendered, it will automatically receive props from the router that include match, history, and location. But what if we want to pass additional props to Stuff? It turns out, we can use the render prop for Route instead, which allows us to pass additional props when the anonymous function returns some JSX.
<Route path="/stuff" render={(props) => (
<Stuff name="Bob" {...props} />
)} />
In this example, the anonymous function in the render for the Route receives an argument of props (which includes match, history, and location). Our render method returns some JSX - specifically, the <Stuff /> component. We pass along our existing props to Stuff via Object spread, as well as an additional name prop.
Back in the olden days of React development, it would often take a significant amount of time to get your project up and running. Webpack configuration, dependency installations, script configuration, polyfills, etc, all had to be set up just to get a simple “Hello world” displaying on the screen.
Create React App solved this problem by doing all this initial setup for you! Just type create-react-app and your project name into terminal, and you’re up and running in minutes. The standard configuration works for almost any normal use case.
However, maybe you have a specific need that the standard create-react-app build isn’t set up for. In a standard app, all the config files are hidden, so what can you do?
Luckily, the ‘create-react-app’ team anticipated this as well. They provide an eject script that copies all configuration files and transitive dependencies into your project so you can have full control over them.
npm run eject
Simply run this command, and all of the configuration files will appear in your project folder!
Remember, ejecting is not reversible. Make sure you have a good reason to eject before you do so!