how to use usehistory in react js code example

Example 1: usehistory example

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

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

Example 2: usehistory, uselocation

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

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

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

  return (
    
  );
}

Example 3: 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 4: react router dom usehistory hook

import styled from 'styled-components'
import {useHistory} from 'react-router-dom'
import {useState , useEffect} from 'react'
function Sidebar() {

    const [channel , setChannel ] = useState([])

    const getConnectFirebase = ()=>{
        db.collection('channels').onSnapshot((snapshot)=>{
            setChannel(snapshot.docs.map((doc)=>{
                return {id:doc.id , name:doc.data().name}
            }))
        })
    }

    const history = useHistory();

    const goToChannel = (id)=>{
        if(id)
        {
            history.push(`/channel/${id}`)
        }
    }


    useEffect(()=>{
        getConnectFirebase()
    })

    return (
      
{ channel.map((items)=>{ return ( # {items.name} ) } ) }
) } export default Sidebar const Container = styled.div` background:#350d36; height:95.9vh; padding-left:35px; color:violet; font-family: 'Courier New', Courier, monospace; `; const CreateChannel = styled.div` margin-top:25px; `; const NamingChannel = styled.div ` padding-left:5px; color:violet; cursor:pointer; :hover{ color:whitesmoke; } `;

Tags:

Misc Example