0

I'm trying to get the id of a route from a react.js project like this: page1#view-all

I tried with the native JavaScript document and window but unfortunely I can't get it that way because of the SSR.

Is there any alternative to the functions mentioned above? How can I get the router link with the href id? page1#view-all

Thanks

FYI, the errors I'm getting when using document or window I'm getting that any of these isn't defined.

Here's a code snippet:

<Link
                to="/page1#view-all"
                className={`subItem-anchor
                ${
                  route && route.split("/")[route.split("/").length - 1] === "all-projects"
                    ? "subnavitemHighlightd"
                    : ""
                }`}
              >

route is actually the other routes such as page1/another-sub-page but I can't get page1#view-all

Kleo Magaret
  • 73
  • 1
  • 1
  • 5
  • Does this answer your question? [How to access a DOM element in React? What is the equilvalent of document.getElementById() in React](https://stackoverflow.com/questions/38093760/how-to-access-a-dom-element-in-react-what-is-the-equilvalent-of-document-getele) – mrdeadsven Jan 14 '20 at 09:24
  • @mrdeadsven Not really, I'm looking for a react way. – Kleo Magaret Jan 14 '20 at 09:32

2 Answers2

1

Use react-router-dom

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

and access like this

  let location = useLocation()
  console.log(location);

The useLocation hook returns the location object which contains the pathname, search, hash, key and the state properties of the current location.

Sample code to access

function App(){

let location = useLocation()
return(
<h3>Access from useLocation</h3>
)}

or if it's class based component then access like this without importing anything

let urlData = this.props.location;
console.log(urlData);
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
0

Found a fix, what I did:

render() {
  { ssr } = this.props

  if (ssr) return
  const urlId = window.location.toString().split("#")[1]

  return(
    <div>URL ID: {urlId}</div>
  )
}

Kleo Magaret
  • 73
  • 1
  • 1
  • 5