react router params code example
Example 1: react router dom
npm install react-router-dom
Example 2: react router url params
import { Route, useParams } from "react-router-dom";
// Route with URL param of id
<Route path="/:id" children={<Child />} />
// We can use the `useParams` hook here to access
// the dynamic pieces of the URL.
let { id } = useParams();
Example 3: react js router parameters
// Declaramos la ruta
<Route path="/thanks/:status" component={ThanksPage} />
// Obtenemos la variable
import { useParams } from "react-router-dom";
const { status } = useParams();
Example 4: react router redirect
<Route exact path="/">
{loggedIn ? <Redirect to="/dashboard" /> : <PublicHomePage />}
</Route>
Example 5: react get route params
const Child = ({ match }) => (
<div>
<h3>ID: {match.params.id}</h3>
</div>
)
Example 6: router in react-router-dom
npm install react-router-dom
import {BrowserRouter, Switch, Route, Link} from "react-router-dom"
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
</ul>
</nav>
{/* A <Switch> looks through its children <Route>s and
renders the first one that matches the current URL. */}
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/users">
<Users />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
function Home() {
return <h2>Home</h2>;
}
function About() {
return <h2>About</h2>;
}
function Users() {
return <h2>Users</h2>;
}