path name as class name TypeError: Cannot read property 'replace' of undefined

Viewed 187

I am using gatsby, react and this is a HEADER component.

I wanna add a class on nav.gnbUl which matches pathname through onClick event. It worked on a plain react page but this time it doesn't on gatsby site.

It says TypeError: Cannot read property 'replace' of undefined Which part should I fix?

import React, { useState } from "react"
import { Link } from "gatsby"
//import PropTypes from "prop-types"
import logo from "../img/logo/logo.svg"

function Header({ /*siteTitle,*/ pathname }) {
  const [path, setPath] = useState(pathname.replace("/", ""))

  function handleClick(path) {
    setPath(path.replace("/", ""))
  }
  return (
    <header className="headerWrap">
      <p className="companyTopLogo imgWrap">
        <Link to="/">
          <img src={logo} alt="logo" />
        </Link>
      </p>
      <nav className={`gnbUl ${path}`}>
        <Link to="/Elsa/" onClick={() => handleClick("/Elsa")}>
          ELSA
        </Link>
        {/*<Link to="./App">R&amp;BD projects</Link>*/}
        <Link to="/AboutUs/" onClick={() => handleClick("/AboutUs")}>
          about us
        </Link>
        <Link to="/news/" onClick={() => handleClick("/news")}>
          news &amp; press
        </Link>
        <a href="#none" title="">
          contact us
        </a>
      </nav>
    </header>
  )
}
/*Header.propTypes = {
  siteTitle: PropTypes.string,
}
Header.defaultProps = {
  siteTitle: ``,
}
*/
export default Header

error messege

1 Answers

You need to put your function inside a componentDidMount lifecycle or useEffect hook. This is because in Gatsby, at the render time doesn't have the information about some parameters, such as window, paths, etc.

So, at the initial render point, define your useState as empty (i.e: empty string or whatever) and inside a useEffect hook, once the layout is rendered, set your function.

  const [path, setPath] = useState('')


    useEffect(()=>{
      setPath(pathname.replace("/", "")
    },[])

You can check for further information in Debugging HTML in Gatsby's documentation.

Related