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
- focus 의사클래스
- css
- br 태그
- 임베디드
- i 태그
- reveal in file explorer
- not 의사클래스
- width속성
- 자식결합자
- iframe 태그
- html
- 일반 형제 결합자
- sup태그
- 인접 형제 결합자
- tag html
- RGBA
- 아두이노
- RGB
- Live Server
- iframe
- Checked 의사 클래스
- height속성
- 전체 선택자
- html 태그
- go live
- background-color 속성
- id 선택자
- html tag i
- padding 속성
- sub태그
Archives
- Today
- Total
so woon!
[REACT] useLocation() 사용하기 본문
학습일 : 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는 이미지가 없는 코인 때문에 그런것이다 :>
아래와 같이 각각의 코인 페이지로 이동시
코인의 이름이 콘솔에 잘 찍혀나오는 것을 확인할 수 있겠다.
'ReactJS > 개념정리' 카테고리의 다른 글
[REACT] Data Types (0) | 2023.04.06 |
---|---|
[REACT] async, await (0) | 2023.04.06 |
[REACT] API로 이미지 불러오기 (0) | 2023.04.05 |
[REACT] API fetch (0) | 2023.04.05 |
[React] array로 정보 불러오기 (0) | 2023.04.04 |
Comments