useparams react router code example

Example 1: usehistory, uselocation

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

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    
  );
}

Example 2: usematch react router

import React from 'react'
import ReactDOM from 'react-dom'
import { useParams } from 'react-router-dom'

function BlogPost() {
  // We can call useParams() here to get the params,
  // or in any child element as well!
  let { slug } = useParams()
  // ...
}

ReactDOM.render(
  
    
{/* No weird props here, just use regular `children` elements! */}
, document.getElementById('root') )

Example 3: useparams react hooks

import React from "react";
import ReactDOM from "react-dom";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  useParams
} from "react-router-dom";

function BlogPost() {
  let { slug } = useParams();
  return 
Now showing post {slug}
; } ReactDOM.render( , node );

Example 4: react router dom current path hook

import { useLocation } from 'react-router-dom'

// Location is, for example: http://localhost:3000/users/new

// Care! MyComponent must be inside Router to work
const MyComponent = () => {
	const location = useLocation()
    
    // location.pathname is '/users/new'
    return Path is: {location.pathname}
}

export default MyComponent

Example 5: uselocation hook

import { useHistory } from 'react-router-dom';

function Home() {
  const history = useHistory();
  return ;
}

Example 6: useparams

import {
  BrowserRouter as Router,
  Switch,
  Route,
  useParams
} from "react-router-dom";

function BlogPost() {
  let { slug } = useParams();
  return 
Now showing post {slug}
; } ReactDOM.render( , node );

Tags:

Misc Example