### Basic Routing Example
Source: https://v5.reactrouter.com/web/guides/quick-start/installation
An example demonstrating basic routing setup with BrowserRouter, Switch, Route, and Link.
```APIDOC
## Basic Routing Example
This example demonstrates how to set up basic routing in a React application using `react-router-dom`.
### Method
GET
### Endpoint
/
### Description
This example sets up a simple routing structure with a Home, About, and Users page. It utilizes `BrowserRouter`, `Switch`, `Route`, and `Link` components to manage navigation.
### Request Body
N/A
### Response
#### Success Response (200)
- Renders the appropriate component based on the current URL.
### Request Example
```javascript
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
);
}
function Home() {
return
Home
;
}
function About() {
return
About
;
}
function Users() {
return
Users
;
}
```
```
--------------------------------
### Basic Routing Example
Source: https://v5.reactrouter.com/web/guides/quick-start
Demonstrates basic routing setup with BrowserRouter, Switch, Route, and Link components.
```APIDOC
## Basic Routing Example
### Description
This example sets up basic navigation between Home, About, and Users pages using React Router.
### Code
```javascript
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
);
}
function Home() {
return
Home
;
}
function About() {
return
About
;
}
function Users() {
return
Users
;
}
```
```
--------------------------------
### Basic React Router Setup
Source: https://v5.reactrouter.com/web/guides/quick-start/2nd-example-nested-routing
Demonstrates a basic setup for React Router v5, including `BrowserRouter`, `Switch`, `Route`, and `Link` components. This example sets up navigation for Home, About, and Users pages, rendering the first matching route.
```javascript
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-react-router-dom";
export default function App() {
return (
{/* A looks through its children s and
renders the first one that matches the current URL. */}
);
}
function Home() {
return
Home
;
}
function About() {
return
About
;
}
function Users() {
return
Users
;
}
```
--------------------------------
### Basic React Native Router Setup
Source: https://v5.reactrouter.com/native/guides/quick-start/installation
A basic example demonstrating the core components of React Router Native: NativeRouter, Route, and Link. It sets up a simple navigation structure for Home, About, and Topics pages.
```javascript
import React from "react";
import { StyleSheet, Text, View, AppRegistry } from "react-native";
import { NativeRouter, Route, Link } from "react-router-native";
const Home = () => Home;
const About = () => About;
const Topic = ({ match }) => (
{match.params.topicId}
);
const Topics = ({ match }) => (
TopicsRendering with ReactComponentsProps v. State (
Please select a topic.
)}
/>
);
const App = () => (
HomeAboutTopics
);
const styles = StyleSheet.create({
container: {
marginTop: 25,
padding: 10
},
header: {
fontSize: 20
},
nav: {
flexDirection: "row",
justifyContent: "space-around"
},
navItem: {
flex: 1,
alignItems: "center",
padding: 10
},
subNavItem: {
padding: 5
},
topic: {
textAlign: "center",
fontSize: 15
}
});
AppRegistry.registerComponent("MyApp", () => App);
```
--------------------------------
### Express Static Routing Example
Source: https://v5.reactrouter.com/core/guides/philosophy/responsive-routes
Demonstrates how routes are declared upfront in Express before the application starts listening. This is an example of static routing.
```javascript
app.get("/", handleIndex);
app.get("/invoices", handleInvoices);
app.get("/invoices/:id", handleInvoice);
app.get("/invoices/:id/edit", handleInvoiceEdit);
app.listen();
```
--------------------------------
### Basic React Router Setup
Source: https://v5.reactrouter.com/web/guides/quick-start/keep-going
Sets up basic routing for a React application using BrowserRouter, Switch, Route, and Link. It defines navigation links for Home, About, and Users pages and renders the corresponding component based on the URL. This is a fundamental example for creating multi-page experiences in a single-page application.
```jsx
import React from "React";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
{/* A looks through its children s and
renders the first one that matches the current URL. */}
);
}
function Home() {
return
Home
;
}
function About() {
return
About
;
}
function Users() {
return
Users
;
}
```
--------------------------------
### Basic Route Component Setup in React Router
Source: https://v5.reactrouter.com/native/api/Redirect/exact-bool
A fundamental example of setting up the BrowserRouter and Route components to render different components based on the current URL path. It demonstrates rendering 'Home' for '/' and 'NewsFeed' for '/news'.
```javascript
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
// Assume Home and NewsFeed components are defined elsewhere
// const Home = () =>
Home Component
;
// const NewsFeed = () =>
NewsFeed Component
;
ReactDOM.render(
,
document.getElementById('root') // Assuming 'node' is a placeholder for the DOM element
);
```
--------------------------------
### Express Style Routing Example
Source: https://v5.reactrouter.com/web/guides/philosophy/static-routing
Demonstrates a typical way to declare routes in Express before the application starts listening. This is an example of 'static routing'.
```javascript
// Express Style routing:
app.get("", handleIndex);
app.get("/invoices", handleInvoices);
app.get("/invoices/:id", handleInvoice);
app.get("/invoices/:id/edit", handleInvoiceEdit);
app.listen();
```
--------------------------------
### Basic React Router Setup
Source: https://v5.reactrouter.com/web/guides/quick-start/1st-example-basic-routing
Demonstrates a basic React application setup using React Router. It includes setting up a BrowserRouter, navigation links (Home, About, Users), and routes that render different components based on the URL.
```javascript
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
);
}
function Home() {
return
Home
;
}
function About() {
return
About
;
}
function Users() {
return
Users
;
}
```
--------------------------------
### Install create-react-app
Source: https://v5.reactrouter.com/web
Command to install the create-react-app tool and create a new React project. This is a prerequisite for using React Router in a web app.
```bash
npx create-react-app demo-app
cd demo-app
```
--------------------------------
### Install React Router DOM
Source: https://v5.reactrouter.com/web/guides/quick-start/1st-example-basic-routing
Installs the 'react-router-dom' package, which is necessary for implementing routing in React web applications. This is typically done using npm or yarn.
```bash
yarn add react-router-dom
```
--------------------------------
### React Router: Basic BrowserRouter Example
Source: https://v5.reactrouter.com/web/api/MemoryRouter/Redirect
Demonstrates the basic setup using `BrowserRouter` for HTML5 history API-based routing. It wraps the application to enable routing functionalities. Requires React >= 16.8.
```javascript
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
function HomePage() { return
Home
; }
function AboutPage() { return
About
; }
ReactDOM.render(
,
document.getElementById("root")
);
```
--------------------------------
### Express Style Routing Example
Source: https://v5.reactrouter.com/core/Redirect
An example of how routes are declared in Express, a popular Node.js web application framework. This demonstrates traditional static routing where routes are defined before the application starts listening for requests.
```javascript
app.get("/", handleIndex);
app.get("/invoices", handleInvoices);
app.get("/invoices/:id", handleInvoice);
app.get("/invoices/:id/edit", handleInvoiceEdit);
app.listen();
```
--------------------------------
### Basic Routing Example with React Router
Source: https://v5.reactrouter.com/web
A fundamental React Router example demonstrating basic navigation between Home, About, and Users pages. It utilizes BrowserRouter, Switch, Route, and Link components.
```javascript
import React from "";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
{/* A looks through its children s and
renders the first one that matches the current URL. */}
);
}
function Home() {
return
Home
;
}
function About() {
return
About
;
}
function Users() {
return
Users
;
}
```
--------------------------------
### Express Style Routing Example
Source: https://v5.reactrouter.com/core/Router
This code snippet demonstrates static route configuration in Express.js, where routes are declared before the application starts listening. It defines GET endpoints for the root path, invoices, and specific invoice details with parameters.
```javascript
// Express Style routing:
app.get("/", handleIndex);
app.get("/invoices", handleInvoices);
app.get("/invoices/:id", handleInvoice);
app.get("/invoices/:id/edit", handleInvoiceEdit);
app.listen();
```
--------------------------------
### MemoryRouter with Initial Entries and Index
Source: https://v5.reactrouter.com/core/api/Prompt/message-func
This example demonstrates configuring MemoryRouter with an initial set of history entries and specifying the starting index within that history stack.
```javascript
```
--------------------------------
### Install React Router Native
Source: https://v5.reactrouter.com/native/guides/quick-start
Instructions for installing React Router Native using npm or yarn. This is the first step to integrating routing into your React Native project.
```bash
npm install react-router-native
# or
yarn add react-router-native
```
--------------------------------
### Basic React Native Router Example
Source: https://v5.reactrouter.com/native/guides/quick-start
A fundamental example showcasing the usage of NativeRouter, Route, and Link components from React Router Native. It demonstrates basic navigation between Home, About, and Topics screens, including nested routes for topics.
```javascript
import React from "react";
import { StyleSheet, Text, View, AppRegistry } from "react-native";
import { NativeRouter, Route, Link } from "react-router-native";
const Home = () => Home;
const About = () => About;
const Topic = ({ match }) => (
{match.params.topicId}
);
const Topics = ({ match }) => (
TopicsRendering with ReactComponentsProps v. State (
Please select a topic.
)}
/>
);
const App = () => (
HomeAboutTopics
);
const styles = StyleSheet.create({
container: {
marginTop: 25,
padding: 10
},
header: {
fontSize: 20
},
nav: {
flexDirection: "row",
justifyContent: "space-around"
},
navItem: {
flex: 1,
alignItems: "center",
padding: 10
},
subNavItem: {
padding: 5
},
topic: {
textAlign: "center",
fontSize: 15
}
});
AppRegistry.registerComponent("MyApp", () => App);
```
--------------------------------
### React Router - StaticRouter Context Example
Source: https://v5.reactrouter.com/web/example/static-router
A basic example demonstrating the use of `StaticRouter` with context, suitable for server-side rendering or static site generation. It's deployed using react-codesandboxer for interactive testing.
```javascript
// (includes the RouteStatus component below e.g. for 404 errors)
```
--------------------------------
### Initialize Sidebar with Specific Route using MemoryRouter
Source: https://v5.reactrouter.com/web/guides/testing/starting-at-specific-routes
This example shows how to use the `initialEntries` prop of `MemoryRouter` to set the starting route for a component during testing. This is useful for testing scenarios where a component's behavior depends on the current URL, such as highlighting an active user in a sidebar.
```javascript
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
// Assume Sidebar component and expectUserToBeActive function are defined elsewhere
test("current user is active in sidebar", () => {
render(
);
expectUserToBeActive(2);
});
```
--------------------------------
### Express Static Routing Example
Source: https://v5.reactrouter.com/core/guides/philosophy/nested-routes
This snippet demonstrates static route configuration in Express.js, where routes are declared before the application starts listening. It includes examples for handling root, invoices, and specific invoice routes.
```javascript
// Express Style routing:
app.get("/"), handleIndex;
app.get("/invoices"), handleInvoices;
app.get("/invoices/:id"), handleInvoice;
app.get("/invoices/:id/edit"), handleInvoiceEdit;
app.listen();
```
--------------------------------
### MemoryRouter with Initial Entries and Index
Source: https://v5.reactrouter.com/core/api/match/Route
This example demonstrates configuring `` with `initialEntries` to predefine the history stack and `initialIndex` to set the starting point within that stack. It supports both string URLs and location objects.
```jsx
```
--------------------------------
### Basic BrowserRouter Setup (JavaScript)
Source: https://v5.reactrouter.com/web/guides/primary-components/navigation-or-route-changers
This code illustrates the basic setup of a React Router application using BrowserRouter. It shows how to wrap the top-level App component with BrowserRouter and render it to the DOM. This configuration is essential for enabling client-side routing.
```javascript
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
function App() {
return
Hello React Router
;
}
ReactDOM.render(
,
document.getElementById("root")
);
```
--------------------------------
### React Router Redirects (Auth) - Basic Setup
Source: https://v5.reactrouter.com/web/example/auth-workflow
This snippet sets up the basic React context and state management for authentication. It defines a context to hold the authentication status and a provider to manage state changes, which is crucial for conditional rendering of routes.
```javascript
import React, { useContext, createContext, useState } from "react";
const AuthContext = createContext(null);
export const AuthProvider = ({ children }) => {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const login = () => {
setIsAuthenticated(true);
};
const logout = () => {
setIsAuthenticated(false);
};
return (
{children}
);
};
export const useAuth = () => {
return useContext(AuthContext);
};
```
--------------------------------
### Core Components
Source: https://v5.reactrouter.com/web/example/no-match
Documentation for core React Router components used for setting up routing and navigation.
```APIDOC
## BrowserRouter
### Description
A router that uses HTML5 history API (pushState, replaceState and the popstate event) to keep your UI in sync with the URL.
### Props
- **basename** (string) - Optional - The base URL to use for all locations.
- **getUserConfirmation** (func) - Optional - Callback to use when the user is attempting to leave the current page.
- **forceRefresh** (boolean) - Optional - If true, will force a full page refresh on navigation.
- **keyLength** (number) - Optional - The length of location keys.
- **children** (node) - Required - The child routes to render.
## HashRouter
### Description
A router that uses the hash part of the URL to keep your UI in sync with the URL.
### Props
- **basename** (string) - Optional - The base URL to use for all locations.
- **getUserConfirmation** (func) - Optional - Callback to use when the user is attempting to leave the current page.
- **hashType** (string) - Optional - The type of hash to use (e.g. 'slash', 'none').
- **children** (node) - Required - The child routes to render.
## Link
### Description
A component for declarative, declarative navigation.
### Props
- **to** (string | object | func) - Required - The destination path or object.
- **replace** (boolean) - Optional - If true, the link will replace the current entry in the history stack.
- **innerRef** (func | RefObject) - Optional - A ref to be attached to the inner anchor element.
- **component** (React.Component) - Optional - A custom component to render instead of an anchor tag.
- **others** - Any other props will be passed to the anchor tag.
## NavLink
### Description
A special version of `Link` that knows whether or not it is "active", CSS classes and styles are applied based on this state.
### Props
- **className** (string | func) - Optional - The CSS class to apply when the link is active.
- **activeClassName** (string) - Optional - The CSS class to apply when the link is active.
- **style** (object | func) - Optional - The inline style to apply when the link is active.
- **activeStyle** (object | func) - Optional - The inline style to apply when the link is active.
- **exact** (boolean) - Optional - If true, will only match the exact path.
- **strict** (boolean) - Optional - If true, will only match the strict path.
- **isActive** (func) - Optional - A function to determine if the link is active.
- **location** (object) - Optional - The current location object.
- **aria-current** (string) - Optional - The ARIA property to set when the link is active.
## Prompt
### Description
Used to render a confirmation dialog when a user is trying to leave a page.
### Props
- **message** (string | func) - Required - The message to display or a function that returns the message.
- **when** (boolean) - Required - If true, the prompt will be rendered.
## MemoryRouter
### Description
A router that keeps your URL in sync by storing the history internally in memory.
### Props
- **initialEntries** (array) - Optional - The initial list of entries in the history stack.
- **initialIndex** (number) - Optional - The initial index in the history stack.
- **getUserConfirmation** (func) - Optional - Callback to use when the user is attempting to leave the current page.
- **keyLength** (number) - Optional - The length of location keys.
- **children** (node) - Required - The child routes to render.
## Redirect
### Description
Used to declaratively redirect to a new location.
### Props
- **to** (string | object) - Required - The destination path or object.
- **push** (boolean) - Optional - If true, will push the new location onto the history stack.
- **from** (string) - Optional - The path to match for the redirect.
- **exact** (boolean) - Optional - If true, will only match the exact path.
- **strict** (boolean) - Optional - If true, will only match the strict path.
- **sensitive** (boolean) - Optional - If true, will match paths with or without a trailing slash.
## Route
### Description
A component that renders UI based on the matched URL.
### Props
- **Route render methods** - Various ways to render content.
- **Route props** - Props available to the render function.
- **component** (React.Component) - Optional - The component to render.
- **render** (func) - Optional - A function that returns a React node to render.
- **children** (func) - Optional - A function that returns a React node to render, always called.
- **path** (string | string[]) - Optional - The path to match.
- **exact** (boolean) - Optional - If true, will only match the exact path.
- **strict** (boolean) - Optional - If true, will only match the strict path.
- **location** (object) - Optional - The location object to match.
- **sensitive** (boolean) - Optional - If true, will match paths with or without a trailing slash.
## Router
### Description
A low-level routing component that uses a mutable history object.
### Props
- **history** (object) - Required - The history object to use.
- **children** (node) - Required - The child routes to render.
## StaticRouter
### Description
A router for non-browser environments. Useful for server-side rendering.
### Props
- **basename** (string) - Optional - The base URL to use for all locations.
- **location** (string | object) - Optional - The location to use for the initial render.
- **context** (object) - Optional - The context object to use for server-side rendering.
- **children** (node) - Required - The child routes to render.
## Switch
### Description
A component that renders the first child `Route` or `Redirect` that matches the location.
### Props
- **location** (object) - Optional - The location to match.
- **children** (node) - Required - The child routes to render.
```
--------------------------------
### Basic React Router Setup
Source: https://v5.reactrouter.com/web/guides/quick-start/installation
Sets up basic routing in a React application using BrowserRouter, Switch, Route, and Link components from react-router-dom. It demonstrates how to define different routes for Home, About, and Users pages and navigate between them.
```javascript
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
{/* A looks through its children s and
renders the first one that matches the current URL. */}
);
}
function Home() {
return
Home
;
}
function About() {
return
About
;
}
function Users() {
return
Users
;
}
```
--------------------------------
### Initialize Component with Specific Route using MemoryRouter
Source: https://v5.reactrouter.com/web/guides/testing/context
Shows how to start a React component within a specific route using the `initialEntries` prop of `MemoryRouter`. This is useful for testing scenarios where a component's behavior depends on its initial location in the routing history, allowing for precise state setup.
```javascript
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
// Assume Sidebar and expectUserToBeActive are defined elsewhere
// class Sidebar extends React.Component { ... }
// const expectUserToBeActive = (userId) => { ... };
test("current user is active in sidebar", () => {
render(
);
expectUserToBeActive(2);
});
```
--------------------------------
### Utilities
Source: https://v5.reactrouter.com/web/example/no-match
Documentation for utility functions provided by React Router.
```APIDOC
## generatePath
### Description
Generates a path for the given pattern and parameters.
### Parameters
- **pattern** (string) - Required - The route pattern.
- **params** (object) - Optional - An object of parameters to fill in the pattern.
## history
### Description
React Router's history object is mutable. Use with caution.
## location
### Description
Represents the current URL.
## match
### Description
An object containing information about a matched route.
### null matches
### Description
When a route does not match, the match object will be null.
## matchPath
### Description
A utility for matching a path against a location.
### Parameters
- **pathname** (string) - Required - The pathname to match.
- **props** (object) - Optional - Props for the match.
### Returns
- An object containing match information or null if no match is found.
## withRouter
### Description
A higher-order component that provides routing information to the wrapped component.
### WrappedComponent
- **wrappedComponentRef** (func) - Optional - A ref to be attached to the wrapped component.
```
--------------------------------
### React Router Sidebar Example (JavaScript)
Source: https://v5.reactrouter.com/web/example/sidebar
This JavaScript code snippet demonstrates a basic sidebar implementation using React Router. It sets up routes and renders components based on the URL, suitable for a single-page application.
```javascript
import React from 'react';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
const Home = () =>
Home
;
const About = () =>
About
;
const Contact = () =>
Contact
;
const Sidebar = () => (
);
const App = () => (
);
export default App;
```
--------------------------------
### React Router Route Configuration Example
Source: https://v5.reactrouter.com/web/example/route-config
A basic example demonstrating how to configure routes in React Router, often used for nested routing or dynamic route handling. This snippet shows how to render a component and pass down nested routes.
```javascript
```
--------------------------------
### Static Routing Configuration in Express
Source: https://v5.reactrouter.com/core/guides/philosophy/backstory
Demonstrates how routes are declared statically before the application listens in Express. This example shows basic GET routes for different URL paths.
```javascript
// Express Style routing:
app.get("/", handleIndex);
app.get("/invoices", handleInvoices);
app.get("/invoices/:id", handleInvoice);
app.get("/invoices/:id/edit", handleInvoiceEdit);
app.listen();
```
--------------------------------
### Initialize Component with Specific Route using MemoryRouter
Source: https://v5.reactrouter.com/web/guides/testing/navigating
Shows how to use the `initialEntries` prop of MemoryRouter to start a test at a specific URL. This is useful for testing components that depend on the current location or route parameters.
```javascript
import React from 'react';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import Sidebar from './Sidebar'; // Assuming Sidebar is in a separate file
// Mock components or data if necessary
const users = [
{ path: '/users/1', name: 'Alice' },
{ path: '/users/2', name: 'Bob' },
];
// Dummy Link component for demonstration if not imported directly
const Link = ({ to, children }) => {children};
// Dummy implementation of Sidebar for testing context
class Sidebar extends React.Component {
render() {
return (
{users.map(user => (
{user.name}
))}
);
}
}
test('current user is active in sidebar', () => {
render(
);
// Replace with actual assertions based on your component's behavior
// expectUserToBeActive(2);
console.log('Test executed: component rendered with initialEntries set to /users/2.');
// Example assertion if you had a way to check active user:
// expect(screen.getByText('Bob')).toHaveClass('active');
});
```
--------------------------------
### Hooks
Source: https://v5.reactrouter.com/web/example/no-match
Documentation for React Router hooks.
```APIDOC
## useHistory
### Description
Returns the history object.
## useLocation
### Description
Returns the location object.
## useParams
### Description
Returns an object with URL parameters.
## useRouteMatch
### Description
Returns the match object for the current route.
```
--------------------------------
### Basic Server Rendering Setup with StaticRouter
Source: https://v5.reactrouter.com/web/guides/server-rendering/404-401-or-any-other-status
This snippet shows the fundamental setup for server-side rendering using React Router. It demonstrates wrapping the application with `` on the server, passing the request URL and a context object.
```javascript
// client
// server (not the complete story)
```
--------------------------------
### React Router - Basic Switch Example
Source: https://v5.reactrouter.com/web/example/basic
A fundamental example demonstrating the use of the `` component in React Router v5. The `` component iterates through its children `` components and renders the first one that matches the current location. This is crucial for defining distinct routes within an application.
```javascript
import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom';
function Home() {
return