React Router
is the answer for rendering different components for different pages.
Client-side Routing
Getting started with routing
Install React Router with:
Import Browser Router
from package.
BrowserRouter
is the primary component of the router that wraps your route hierarchy.
React Context
that passes routing information down to all its descendant components.You can also use HashRouter
, where it would generate a hash before the endpoint.
Creating frontend routes
The most common component is <Route>
Props
: path, component, exact, and [render]Browser Router can only have a single child component.
const Root = () => {
const users = {
1: { name: "Andrew" },
2: { name: "Raymond" },
};
return (
<BrowserRouter>
<div>
<h1>Hi, I'm Root!</h1>
<Route exact path="/" component={App} />
<Route path="/hello" render={() => <h1>Hello!</h1>} />
<Route path="/users" render={() => <Users users={users} />} />
</div>
</BrowserRouter>
);
};
render
component
and render
is that component returns new JSX that be re-mounted, but render returns the JSX that will be mounted only once.// This inline rendering will work, but is unnecessarily slow.
<Route path="/hello" component={() => <h1>Hello!</h1>} />
// This is the preferred way for inline rendering.
<Route path="/hello" render={() => <h1>Hello!</h1>} />
Route path params
:
to the next /
, ?
, #
.{...props}
spreads out the router’s props.props.match.params
is used to access the match prop’s parameters.match
object:
isExact
: boolean that tells you whether or not the URL exactly matches the path.url
: the currentURLpath
: Route path it matched against (w/o wildcards)params
: Matches for the individual wildcard segments.React Router Navigation
Link
, NavLink
, Redirect
, history
props of React Router are used to help your user navigate routes.Adding links for navigation
href
attribute.Link
takes two properties: to
and onClick
.
to
: route location that points to an absolute path.onClick
: clickHandler.NavLink
works just like Link
but has a bit of extra functionality.
activeClassName
: allows you to set a CSS class name for styling. (default set to ‘active’)activeStyle
: style object that is applied inline when it’s to
prop. matches the current URL.exact
prop is a boolean that defaults to false; you can set it to true to apply requirement of an exact URL match.
Switching between routes
<Switch>
: Component allows you to only render one route even if several match the current URL.
Very useful if we want a default component to render if none of our routes match.
<Switch>
<Route path="some/url" component={SomeComponent} />
<Route path="some/other/url" component={OtherComponent} />
<Route component={DefaultComponent} />
</Switch>
DefaultComponent
will only render if none of the other URLs match up.
<Redirect>
: Helps redirect users.
to
.<Route
exact
path="/"
render={() => (this.props.currentUser ? <Home /> : <Redirect to="/login" />)}
/>
History
History
allows you to update the URL programmatically.push
: Adds a new URL to the end of the history stack.replace
: Replaces the current URL on the history stack, so the back button won’t take you to it.// Pushing a new URL (and adding to the end of history stack):
const handleClick = () => this.props.history.push("/some/url");
// Replacing the current URL (won't be tracked in history stack):
const redirect = () => this.props.history.replace("/some/other/url");
Why nested routes?
What are nested routes?
const Profile = (props) => {
// Custom call to database to fetch a user by a user ID.
const user = fetchUser(props.match.params.userId);
const { name, id } = user;
return (
<div>
<h1>Welcome to the profile of {name}!</h1>
<Link to={`/users/${id}/posts`}>{name}'s Posts</Link>
<Link to={`/users/${id}/photos`}>{name}'s Photos</Link>
<Route path="/users/:userId/posts" component={UserPosts} />
<Route path="/users/:userId/photos" component={UserPhotos} />
</div>
);
};
Alt. version using props.match
// Destructure `match` prop
const Profile = ({ match: { url, path, params }) => {
// Custom call to database to fetch a user by a user ID.
const user = fetchUser(params.userId);
const { name, id } = user;
return (
<div>
<h1>Welcome to the profile of {name}!</h1>
<Link to={`${url}/posts`}>{name}'s Posts</Link>
<Link to={`${url}/photos`}>{name}'s Photos</Link>
<Route path={`${path}/posts`} component={UserPosts} />
<Route path={`${path}/photos`} component={UserPhotos} />
</div>}
);
};
Build
: Process of converting code into something that can actually execute or run on the target platform.
Reviewing common terminology
Linting
: Process of using a tool to analyze your code to catch common errors, bugs, inconsistencies etc…Transpilation
: Process of converting source code, like JS, from one version to another.Minification
: Process of removing all unnecessary characters in your code.Bundling
: Process of combining multiple code files into a single file.Tree Shaking
: Process of removing unused or dead code from your application before it’s bundled.Configuration or code?
Configuration
allows developers to create build tasks by declaring either JSON, XML, or YAML without explicitly writing every step in the process.Coding
or Scripting
simply requires code.Babel and webpack (yes, that’s intentionally a lowercase ‘w’)
Babel
: Code Transpiler that allows you to use all of the latest features and syntax wihtout worrying about what browsers support what.
webpack
: Allows developers to use JS modules w/o requiring users to use a browser that natively supports ES modules.
Create React App uses webpack and Babel under the hood to build applications.
The Create React App build process
npm start
:
webpack-dev-starter
is startedwebpack-dev-starter
compiles app.index.html
is loaded into browserEjecting
eject
that allows you to ‘eject’ your application and expose all the hidden stuff.Preparing to deploy a React application for production
REACT_APP_FOO: some value
REACT_APP_BAR: another value
Configuring the supported browsers
{
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Creating a production build
npm run build
to create a production build.