참치코더의 꿈 메모장

React / Link to Router 사용법 미니정리 본문

잡다한 웹지식

React / Link to Router 사용법 미니정리

참치깡 2025. 9. 9. 13:57
728x90

 

 

 

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 리액트 버전 5로 사용할때 Link to Router 사용법
 
//문자열
<Link to="/about">About</Link>
 
// 객체
<Link to={{pathname: "/about", state : {fromDashboard : true}}}> About </Link>
 
// 데이터를 받는 컴포넌트
// v5 에서는 location.state로 접근
 
import {useLocation} from "react-router-dom";
 
function About () {
    const location = useLocation();
    console.log(location.state?.fromDashboard); // true
    return <h1>About</h1>;
}
 
 
// 리액트 버전 6로 사용할때 Link to Router 사용법
 
// v6에서 state 전달
 
<Link to="/about" state = {{ fromDashboard: true }}> About </Link>
 
 
import {useLocation} from "react-router-dom";
 
function About() {
    const location = useLocation();
    console.log(location.state?.fromDashboard); // true
    return <h1>About</h1>;
}
 
 
// 구조 분해 할당
 
import {useLocation} from "react-router-dom";
function About() {
    const location = useLocation();
    const {year, title, summary, poster, genres} = location.state || {};
    
    return(
        <h1>{title}</h1>
        <p>{summary}</p>
        <p>Year: {year}</p>
        <img src={poster} alt={title}/>
        <ul>
            {genres?.map((g, idx) => (
                <li key={idx}>{g}</li>
            ))}
        </ul>
    </div>
    );
}
 
cs

 

 

핵심 차이점

 

- v5 -> to = {{ pathname = '/path', state : {....}}} 

- v6 -> to = "/path" state={{....}} (state를 props로 직접 분리)

 

 

728x90
Comments