
Security News
Browserslist-rs Gets Major Refactor, Cutting Binary Size by Over 1MB
Browserslist-rs now uses static data to reduce binary size by over 1MB, improving memory use and performance for Rust-based frontend tools.
react-router-config
Advanced tools
The react-router-config package is used to simplify the process of configuring routes in a React application. It allows you to define your routes in a configuration object, making it easier to manage and understand complex routing structures.
Route Configuration
This feature allows you to define your routes in a nested configuration object. This makes it easier to manage and understand complex routing structures.
const routes = [
{
component: App,
routes: [
{
path: '/home',
exact: true,
component: Home
},
{
path: '/about',
component: About
}
]
}
];
Rendering Routes
The renderRoutes function is used to render the routes defined in the configuration object. This function takes the routes array and returns the corresponding React elements.
import { renderRoutes } from 'react-router-config';
const App = ({ route }) => (
<div>
{renderRoutes(route.routes)}
</div>
);
Route Matching
The matchRoutes function is used to match a given pathname against the route configuration. This is useful for server-side rendering and data fetching.
import { matchRoutes } from 'react-router-config';
const branch = matchRoutes(routes, '/some/path');
react-router is the core package for routing in React applications. It provides a more flexible and powerful API for defining routes, but it does not offer the same configuration-based approach as react-router-config. Instead, routes are defined using JSX components.
react-router-dom is a package that provides DOM bindings for react-router. It includes components like BrowserRouter and Link, which are essential for web applications. Like react-router, it does not use a configuration-based approach for defining routes.
found is a routing library for React that emphasizes a configuration-based approach similar to react-router-config. It provides a more powerful and flexible API for route matching and data fetching, but it has a steeper learning curve.
Static route configuration helpers for React Router.
This is alpha software, it needs:
Using npm:
$ npm install --save react-router-config
Then with a module bundler like webpack, use as you would anything else:
// using an ES6 transpiler, like babel
import { matchRoutes, renderRoutes } from "react-router-config";
// not using an ES6 transpiler
var matchRoutes = require("react-router-config").matchRoutes;
The UMD build is also available on unpkg:
<script src="https://unpkg.com/react-router-config/umd/react-router-config.min.js"></script>
You can find the library on window.ReactRouterConfig
With the introduction of React Router v4, there is no longer a centralized route configuration. There are some use-cases where it is valuable to know about all the app's potential routes such as:
This project seeks to define a shared format for others to build patterns on top of.
Routes are objects with the same properties as a <Route>
with a couple differences:
component
(no render
or children
)routes
key for sub routesprops.route
inside the component
, this object is a reference to the object used to render and match.key
prop to prevent remounting component when transition was made from route with the same component and same key
propconst routes = [
{
component: Root,
routes: [
{
path: "/",
exact: true,
component: Home
},
{
path: "/child/:id",
component: Child,
routes: [
{
path: "/child/:id/grand-child",
component: GrandChild
}
]
}
]
}
];
Note: Just like <Route>
, relative paths are not (yet) supported. When it is supported there, it will be supported here.
matchRoutes(routes, pathname)
Returns an array of matched routes.
import { matchRoutes } from "react-router-config";
const branch = matchRoutes(routes, "/child/23");
// using the routes shown earlier, this returns
// [
// routes[0],
// routes[0].routes[1]
// ]
Each item in the array contains two properties: routes
and match
.
routes
: A reference to the routes array used to matchmatch
: The match object that also gets passed to <Route>
render methods.branch[0].match.url;
branch[0].match.isExact;
// etc.
You can use this branch of routes to figure out what is going to be rendered before it actually is rendered. You could do something like this on the server before rendering, or in a lifecycle hook of a component that wraps your entire app
const loadBranchData = (location) => {
const branch = matchRoutes(routes, location.pathname)
const promises = branch.map(({ route, match }) => {
return route.loadData
? route.loadData(match)
: Promise.resolve(null)
})
return Promise.all(promises)
}
// useful on the server for preloading data
loadBranchData(req.url).then(data => {
putTheDataSomewhereTheClientCanFindIt(data)
})
// also useful on the client for "pending navigation" where you
// load up all the data before rendering the next page when
// the url changes
// THIS IS JUST SOME THEORETICAL PSEUDO CODE :)
class PendingNavDataLoader extends Component {
state = {
previousLocation: null,
currentLocation: this.props.location
}
static getDerivedStateFromProps(props, state) {
const currentLocation = props.location
const previousLocation = state.currentLocation
const navigated = currentLocation !== previousLocation
if (navigated) {
// save the location so we can render the old screen
return {
previousLocation,
currentLocation
}
}
return null
}
componentDidUpdate(prevProps) {
const navigated = prevProps.location !== this.props.location
if (navigated) {
// load data while the old screen remains
loadNextData(routes, this.props.location).then(data => {
putTheDataSomewhereRoutesCanFindIt(data)
// clear previousLocation so the next screen renders
this.setState({
previousLocation: null
})
})
}
}
render() {
const { children, location } = this.props
const { previousLocation } = this.state
// use a controlled <Route> to trick all descendants into
// rendering the old location
return (
<Route
location={previousLocation || location}
render={() => children}
/>
)
}
}
// wrap in withRouter
export default withRouter(PendingNavDataLoader)
/////////////
// somewhere at the top of your app
import routes from './routes'
<BrowserRouter>
<PendingNavDataLoader routes={routes}>
{renderRoutes(routes)}
</PendingNavDataLoader>
</BrowserRouter>
Again, that's all pseudo-code. There are a lot of ways to do server rendering with data and pending navigation and we haven't settled on one. The point here is that matchRoutes
gives you a chance to match statically outside of the render lifecycle. We'd like to make a demo app of this approach eventually.
renderRoutes(routes, extraProps = {}, switchProps = {})
In order to ensure that matching outside of render with matchRoutes
and inside of render result in the same branch, you must use renderRoutes
instead of <Route>
inside your components. You can render a <Route>
still, but know that it will not be accounted for in matchRoutes
outside of render.
import { renderRoutes } from "react-router-config";
const routes = [
{
component: Root,
routes: [
{
path: "/",
exact: true,
component: Home
},
{
path: "/child/:id",
component: Child,
routes: [
{
path: "/child/:id/grand-child",
component: GrandChild
}
]
}
]
}
];
const Root = ({ route }) => (
<div>
<h1>Root</h1>
{/* child routes won't render without this */}
{renderRoutes(route.routes)}
</div>
);
const Home = ({ route }) => (
<div>
<h2>Home</h2>
</div>
);
const Child = ({ route }) => (
<div>
<h2>Child</h2>
{/* child routes won't render without this */}
{renderRoutes(route.routes, { someProp: "these extra props are optional" })}
</div>
);
const GrandChild = ({ someProp }) => (
<div>
<h3>Grand Child</h3>
<div>{someProp}</div>
</div>
);
ReactDOM.render(
<BrowserRouter>
{/* kick it all off with the root route */}
{renderRoutes(routes)}
</BrowserRouter>,
document.getElementById("root")
);
FAQs
Static route config matching for React Router
The npm package react-router-config receives a total of 462,342 weekly downloads. As such, react-router-config popularity was classified as popular.
We found that react-router-config demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 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
Browserslist-rs now uses static data to reduce binary size by over 1MB, improving memory use and performance for Rust-based frontend tools.
Research
Security News
Eight new malicious Firefox extensions impersonate games, steal OAuth tokens, hijack sessions, and exploit browser permissions to spy on users.
Security News
The official Go SDK for the Model Context Protocol is in development, with a stable, production-ready release expected by August 2025.