Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- reveal in file explorer
- sub태그
- html
- i 태그
- RGBA
- html tag i
- 아두이노
- css
- br 태그
- sup태그
- padding 속성
- 일반 형제 결합자
- width속성
- RGB
- height속성
- go live
- html 태그
- 임베디드
- not 의사클래스
- 전체 선택자
- iframe 태그
- background-color 속성
- tag html
- 인접 형제 결합자
- id 선택자
- 자식결합자
- Checked 의사 클래스
- focus 의사클래스
- Live Server
- iframe
Archives
- Today
- Total
so woon!
[React] <Link></Link> 사용하기 본문
학습일 : 2023. 03. 20
<Link></Link> 는 브라우저의 새로고침 없이도 유저를 다른 페이지로 이동시켜주는 컴포넌트이다.
그래서 우리는 이제
페이지 자체가 다시 로드(새로고침) 되는
기존의 HTML a태그에 링크를 넣어 이동시키게 하는 방법을 쓰지 않아도 된다!
리액트의 <Link></Link>는 페이지가 새로고침 되지 않기 때문에 엄청 빠르게 이동되는 것처럼 보인다.
적용해보면 다음과 같이 쓸 수 있겠다.
<Movie.js>
사용을 위해서
import { Link } from "react-router-dom"; 해주어야 한다.
아래 코드상으로 h2 태그안 <Link> 를 작성하여 영화의 제목을 주고
제목을 클릭했을 때 /movie 로 새로고침 없이 이동할 수 있도록 구현해 보았다.
import PropTypes from "prop-types";
import { Link } from "react-router-dom";
function Movie({ coverImg, title, summary, genres }) {
return (
<div>
<div>
<img src={coverImg} alt="" />
<h2>
<Link to="/movie"> {title}</Link>
</h2>
<ul>
{genres.map((g) => (
<li key={g}>{g}</li>
))}
</ul>
<p>{summary}</p>
</div>
</div>
);
}
// PropType 설정
Movie.propTypes = {
coverImg: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
summary: PropTypes.string.isRequired,
genres: PropTypes.arrayOf(PropTypes.string).isRequired,
};
export default Movie;
<Home.js>
import { useEffect, useState } from "react";
import Movie from "../components/Movie";
function Home() {
const [loading, setLoading] = useState(true);
const [movies, setMovies] = useState([]);
const getMovies = async () => {
const json = await (
await fetch(
`https://yts.mx/api/v2/list_movies.json?minimum_rating=9&sort_by=year`
)
).json();
setMovies(json.data.movies);
setLoading(false);
};
// useEffect를 이용하여 getMovies를 호출
useEffect(() => {
getMovies();
}, []);
return (
<div>
{loading ? (
<h3>로딩 중...</h3>
) : (
<div>
{movies.map((movie) => (
<Movie
key={movie.id}
coverImg={movie.medium_cover_image}
title={movie.title}
summary={movie.summary}
genres={movie.genres}
/>
))}
</div>
)}
</div>
);
}
export default Home;
<Detail.js>
function Detail() {
return <h1>Detail</h1>
}
export default Detail;
<App.js>
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Home from "./routes/Home";
import Detail from "./routes/Detail";
function App() {
return (
<Router>
<Switch>
<Route path="/movie">
<Detail />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
);
}
export default App;
실행결과는 아래와 같다.
'ReactJS > 개념정리' 카테고리의 다른 글
[React] github pages 배포 (0) | 2023.03.22 |
---|---|
[React] useParams() 사용하기 (0) | 2023.03.21 |
[React] React Router2 (0) | 2023.03.20 |
[React] React Router1 (0) | 2023.03.20 |
[React] <component /> 사용하기 (0) | 2023.03.20 |
Comments