Security News
Cloudflare Adds Security.txt Setup Wizard
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
react-router
Advanced tools
The react-router npm package is a declarative routing library for React, allowing you to add navigation functionality to your React applications. It enables you to handle URL routing, match routes to your React components, and manage navigation state in a single-page application (SPA) environment.
Basic Routing
This code demonstrates how to set up basic routing in a React application using react-router. It includes navigation links and route components that render different components based on the URL path.
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to='/'>Home</Link>
</li>
<li>
<Link to='/about'>About</Link>
</li>
</ul>
</nav>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
</div>
</Router>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
Dynamic Routing
This code snippet shows how to implement dynamic routing with path parameters. The User component will render with the appropriate user ID based on the URL.
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
function App() {
return (
<Router>
<div>
<ul>
<li>
<Link to='/users/1'>User 1</Link>
</li>
<li>
<Link to='/users/2'>User 2</Link>
</li>
</ul>
<Route path='/users/:id' component={User} />
</div>
</Router>
);
}
function User({ match }) {
return <h2>User ID: {match.params.id}</h2>;
}
Nested Routing
Nested routing allows you to create routes within routes. This example shows a Layout component with a nested Dashboard route.
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Route path='/' component={Layout} />
</Router>
);
}
function Layout({ match }) {
return (
<div>
<nav>
<Link to={`${match.url}dashboard`}>Dashboard</Link>
</nav>
<Switch>
<Route path={`${match.path}dashboard`} component={Dashboard} />
</Switch>
</div>
);
}
function Dashboard() {
return <h2>Dashboard</h2>;
}
Protected Routes
Protected routes are used to restrict access to certain parts of your application. This example shows a route that renders a component only if the user is authenticated, otherwise it redirects to a login page.
import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom';
function App() {
return (
<Router>
<Route path='/protected' render={() => (
isAuthenticated() ? (
<ProtectedComponent />
) : (
<Redirect to='/login' />
)
)} />
</Router>
);
}
function isAuthenticated() {
// Authentication logic here
return true;
}
function ProtectedComponent() {
return <h2>Protected</h2>;
}
Vue-router is the official router for Vue.js. It provides similar functionalities for Vue applications as react-router does for React applications, including nested routes, dynamic segments, and navigation guards. However, it is designed to work seamlessly with Vue's reactivity system.
Reach Router is another routing library for React, which aims to be more accessible and simpler to use than react-router. It has a smaller API surface area and focuses on accessibility by managing focus after route transitions. However, as of my knowledge cutoff in 2023, Reach Router has been officially merged with React Router, and its features have been integrated into React Router v6.
A complete routing library for React.
You are viewing docs for the latest code on master. Check out other releases for the version you have installed.
Also, please refer to the CHANGELOG when upgrading.
This package has moved from react-nested-router
to react-router
.
Update your package.json to point to the new package, or if you aren't
ready to update, make sure your package.json specifically points to
0.3.5
or less, 0.3.6
just throws an error telling you the package
has moved.
Before our 1.0
release, breaking API changes will cause a bump to
0.x
. For example, 0.4.1
and 0.4.8
will have the same API, but
0.5.0
will have breaking changes.
.active
class when their route is activeCheck out the examples
directory to see how simple previously complex UI
and workflows are to create.
npm install react-router
# or
bower install react-router
This library is written with CommonJS modules. If you are using browserify, webpack, or similar, you can consume it like anything else installed from npm.
There is also a UMD build available on bower, find the library on
window.ReactRouter
.
var Route = require('react-router').Route;
React.renderComponent((
<Routes>
<Route handler={App}>
<Route name="about" handler={About}/>
<Route name="users" handler={Users}>
<Route name="user" path="/user/:userId" handler={User}/>
</Route>
</Route>
</Routes>
), document.body);
Or if JSX isn't your jam:
React.renderComponent((
Routes({},
Route({handler: App},
Route({name: "about", handler: About}),
Route({name: "users", handler: Users},
Route({name: "user", path: "/user/:userId", handler: User})
)
)
)
), document.body);
URLs will be matched to the deepest route, and then all the routes up the hierarchy are activated and their "handlers" (normal React components) will be rendered.
Paths are assumed from names unless specified.
Each handler will receive a params
property containing the matched
parameters form the url, like :userId
.
Handlers also receive a query
prop equal to a dictionary of the
current query params.
Parent routes will receive a activeRouteHandler
property. Its a function that
will render the active child route handler.
Here's the rest of the application:
var Link = require('react-router').Link;
var App = React.createClass({
render: function() {
return (
<div>
<ul>
<li><Link to="about">About</Link></li>
<li><Link to="users">Users</Link></li>
<li><Link to="user" userId="123">User 123</Link></li>
</ul>
<this.props.activeRouteHandler/>
</div>
);
}
});
var About = React.createClass({
render: function() {
return <h2>About</h2>;
}
});
var Users = React.createClass({
render: function() {
return (
<div>
<h2>Users</h2>
<this.props.activeRouteHandler/>
</div>
);
}
});
var User = React.createClass({
render: function() {
return <div>{this.props.params.userId}</div>
}
});
To better understand what is happening with activeRouteHandler
perhaps an
example without the router will help. Lets take the scenario where
/users/2
has been matched. Your render method, without this router,
might look something like this:
render: function() {
var user = <User params={{userId: 2}}/>;
var users = <Users activeRouteHandler={user}/>;
return <App activeRouteHandler={users}/>;
}
Instead, the router manages this view hierarchy for you.
Incredible screen-creation productivity - There is only one use-case when a user visits a route: render something. Every user interface has layers (or nesting) whether its a simple navbar or multiple levels of master-detail. Coupling nested routes to these nested views gets rid of a ton of work for the developer to wire all of it together when the user switches routes. Adding new screens could not get faster.
Immediate understanding of application structure - When routes are declared in one place, developers can easily construct a mental image of the application. It's essentially a sitemap. There's not a better way to get so much information about your app this quickly.
Code tractability - When a developer gets a ticket to fix a bug at as specific url they simply 1) look at the route config, then 2) go find the handler for that route. Every entry point into your application is represented by these routes.
URLs are your first thought, not an after-thought - With React Nested Router, you don't get UI on the page without configuring a url first. Fortunately, its wildly productive this way, too.
Configuration component for your router, all <Route/>
s must be
children of a <Routes/>
. It is the component you provide to
React.renderComponent(routes, el)
.
location - "hash"
or "history"
, defaults to "hash"
. Configures
what type of url you want, hash includes #/
in the url and works
without a server, if you use history
your server will need to support
it.
Configuration component to declare your application's routes and view hierarchy.
name - The name of the route, used in the Link
component and the
router's transition methods.
path - The path used in the URL, supporting dynamic segments. If
left undefined, the path will be defined by the name
, and if there is
no name, will default to /
. This path is always absolute from the URL
"root", even if the leading slash is left off. Nested routes do not
inherit the path of their parent.
handler - The component to be rendered when the route matches.
Routes can be nested. When a child route matches, the parent route's
handler will have an instance of the child route's handler available as
this.props.activeRouteHandler()
. You can then render it in the parent
passing in any additional props as needed.
<Routes>
<!-- path defaults to '/' since no name or path provided -->
<Route handler={App}>
<!-- path is automatically assigned to the name since it is omitted -->
<Route name="about" handler={About}/>
<Route name="users" handler={Users}>
<!-- note the dynamic segment in the path -->
<Route name="user" handler={User} path="/user/:id"/>
</Route>
</Route>
</Routes>
Or w/o JSX:
Route({handler: App},
Route({name: 'about', handler: About}),
Route({name: 'users', handler: Users},
Route({name: 'user', handler: User, path: '/user/:id'})
)
);
The value you pass to a route's handler
prop is another component that
is rendered to the page when that route is active. There are some special
props and static methods available to these components.
this.props.activeRouteHandler(extraProps) - The active child route handler. Use it in your render method to render the child route, passing in additional properties as needed.
this.props.params - When a route has dynamic segments like <Route path="users/:userId"/>
the dynamic values are available at
this.props.params.userId
, etc.
this.props.query - The query parameters from the url.
You can define static methods on your route handlers that will be called during route transitions.
willTransitionTo(transition, params) - Called when a route is about to render, giving you the opportunity to abort the transition. You can return a promise and the whole route hierarchy will wait for the promises to resolve before proceeding. This is especially useful for server-side rendering when you need to populate some data before the handler is rendered.
willTransitionFrom(transition, component) - Called when an active
route is being transitioned out giving you an opportunity to abort the
transition. The component
is the current component, you'll probably
need it to check its state to decide if you want to allow the
transition.
transition.abort() - aborts a transition
transition.redirect(to, params, query) - redirect to another route
transition.retry() - retrys a transition
var Settings = React.createClass({
statics: {
willTransitionTo: function(transition, params) {
return auth.isLoggedIn().then(function(loggedIn) {
if (!loggedIn)
return;
transition.abort();
return auth.logIn({transition: transition});
// in auth module call `transition.retry()` after being logged in
});
},
willTransitionFrom: function(transition, component) {
if (component.formHasUnsavedData())) {
if (!confirm('You have unsaved information, are you sure you want to leave this page?')) {
transition.abort();
}
}
}
}
//...
});
Creates an anchor tag that links to a route in the application. Also
gets the active
class automatically when the route matches. If you
change the path of your route, you don't have to change your links.
to - The name of the route to link to, or a full URL.
query - Object, Query parameters to add to the link. Access query
parameters in your route handler with this.props.query
.
[param] - Any parameters the route defines are passed by name through the link's properties.
Given a route like <Route name="user" path="/users/:userId"/>
:
<Link to="user" userId={user.id} query={{foo: bar}}>{user.name}</Link>
<!-- becomes one of these depending on your router and if the route is
active -->
<a href="/users/123?foo=bar" class="active">Michael</a>
<a href="#/users/123?foo=bar">Michael</a>
<!-- or if you have the full url already, you can just pass that in -->
<Link to="/users/123?foo=bar"/>
The router has several top-level methods that may be used to navigate around the application.
var Router = require('react-router')
transitionTo(routeNameOrPath, [params[, query]]) - Programatically transition to a new route.
Router.transitionTo('user', {id: 10}, {showAge: true});
Router.transitionTo('about');
Router.transitionTo('/users/10?showAge=true');
replaceWith(routeName, [params[, query]]) - Programatically replace current route with a new route. Does not add an entry into the browser history.
Router.replaceWith('user', {id: 10}, {showAge: true});
Router.replaceWith('about');
Router.replaceWith('/users/10?showAge=true');
goBack() - Programatically go back to the last route and remove the most recent entry from the browser history.
Router.goBack();
Please see CONTRIBUTING
This library is highly inspired by the Ember.js routing API. In general, its a translation of the Ember router api to React. Huge thanks to the Ember team for solving the hardest part already.
FAQs
Declarative routing for React
The npm package react-router receives a total of 8,765,830 weekly downloads. As such, react-router popularity was classified as popular.
We found that react-router demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.
Security News
ENISA’s 2024 report highlights the EU’s top cybersecurity threats, including rising DDoS attacks, ransomware, supply chain vulnerabilities, and weaponized AI.