Routing is an important part of any web application. Unfortunately, React does not have a built-in solution for routing. React developers are forced to use external libraries, most commonly react-router. This library does more than define routes and components for specific URLs. It helps you deal with everything related to page URLs and web app navigation.
Before we delve into this topic, we need to explain what window interface is, count its many properties, and then explain location property. Window is a global interface available for all web application that run in the browser. Like its name suggests, this interface contains information about browser window. There is a wealth of information about window height, width, and fortunately, it also contains information about current URL in the browser. That information is stored in the location property of the interface.
React apps run in the browser, so you can access the window interface and all its properties to determine current URL in React. However, generally it’s a bad practice to work directly with DOM in React. For this reason, it’s better to use the useLocation() hook which accesses the location object so you can get the information you need.
First, you’re going to need to install react-router. Once you have, then you can import many useful components to implement navigation features in your app. You’re going to need
<Link> and other custom components to set up a fully fleshed-out navigation system for your app.
Since version 6, react-router also provides the useLocation() hook. To use it, you need to create a variable and set it equal to the result of useLocation() hook. It returns the reference to window.location object, which will be stored in the variable. Then you can access the variable and use it throughout your application. You also need to read the href property of the variable to output the actual URL.
SimpleFrontEnd has a comprehensive tutorial on how to get current URL in React:
Like any other react-router feature, this only works if the entire application is wrapped with custom components. You don’t need to wrap the child component itself, it’s enough that parent is wrapped with it.