jinie kim
jinie kim

Reputation: 175

Cannot read property 'pathname' of undefined in React-Hooks

It worked well before.

But it doesn't work now.

What's the reason?

What should I do?

Unable to read location prop.

Added withRouter to header code,

Then this time there was an error in FriendsHeader.

This is my FriendsHeader code

import React from "react";
import styled from "styled-components";
import { Container } from "../BaseLabel";
import { Link, withRouter } from "react-router-dom";

const FriendstHeader = ({ location: { pathname } }) => {
  return (
    <>
      <FriendContainer>
            <Icons>
              {
                <Links to="/setting">
                  <div current={pathname === "/setting"}>
                    <img src={Cog} width="18px" height="18px" alt="" />
                  </div>
                </Links>
              }
            </Icons>
      </FriendContainer>
    </>
  );
};
export default withRouter(FriendstHeader);

This React Router code

import React from "react";
import {
  HashRouter as Router,
  Route,
  Switch,
  Redirect,
} from "react-router-dom";

export default () => (
  <Router>
    <>
      <Header />
      <Switch>
        <Route path="/" exact component={Friends} />
        <Route path="/chats" component={Chats} />
        <Route path="/shap" component={Shap} />
        <Route path="/more" component={More} />
        <Route path="/setting" component={Setting} />
        <Route path="/covid19" component={Covid19} />
        <Route path="/kakaotv" component={KakaoTV} />
        <Route path="/fun" component={Fun} />
        <Route path="/entertain" component={Entertain} />
        <Route path="/sports" component={Sports} />
        <Route path="/openchats" component={OpenChat} />
        <Redirect from="*" to="/" />
      </Switch>
      <Navgation />
    </>
  </Router>
);

Upvotes: 0

Views: 223

Answers (1)

Jayce444
Jayce444

Reputation: 9063

Not sure how it ever worked, but you need to either pass the router location in as a prop, or use withRouter when exporting your Header component, e.g. in your Header component file have

import { withRouter } from "react-router";

then when exporting:

export default withRouter(Header);

https://reactrouter.com/web/api/withRouter

Upvotes: 2

Related Questions