🌟 https://github.com/JIWON-MIN/react-router-test 연습 프로젝트 코드 참고!
$ npx create-reate-app react-router-test
React 프로젝트 생성$ cd react-router-test
$ npm i react-router-dom
$ code .
<BrowserRouter>
<Route path="/" exact component={Home} />
<Route path="/profile" component={Profile} />
</BrowserRouter>
exact
넣어주기<Route path=”/profile/:id” component={Profile} />
export default function Profile(props){ // props는 Route Component 에서만!
const id = props.match.params.id;
console.log(id, typeof id); // 1 string
return (
<div>
<h2>Profile Page </h2>
{id && <p>ID is {id}.</p>} // id 있으면 뒤의 p태그 출력
</div>
);
}
const searchParams = props.location.search; // ?name=mark
const obj = new URLSearchParams(searchParams); // URLSearchParams 내장객체 사용
console.log(obj.get(“name”)); // mark 출력
$npm i query-string
설치 후 import queryString from ‘query-string’;
const query = queryString.parse(searchParams); // {name: “mark”} 객체 저장
function App(){
return(
<BrowserRouter>
<Switch>
<Route path="/profile/:id" component={Profile} />
<Route path="/profile" component={Profile} />
<Route path="/" exact component={Home} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
)
}
// NotFound.jsx
export default function NotFound() {
return <div>페이지를 찾을 수 없습니다.</div>
}
1) Link 태그 이용
import {Link} from “react-router-dom”;
export default function Links(){
return(
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/profile">Profile</Link></li>
<li><Link to="/profile/1">Profile/1</Link></li>
</ul>
)
}
2) NavLink 태그 이용
import {NavLink} from ‘react-router-dom’;
const activeStyle = {color: "green"};
<NavLink to="/" exact activeStyle={activeStyle}>Home</Link>
<NavLink
to="/about?name=mark"
activeStyle={activeStyle}
isActive={(match, location) => {
return match !== null && location.search === "?name=mark";
}}
>
About?name=mark
</NavLink>
props.history.push(‘경로’);
통해 페이지 이동 가능import {withRouter} from “react-router-dom”;
이후 withRouter 함수 안에 자신이 만든 함수를 매개변수처럼 넣어 사용하면 아무대서나 props 사용 가능import {Redirect} from ‘react-router-dom’;
<Redirect to=”/” />
형태로 사용<Route
path="/login"
render={() => (isLogin ? <Redirect to="/" /> : <Login />)}
/>
component={Login}
대신 render=함수
형태로 사용 가능