I’m trying to figure out the basics of React, and I can’t find any explanation for the behaviour I’m seeing. When I try to use routes, the app acts as if the path is always "/": no route is ever matched other than path="/", and the console gives me the warning ‘No routes matched location "/"’.
index.js
import React from 'react';
import {createRoot} from 'react-dom/client';
import {NativeRouter} from 'react-router-native';
import './index.css';
import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<NativeRouter>
<App />
</NativeRouter>
</React.StrictMode>
);
App.js
import {Routes, Route} from 'react-router-native';
function App() {
return (
<Routes>
<Route path="/about" element={<About/>} />
</Routes>
)
}
function Home() {
return (<div style={{ padding: 20 }}>
<h2>Home View</h2>
<p>Lorem ipsum dolor sit amet, consectetur adip.</p>
</div>
);
}
function About() {
return (
<div style={{ padding: 20 }}>
<h2>About View</h2>
<p>ABOOOOUT.</p>
</div>
);
}
export default App;
I tried running this with npm start and expected a blank page for localhost:3000 and a page displaying "About View" for localhost:3000/about. The tutorial I copied most of this code from seems to suggest it should do exactly that.
Edit: for clarification, no matter what path I try, the page is always blank. The path "/about" does not work as intended.
>Solution :
If you are trying to use the NativeRouter in a web browser then you’ll need to manually specify the initial route path to match and handle navigating around the app via links. "/" is the default initial route. The NativeRouter isn’t coupled to the Browser’s URL in the address bar the way the BrowserRouter is. This is similar to the way the MemoryRouter works.
See NativeRouter.
declare function NativeRouter( props: NativeRouterProps ): React.ReactElement; interface NativeRouterProps extends MemoryRouterProps {}
Example:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { NativeRouter as Router } from "react-router-native";
import App from "./App";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<Router>
<App />
</Router>
</StrictMode>
);
mport { Routes, Route, Link } from "react-router-native";
import { Text } from "react-native";
export default function App() {
return (
<div className="App">
<ul>
<li>
<Link to="/">
<Text>Home</Text>
</Link>
</li>
<li>
<Link to="/about">
<Text>About</Text>
</Link>
</li>
</ul>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
);
}

