스파르타 코딩클럽 - 리액트 3주차(5)

SeungMai(junior)·2021년 7월 28일
0

1. 라우팅, 고금 더 꼼꼼히 쓰려면?

1-1. 잘못된 주소 처리하기

  • NotFound.js 파일을 만들고 빈 컴포넌트를 만든다.
import React from "react";

const NotFound = (props) => {
  return <h1>주소가 올바르지 않아요!</h1>;
};

export default NotFound;
  • App.js에서 불러온다.
import NotFound from "./NotFound";
  • Switch를 추가한다.
...
import { Route, Switch } from "react-router-dom";
...
class App extends React.Component {
  ...
  render() {
    return (
      <div className="App">
        ...
          <Switch>
            <Route
              path="/"
              exact
              render={(props) => (
                <BucketList
                  list={this.state.list}
                  history={this.props.history}
                />
              )}
            />
            <Route path="/detail" component={Detail} />
          </Switch>
        ...
      </div>
    );
  }
  • NotFound컴포넌트를 Route에 주소 없이 연결하면 끝난다.
...
					<Switch>
            <Route
              path="/"
              exact
              render={(props) => (
                <BucketList
                  list={this.state.list}
                  history={this.props.history}
                />
              )}
            />
            <Route path="/detail" component={Detail} />
            <Route component={NotFound} />
          </Switch>
...

1-2. NotFound에 뒤로가기 버튼을 달아보자.

  • App.js에서 history를 props로 넘겨주는 게 먼저!
<Route render={(props) => (
                <NotFound
                  history={this.props.history}
                />
              )}/>
  • NotFound.js에서는,
import React from "react";

const NotFound = (props) => {
  return (
    <div>
      <h1>주소가 올바르지 않아요!</h1>
      <button>뒤로가기</button>
    </div>
  );
};

export default NotFound;
  • props를 받는다.
const NotFound = (props) => {
  console.log(props);
...
  • onClick에 넣어준다.
<button onClick={() => {props.history.goBack();}}>뒤로가기</button>
profile
👍🏻 SeungMai (매 순간 기록을!)🧑🏻‍💻 | WIL만 올리고 있습니다 | 기술블로그는 아래 🏠 의 링크를 이용해주세요.

0개의 댓글

관련 채용 정보