On this tutorial we’re going to focus on find out how to get began with react router model 6 to navigate and render a number of componets in your single web page utility(spa)
Conditions
- A Fundamental React utility
- Fundamental data of react
Set up React Router
Step one after making a react app is to put in react router
To put in the react router open your command line and sort under code and hit enter to put in react router@6
npm set up react-router-dom@6
in case you are utilizing yarn then
yarn add react-router-dom@6
Setup React Router
The setup of react router could be very easy. Navigate to your src folder and open index.js file after then import BrowserRouter from ‘react-router-dom’ and wrap the foundation element with this.
After doing so your index.js file might seem like this
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
doc.getElementById("root")
);
How To Route the opposite Componets
We’re carried out with the inital setup and now we are able to create routes for different componets to render comply with me
Create Mutiple elements to Route
Now we’re creating a number of elements like dwelling.js signup.js and about.js and so forth.
import React from 'react'
operate Contacting() {
return (
<div className="bg-danger">
<p>That is the contact web page</p>
</div>
)
}
export default Contacting
Contact.js
import React from 'react'
operate AboutUs() {
return (
<div className="bg-primary">
<p>That is the about web page</p>
</div>
)
}
export default AboutUs
About.js
operate HomePage() {
return (
<div className="bg-success">
<p>That is the house web page</p>
</div>
);
}
export default HomePage
Dwelling.js
Defining Routes
Now open app.js file and outline the routes and path for particular element to render
import { Routes, Route } from "react-router-dom"
import HomePage from "./Dwelling.js"
import AboutUs from "./About.js"
import Contacting from "./Contact.js"
operate App() {
return (
<div className="App">
<Routes>
<Route path="https://dev.to/" factor={ <HomePage/> } />
<Route path="aboutus" factor={ <AboutUs/> } />
<Route path="contacting" factor={ <Contacting/> } />
</Routes>
</div>
)
}
export default App
use Hyperlink tag supplied by react-router-dom to navigate round
import { Hyperlink } from "react-router-dom";
operate Dwelling() {
return (
<div>
<h1>That is the house web page</h1>
<Hyperlink to="aboutus">Click on to view our about web page</Hyperlink>
<Hyperlink to="contacting">Click on to view our contact web page</Hyperlink>
</div>
);
}
export default Dwelling;
That is all for this tutorial now we are able to mess around with react router in your react app.
Be aware:-This may work just for react router model 6
comply with me on github to get extra tutorial like this