늘 겸손하게

React - react-router-dom - useHistory + 데이터 전달 본문

Programming/React

React - react-router-dom - useHistory + 데이터 전달

besforyou999 2022. 7. 13. 16:55

다른 페이지로 리다이렉트하는 기능을 history.push로 구현해보겠습니다.

 

1. react-router-dom 설치

 

1
npm i react-router-dom
cs

 

 

2. useHistory import

 

1
import { useHistory } from 'react-router-dom';
cs

 

 

3. 변수 생성

 
1
const history = useHistory();
cs
 
 
 

4. history.push에 이동할 경로 넣기

 
 
1
history.push('이동할 경로')
cs
 
 
 
history.push 메소드가 실행되면 현재 경로에 '이동할 경로'가 붙은 경로로 리다이렉션됩니다.
 
 
 

+ history.push 로 이동할 경로에 데이터 전달

 
 
 
state에 데이터를 담아서 이동할 경로에 데이터를 전달할 수 있습니다.
 
 
ex)
 
 
history.push( {
    pathname: '/이동할 경로',
    state: {
        object: obj
    }
})
 
이동할 경로에서는 useLocation으로 데이터를 읽어들일 수 있습니다.
 
import {useLocation} from 'react-router-dom';
const location = useLocation();
console.log(location.state.object); // obj 내용 출력됨