05. withRouter

라우트가 아닌 컴포넌트에서 라우터에서 사용하는 객체 - location, match, history 를 사용하려면, withRouter 라는 HoC 를 사용해야합니다.

src/components/ShowPageInfo.js

import React from 'react';
import { withRouter } from 'react-router-dom';

const ShowPageInfo = withRouter(({ match, location }) => {
  return <div>현재 위치: {location.pathname}</div>;
});

export default ShowPageInfo;

App 컴포넌트에서 이렇게 렌더링 해보세요.

src/App.js

import React from 'react';
import { Route } from 'react-router-dom';
import { Home, About, Posts } from 'pages';
import Menu from 'components/Menu';
import ShowPageInfo from 'components/ShowPageInfo';


const App = () => {
  return (
    <div>
      <Menu />
      <Route exact path="/" component={Home} />
      <Route path="/about/:name?" component={About} />
      <Route path="/posts" component={Posts}/>
      <ShowPageInfo />
    </div>
  );
};

export default App;

results matching ""

    No results matching ""