useLocation state code example
Example 1: react useLocation()
import React from "react";
import ReactDOM from "react-dom";
import {
BrowserRouter as Router,
Switch,
useLocation
} from "react-router-dom";
function usePageViews() {
let location = useLocation();
React.useEffect(() => {
ga.send(["pageview", location.pathname]);
}, [location]);
}
function App() {
usePageViews();
return <Switch>...</Switch>;
}
ReactDOM.render(
<Router>
<App />
</Router>,
node
);
Example 2: usematch react router
import React from 'react'
import ReactDOM from 'react-dom'
import { useParams } from 'react-router-dom'
function BlogPost() {
let { slug } = useParams()
}
ReactDOM.render(
<Router>
<div>
<Switch>
{}
<Route path="/posts/:slug">
<BlogPost />
</Route>
</Switch>
</div>
</Router>,
document.getElementById('root')
)
Example 3: react router dom current path hook
import { useLocation } from 'react-router-dom'
const MyComponent = () => {
const location = useLocation()
return <span>Path is: {location.pathname}</span>
}
export default MyComponent