Introduction
Single Page Application takes a different approach when navigating from one page (Component) to another.
This is because unlike Multi-page Applications with multiple HTML files that are uploaded to the server and then accessed later based on a new request from the client side.
Single Page Application has one HTML file that is uploaded to the server and once a request is made, the entire app (html file) is sent to the client. This helps users to navigate directly within the client-side (client-side routing) without sending a new request to the server.
With useLocation
hook, we can get access to the pathname
, hash
, state
, key
or search
relative to a specific component and perform side effects in a web app.
In this blog post, I explained how to implement useLocation
hook in React Router and how to return the location object and access the object props relative to the components.
Prerequisites
In other to follow along, you should have a basic understanding of the following:
How to setup a React project
How to install React Router
So with that said, let's dive in.
What is useLocation hook
The useLocation
hook in React Router is used to return the current location of a React component. The useLocation
returns the current location as an object and comes with props such as
pathname
state
search
key
hash
These props can be used with useEffect hook to perform side effects such as clicks onScroll or return state parsed to a Link component.
To use useLocation
hook, import it from the react-router-dom
as indicated below.
π import { useLocation } from 'react-router-dom';
Then create and store the useLocation
hook to a location
variable as indicated below.
export default function App(){
π const location = useLocation()
retun(
<><p>Hello, useLocation</p></>
)
}
With the location
variable, the useLocation
props can be accessed. For example
export default function App(){
const location = useLocation()
π console.log(location)
retun(
<><p>Hello, useLocation</p></>
)
}
This should return the location
variable as an object.
Props
The defined location
object returns an object that contains the URL segment of the current location. π
pathname
The pathname
property (prop) from the location
object is used to return the path name of a given component. The path name is the name that comes after the port number.
//pathname
π
http://localhost:5173/products
π
//port number
From the code sample, the pathname
is the forward slash and the products text π /products
Access the pathname
as follows ;
export default function App(){
// Dot Notation
const location = useLocation()
π console.log(location.pathname)
// Object Destructuring
const {pathname} = useLocation()
π console.log(pathname)
retun(
<><p>Hello, useLocation</p></>
)
}
// layouts/Navbar.js
<div className="main">
{pathname !== "" ? (
<aside>
<Link to="#sectionFour" className="product-btn">
Click Button
</Link>
</aside>
) : null}
</div>
Here, the pathname
returns a button element when the user clicks.
Try the code example on code Codesandbox below
%[https://codesandbox.io/s/uselocation-pathname-xyq46q?file=/src/Layouts/Navbar.js]
state
The state
property (prop) from the location
object is used to set data on parent components that can be accessed by the children components.
To set state
on the parent component, parse the state
property and assign it a value as specified below. π
<li>
<NavLink
to="/"
π state={`Welcome to the ${
pathname.substring(1) !== "" ? "home" : ""
} page`}
>
Home
</NavLink>
</li>
...
<li>
<NavLink
to="products"
state={`Welcome to the ${pathname.substring(1)} page`}
>
Products
</NavLink>
</li>
Here, the pathname
of the specific link the user clicks is returned as a string and we applied the following functions to the state props.
substring(1)
This method removes the forward slash from the pathnamethe ternary operator checks and returns βhomeβ if the path contains an empty string.
Try the code example on Codesandbox below
%[https://codesandbox.io/s/uselocation-state-h6wrrj?file=/src/Layouts/Navbar.js]
search
The search
property (prop) from the location
object is used to get the query string in a URL.
For example, take this URL "http://example.com/search?age=20&name=alex";
The query string refers to a portion in the URL starting from the ?
character followed by a key (βageβ and βnameβ ) and value (β20β and βalexβ) pairs. These keys and value pairs are called parameters and are separated by the &
character.
Access the search
as follows ;
export default function App(){
// Dot Notation
const location = useLocation()
π console.log(location.search)
// Object Destructuring
const {search} = useLocation()
π console.log(search)
retun(
<><p>Hello, useLocation</p></>
)
}
key
The key
property (prop) from the location
object is used to hold a unique identifier (id) from the current URL.
Access the key
as follows ;
export default function App(){
// Dot Notation
const location = useLocation()
π console.log(location.key)
// Object Destructuring
const {key} = useLocation()
π console.log(key)
retun(
<><p>Hello, useLocation</p></>
)
}
export default function Navbar() {
const { pathname, key } = useLocation();
return (
<>
<ul>
<li>
<NavLink to="/">Home</NavLink>
</li>
...
<li>
<NavLink to="products">Products</NavLink>
</li>
</ul>
{/* Outlet */}
<Outlet />
<div className="main">
{pathname !== "" ? (
<aside>
<Link className="product-btn">Click Button</Link>
</aside>
) : null}
<p>
the return text is a key: <i className="key">{key}</i>
</p>
</div>
</>
);
}
Here, we are returning the key of each component when the navlink is clicked.
Try code example on Codesandbox
%[https://codesandbox.io/s/uselocation-key-3p5vtg?file=/src/Layouts/Navbar.js]
hash
The hash
property (prop) from the location
object is used to set the current location in the #
hash segment of the current URL.
This is useful in cases where you want to navigate between different sections on the same page or navigate to a specific section on another page.
Access the hash
as follows ;
export default function App(){
// Dot Notation
const location = useLocation()
π console.log(location.hash)
// Object Destructuring
const {hash} = useLocation()
π console.log(hash)
retun(
<><p>Hello, useLocation</p></>
)
}
%[https://codesandbox.io/s/uselocation-hash-zs94kw?file=/src/App.js]
Here, from the example above, we store the list of countries within the page as a hash fragment. So clicking each link navigates to a specific section of the page.
Conclusion
The useLocation
hook is used to return the current location of a react component. The useLocation
uses the location
object to access the key, pathname, state, hash
and search
of the component.
This is useful for client-side routing and for navigating users within and around different pages in a single-page application.
Top comments (0)