What is <StaticRouter> in React Native?

A static router refers to a router that never changes location. It is widely used in places requiring server-side rendering. For example, if a user is not just clicking around, the router location will never change.

static router is commonly used in simple testing environments where the location is plugged in to make certain assertions on the rendered output.

Code

Let’s look at the example code, where a node server sends a 302 error for simple redirects and HTML otherwise:

// import libraries
import http from "http";
import React from "react";
import ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router";
// basic use of router
<StaticRouter location={req.url} context={context}>
        <App />
      </StaticRouter>
);

Properties

The following are the properties that can be used as a parameter for <StaticRouter>:

1. Basename

basename: string: This refers to the base URL of every location. The proper format is to use a leading slash (look at the example below).

<StaticRouter basename="/hello">
  <Link to="/world"/> // renders <a href="/hello/world">
</StaticRouter>

2. Location (string)

location: string: This refers to the req.url (on the node servers), the URL received from the server.

<StaticRouter location={req.url}>
  <App />
</StaticRouter>

3. Location (object)

location: object: An object-type of the location. This object is shaped in the following format: {pathname, search, hash, state}.

<StaticRouter location={{ pathname: "/hello1" }}>
  <App />
</StaticRouter>

4. Context (object)

context: object: This is just a simple JS object. The components are allowed to add information to the object during the rendering process.

const context = {}
<StaticRouter context={context}>
  <App />
</StaticRouter>

Given a route matches, the context object is directly passed to the component as staticContext prop.

if (context.status === "404") 
{
  // ...
}
Copyright ©2024 Educative, Inc. All rights reserved