Session 9: React Router (Version 6)
React Router is a fully-featured client and server-side routing library for React, a JavaScript library for building user interfaces. React Router runs anywhere React runs; on the web, on the server with node.js, and on React Native.
Installation
npm install --save react-router-dom
hoặc
yarn add react-router-dom
Connect the URL
First things first, we want to connect your app to the browser's URL: import BrowserRouter and render it around your whole app.
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<App />
</BrowserRouter>,
);
Add some links
import { Link } from 'react-router-dom';
export default function App() {
return (
<div>
<h1>Bookkeeper</h1>
<nav
style={{
borderBottom: 'solid 1px',
paddingBottom: '1rem',
}}
>
<Link to='/invoices'>Invoices</Link> | <Link to='/expenses'>Expenses</Link>
</nav>
</div>
);
}