ReactJS/개념정리
[REACT] useLocation() 사용하기
xowoony
2023. 4. 5. 18:33
학습일 : 2023. 04. 05
참고사항
react-router-dom 6.0.0 버전 이상을 사용하는 경우
제네릭을 지원하지 않기 때문에
기존에 만약 이렇게 작성해줬더라면
const { state } = useLocation<RouteState>();
이런식으로 바꾸어 작성해주어야 한다.
const { state } = useLocation() as RouteState;
http://api.coinpaprika.com/docs#operation/getCoinById
코인의 상세정보가 나열 되어 있으며 우리는 여기에서
코인에 대해서 정보를 받아올 수 있다.
이번시간에는 useLocation() 을 사용하여 볼텐데
이는 현재의 URL 정보를 가져올 수 있다.
콘솔에 찍어보도록 하자.
const location = useLocation();
console.log(location);
나는 지금
localhost:3000/btc-bitcoin 에 있다
현재 경로에서 개발자 도구에 찍혀나오는 정보를 보면
pathname과 state 까지 모두 알 수 있다.
이번에는 state 안의 name을 가져와보기로 한다.
state안 name에 접근하게 위해
먼저 interface를 작성
interface RouteState {
state: {
name: string;
};
}
그런다음 useLocation() as RouteState;
를 작성해주어
state.name을 콘솔에 찍어볼 수 있다.
const { state } = useLocation() as RouteState;
console.log(state.name);
전체코드
<Coin.tsx>
import { useState } from "react";
import { useLocation, useParams } from "react-router-dom";
import styled from "styled-components";
// 여기는 각각의 코인 페이지
const Container = styled.div`
padding: 0px 20px;
max-width: 700px;
margin: 0 auto;
// 화면을 크게 했을 때에도 모바일 화면처럼 가운데에 위치하게 됨
`;
const Header = styled.header`
height: 10rem;
display: flex;
justify-content: center;
align-items: center;
`;
const Title = styled.h1`
font-size: 48px;
color: ${(props) => props.theme.accentColor};
`;
const Loader = styled.div`
text-align: center;
font-size: 38px;
display: block;
`;
interface RouteState {
state: {
name: string;
};
}
function Coin() {
// react-router-dom v6 이상의 경우
// useParams쓰는 순간 타입이 string or undefined로 설정됨.
// 따라서 const {coinId} = useParams(); 로만 적어줘도 상관 ㄴ
const { coinId } = useParams(); // coinId를 받아서 parameter로 사용
const [loading, setLoading] = useState(true);
// state 안에 있는 name을 가져오기 위한 작업
const { state } = useLocation() as RouteState;
console.log(state.name);
return (
<Container>
<Header>
<Title>{coinId}</Title>
</Header>
{loading ? <Loader>로딩중입니다...</Loader> : null}
</Container>
);
}
export default Coin;
실행결과
404는 이미지가 없는 코인 때문에 그런것이다 :>
아래와 같이 각각의 코인 페이지로 이동시
코인의 이름이 콘솔에 잘 찍혀나오는 것을 확인할 수 있겠다.