How to Pass Parameter in Reactjs Router ?

React.js

Nicesnippets

1202

05-03-2020


Hello Guys,

This simple article demonstrates of react params from url. i explained simply step by step react js parameter from url. We will use react param route. This article will give you simple example of param react router. Let's get started with react router get id parameter.

You have to pass id or slug in react route first you have to import "useParams" from "react-router-dom". then you can easly get the all the parameter.

Routing Package Install Command

npm install react-router-dom

/src/App.js file

import React from 'react';

import './App.css';

import Header from './Header';

function App() {

return (

<div>

<Header />

</div>

);

}

export default App;

/src/Header.js file

import React from 'react'

import {

BrowserRouter as Router,

Switch,

Route,

Link,

useParams

} from "react-router-dom";

import Home from './Home';

import AboutUs from './AboutUs';

import ContactUs from './ContactUs';

class Header extends React.Component{

render(){

return(

<div>

<div className="row">

<div className="col-md-12">

<Router>

<nav className="navbar navbar-expand-sm bg-dark navbar-dark">

<ul className="navbar-nav">

<li className="nav-item active">

<Link to="/" className="nav-link">Home</Link>

</li>

<li className="nav-item">

<Link to="/category/1" className="nav-link">Category 1</Link>

</li>

<li className="nav-item">

<Link to="/category/2" className="nav-link">Category 2</Link>

</li>

<li className="nav-item">

<Link to="/category/3" className="nav-link">Category 3</Link>

</li>

</ul>

</nav>

<br />

<Switch>

<Route exact path="/">

<Home />

</Route>

<Route path="/category/:id" children={<Child />} />

</Switch>

</Router>

</div>

</div>

</div>

)

}

}

export default Header;

function Child() {

// We can use the `useParams` hook here to access

// the dynamic pieces of the URL.

let { id } = useParams();

return (

<div>

<h3>ID: {id}</h3>

</div>

);

}

I hope it can help you...


Recommended Posts