Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
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.
Declarative routing for React.
React Router keeps your UI in sync with the URL. Make the URL your first thought, not an after-thought.
Using npm:
$ npm install --save react-router@next
Then with a module bundler like webpack, use as you would anything else:
// using an ES6 transpiler, like babel
import { BrowserRouter, Match, Link } from 'react-router'
// not using an ES6 transpiler
var BrowserRouter = require('react-router').BrowserRouter
var Match = require('react-router').Match
var Link = require('react-router').Link
The UMD build is also available on unpkg:
<script src="https://unpkg.com/react-router@next/umd/react-router.min.js"></script>
You can find the library on window.ReactRouter
.
Please read our docs here.
tl;dr Declarative Composability.
We've never been this excited about React Router. Like you, we've learned a lot about React since we first picked it up. We built a Router the best we knew how along the way. What we've learned most is that we love React because of its declarative composability.
As we looked at the router, it didn't work that way because of the static route configuration. You couldn't even wrap a Route!
// NOPE!
const CoolRoute = (props) => <Route {...props} cool={true}/>
For apps to participate in rendering of route components, we had to
create APIs we were never actually comfortable with, like <Router createElement render>
and createRouterMiddleware
. We took
createElement
away from you and had to give it back!
We had to recreate the lifecycle hooks with onEnter
, onLeave
, and
onChange
. React already has componentWillMount
,
componentWillReceiveProps
and componentWillUnmount
.
Route configs described your view hierarchy. Turns out, React components already describe view hierarchy.
To code-split, we had to introduce getComponent
and getChildRoutes
.
Hot module replacement libs had to do specific hacks for routes to work.
The list goes on and on.
React Router was not a React router, it was a routing framework for React. An accidental framework with APIs that were not only redundant with React, but incredibly difficult to build an ecosystem around.
What did we do? We took everything we've learned and love about React
(and we're still learning!) and applied it to routing. It started with
the quest to actually render a <Route>
(we used to just strip their
props). It ended with removing the idea of routes completely (surprised
us too) and a completely component based API, which actually means no
API at all.
You control routing by rendering components and passing props. Finally, we have a solid base for us and others to build an ecosystem on top of.
In other words, it's Just React™ and you're going to love it.
We know things have been rocky. Our previous API was fighting against React, causing a ton of churn. With v4, our only API is components that receive props, so, it's hard to imagine a big change again. Now that we're embracing (not fighting) React's declarative composability, we think this API will last as long as React itself, because that's all it is.
Not only that, but we're excited to create and encourage building an ecosystem of addons to this stable base.
We've been pulled a lot of directions with bleeding edge use-cases that nobody really has generic answers for: server rendering, code-splitting while avoiding waterfalls, anticipating streamed server rendering, loading data before rendering anything, etc. We unconsciously tried to solve this stuff when all we really want to be doing is keeping rendered UI in sync with the url. That's our scope of responsibility.
By using components as our only API, features we had that are important to you can be implemented on top of these components.
We will be creating some addons and hope to see others too.
We have some code close to being published that will manage the scroll positions of window and individual elements.
We have a <ControlledRouter>
close to being published that makes redux
integration with React Router the same as ... uh ... integrating an
<input>
with Redux.
Because we are just components, you have the component lifecycle as transition hooks. They are completely parallel. The only difference is that the route transition hooks could be asynchronous. The problem with that was you weren't in the render lifecycle so you couldn't use React to indicate to the user something was happening.
<Route onEnter={(_, cb) => {
loadStuffForever(() => {
// WHAT IS THE USER SEEING RIGHT NOW?
cb()
})
}}/>
One use case was loading data and waiting to render the next screen until the data landed. With a component, you can save the previous children, render them while loading, and then render your new children when you're done. We'll have an example of this eventually.
Check out the "Route Config" example.
See below
We have started an addon that we hope people who are interested in this will take ownership of here: https://github.com/ReactTraining/react-router-addons-routes
We believe very strongly in iterative migration, not rewrites, for applications. We are working on a migration guide, but the basic strategy is that both versions will be runnable in tandem (due to npm limitations, we'll publish the previous version separately so both can be installed).
You will be able to take routes one-by-one and migrate them to the new API. Additionally, the config addon mentioned above may help out here.
It's in beta, will be released shortly. It's basically just v2 but w/o any warnings of deprecated 1.0 API.
No. Leave your package.json at v2/3 and move on with your life. We'll be merging bug fixes for v2/3 indefinitely.
We've received a ton of great feedback from people we really admire in the React community so we know we've found something special that's a bit unprecendented in the world of UI routing.
We've never been more excited about React Router. It's no longer a router for React, it is truly a React Router.
Thanks to our sponsors for supporting the development of React Router.
Also, thanks to BrowserStack for providing the infrastructure that allows us to run our build in real browsers.
FAQs
Declarative routing for React
The npm package react-router receives a total of 8,390,771 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
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.