Page Routing in React with React Router

React itself doesn't handle routing, so it relies on external libraries. React Router is a popular choice, offering different router components for various use cases. For production environments, BrowserRouter is typically used, while MemoryRouter is suitable for non-browser environments like Codux or testing.

Using MemoryRouter for Testing 

MemoryRouter is ideal for testing components in isolation, as it keeps the navigation state in memory. Here's how to use it:
1
2
3
4
5
6
7
8
9
10
11
12
import { createBoard } from '@wixc3/react-board';
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { MyComponent } from './my-component';  
export default createBoard({
   name: 'My component',
   Board: () => (
       <MemoryRouter>
           <MyComponent />
       </MemoryRouter>
   ),
});
Important!
If your component includes BrowserRouter, ensure it's separated from the component itself.

Configuring Routers for Different Environments 

To handle routing in both Codux boards and production, consider these approaches:
  1. Move BrowserRouter Above the App: Place BrowserRouter in your main entry file (e.g., index.js), and use MemoryRouter in your Codux boards or test files.
  2. Pass Router as a Prop: Modify your App component to accept a router component as a prop, defaulting to BrowserRouter. For Codux boards, pass MemoryRouter instead.
  3. Parallel Entry Implementation: Create a parallel implementation of your App component for Codux boards, using MemoryRouter.
Example: Production Navigation with BrowserRouter
For successful production navigation, here's an example of a component using BrowserRouter:
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import { HomePage } from './HomePage';
import { AboutPage } from './AboutPage';
const App = () => (
<BrowserRouter>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutPage} />
</Switch>
</BrowserRouter>
export default App;
This setup ensures that your application uses BrowserRouter for client-side routing in a production environment.