How to setup routing in React with React Router

How to setup routing in React with React Router

First step is to create a new React project. Check out how to do it here:

How to create React app with Vite
In your terminal: npm create vite@latest You will be prompted by the setup, choose a project name eg. myApp, and choose React from the list of frameworks. Then jump in and start developing: cd myAppnpm install # start development servernpm run dev

Next, install React Router:

npm install react-router-dom localforage match-sorter sort-by

Create folder src/routes, then within it add a component file.

Example:

// src/routes/Home.jsx

export default function Home() {
	return <h1>Hello world</h1>
}

Create file src/router.jsx and import your component as a route.

import {createBrowserRouter} from "react-router-dom";
import Home from "./routes/Home.jsx";

export default createBrowserRouter([
  {
    path: "/",
    element: <Home/>,
  },
])

In src/main.jsx add the following lines:

// src/main.jsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import router from "./router.jsx"; // add this line
import { RouterProvider } from "react-router-dom"; // add this line

import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <RouterProvider router={router} /> {/* add this line */}
  </React.StrictMode>
)

Now you can go to path /hello in your browser and see your rendered component.

Use Link component from React Router:

// src/routes/Home.jsx

import { Link} from "react-router-dom";

export default function Home() {
	return (
	  <div>
	    <h1>Hello world</h1>
      <Link to={`about`}>Go to about page</Link>
    </div>	
	)
}

Using parameters

Add parameters to your path in src/router.jsx like so:

import {createBrowserRouter} from "react-router-dom";
import Hello from "./routes/Hello.jsx";

export default createBrowserRouter([
  {
    path: "/hello/:message",
    element: <Hello/>,
  },
])

Using the parameter in your route component:

// src/routes/Hello.jsx

import { Link} from "react-router-dom";
import {useParams} from "react-router-dom";

export default function Hello() {
  let {message} = useParams()

	return (
	  <div>
	    <h1>{message}</h1>
      <Link to={`about`}>Go to about page</Link>
    </div>	
	)
}