When building a React application, we often need to show different components based on the URL path the user visits. Think of it like having different rooms in a house - we need a way to move between them. Our challenge is to:
Let's look at our file structure first:
src/ ├── App.jsx ├── components/ │ ├── Home/ │ │ ├── index.js │ │ └── Home.jsx │ ├── Stocks/ │ │ ├── index.js │ │ └── Stocks.jsx │ └── Movies/ │ ├── index.js │ └── Movies.jsx └── index.css
// App.jsx
import { createBrowserRouter, RouterProvider } from 'react-router-dom';
import Home from './components/Home';
import Stocks from './components/Stocks';
import Movies from './components/Movies';
// Define our routes - think of this as a map of our application
const router = createBrowserRouter([
{
// The home page route - like the front door of our house
path: '/',
element: <Home />
},
{
// The stocks page - like entering the study
path: 'stocks',
element: <Stocks />
},
{
// The movies page - like entering the entertainment room
path: 'movies',
element: <Movies />
},
{
// The catch-all route - like having a sign for lost visitors
path: '*',
element: <h1>Page Not Found</h1>
}
]);
function App() {
return (
<div className='app'>
<h1>App Component</h1>
<RouterProvider router={router} />
</div>
);
}
export default App;
// App.jsx - JSX Version
import {
createBrowserRouter,
RouterProvider,
createRoutesFromElements,
Route
} from 'react-router-dom';
// Creating routes using JSX syntax - more familiar to React developers
const router = createBrowserRouter(
createRoutesFromElements(
<Route>
<Route path="/" element={<Home />} />
<Route path="stocks" element={<Stocks />} />
<Route path="movies" element={<Movies />} />
<Route path="*" element={<h1>Page Not Found</h1>} />
</Route>
)
);
Think of React Router like a building's navigation system:
Here are some common issues new developers face and how to solve them:
To verify your router is working correctly, try these steps:
This routing pattern is commonly used in:
To deepen your understanding, you might want to explore: