React Routing and Vite

React Routing and Vite

Routing in React involves setting up and managing navigation within a React app. It allows developers to build single-page applications with multiple views, letting users move between different sections without reloading the page.

Here is how can we add Routing to out Vite React app:

1. The first step is getting react router dom installed:

npm install react-router-dom

2. In our main.jsx file, we only need to wrap our main component inside the Browser Router tags <BrowserRouter> <our module /> <BrowserRouter>, here is an example:

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { BrowserRouter } from "react-router-dom";
 
 
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
)        

3. In App.jsx we can now start using <Routes> and <Route>

import   './App.css'
import Home from './views/Home.jsx'
import Landing from './views/Landing';
import About from './views/About.jsx';
import { Route, Routes } from "react-router-dom"
 
 
function App() {
  return (
   <>
  
      <div className="App">
      <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/landing" element={<Landing />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </div>
    </>
 );
  
}
 
export default App        

4. Home, Landing and About will be our normal components:

About.jsx

const About = () =>
{
    return(
        <>
        <h1>This is my About page</h1>
        </>  
    )
}
export default About;        

Landing.jsx

const Landing = () =>
{
    return(
        <>
        <h1>This is my Landing page</h1>
        </>  
    )
}
export default Landing;        

Home.jsx

const Home = () =>
{
    return(
        <>
        <h1>This is my Home page</h1>
        </>  
    )
}
export default Home;        

As simple as that, out app is already able to provide navigation through the different views of the application.

要查看或添加评论,请登录

社区洞察

其他会员也浏览了