본문 바로가기

리액트 기기기초

#7.6 Parameters

  • react router는 동적 url을 지원
  • 동적 -> url에 변수를 넣을 수 있다는 의미
  • :를 붙여줘야 함, 안그러면 진짜 텍스트임
  • useParams -> 변수의 값을 넘겨줌
  • await는 asyns함수 내부에 있지 않으면 사용할 수 없음
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={"/hello"}>
                    <h1>Hello</h1>
                </Route>
                <Route path="/movie/:id">
                    <Detail />
                </Route>
                <Route path="/">
                    <Home />
                </Route>
            </Switch>
        </Router>
    );
}

export default App;
import PropTypes from "prop-types";
import {Link} from "react-router-dom";

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

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

export default Movie;
import { useEffect } from "react";
import { useParams } from "react-router-dom";
import { useState } from "react";

function Detail(){
    const [loading, setLoading] = useState(true);
    const [movie, setMovies] = useState([]);
    const {id} = useParams();
    const getMovie = async() => {
        const json = await( await fetch(`https://yts.mx/api/v2/movie_details.json?movie_id=${id}`))
        .json(); //id를 알고 있으니 api로부터 정보를 fetch해올 수 있음
        setMovies(json.data.movie);
        setLoading(false);
    }; 
    useEffect(()=>{
        getMovie();
    },[])
    console.log(movie);
    return <div>{loading ? <h1>Loading...</h1> :
      (<div>
        <div>
            <h1>{movie.title_long}</h1>
            <img src={movie.medium_cover_image} alt={movie.title}/>
            <h3>{movie.description_full}</h3>
            
      </div>
      </div>
      )}
    </div>;
}

export default Detail;

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

#7.5 React Router  (0) 2023.03.13
#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