본문 바로가기

리액트 기기기초

#7.5 React Router

  • react-router-dom:컴포넌트들의 모음집
    • url이 바뀌면 어떤 걸 보여줄지 결정함
    • Router은 렌더링해주는 애
    • route는 url을 의미
    • switch는 route를 찾는 역할, 한번에 하나의 route만 렌더링 하기 위함
    • Link는 브라우저 새로고침 없이도 유저를 다른 페이지로 이동시켜주는 컴포넌트

  • 이전에는 app컴포넌트가 모든걸 다 하고 있었음
    그 다음에는 app컴포넌트에 만들었던 모든 로직을 별개의 장소로 옮김
    현재 app.js에서 react-router-dom의 컴포넌트를 가져다 쓰는 중
import PropTypes from "prop-types";
import {Link} from "react-router-dom";

function Movie({ coverImage, title, summary, genres }) {
    return (
        <div>
            <img src={coverImage} alt={title}/>
            <h2>
                <Link to="/movie">{title}</Link>
            </h2>
            <p>{summary}</p>
            <ul>
                {genres.map((g) => (
                    <li key={g}>{g}</li>
                    ))}
        </ul>
      </div>
    );
} 

Movie.propTypes = { //propTypes설정
    coverImage: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    summary: PropTypes.string.isRequired,
    genres: PropTypes.arrayOf(PropTypes.string).isRequired,
};

export default Movie;

movie.js

import {
    BrowserRouter as Router,
    Route,
    Switch,
} from "react-router-dom";
import Detail from "./routes/Detail";
import Home from "./routes/Home";

function App() {
    return (
        <Router>
            <Switch>
                <Route path="/movie">
                    <Detail />
                </Route>
                <Route path="/">
                    <Home />
                </Route>
            </Switch>
        </Router>
    );
}

export default App;

app.js

'리액트 기기기초' 카테고리의 다른 글

#7.6 Parameters  (0) 2023.03.15
#7.4 Movie App part Two  (0) 2023.03.13
#7.3 Movie App part One  (1) 2023.03.12
#7.2 Coin Tracker  (0) 2023.03.11
#7.1 To Do List part Two  (0) 2023.03.11