React 에서 a 태그로 링크를 이동하게 되면 html, JS, css 등 모두 매번 다시 다운받는다.
React 는 내부에서 맞는 path 의 component 를 보여주는 것에 집중하는데 a는 그에 반한다.
Link 태그를 사용해서 서버에서 파일을 받는게 아닌, 이동하고자 하는 경로에 맞는
Component로 이동한다.
// Links.jsx
import { Link } from 'react-router-dom';
export default function Links() {
return (
<ul>
<li>
<Link to='/profile'>Profile</Link>
</li>
<li>
<Link to='/profile/1'>Profile/1</Link>
</li>
<li>
<Link to='/About'>About</Link>
</li>
<li>
<Link to='/about?name=mark'>About?name=mark</Link>
</li>
</ul>)
}
// App.jsx
function App() {
return (
<BrowserRouter>
<Links />
<Switch>
<Route path="/profile/:id" component={Profile} />
<Route path="/profile" component={Profile} />
<Route path="/About" component={About} />
{/* 마지막은 exact 넣어주지 않으면 모든 url 은 / 를 포함하기 home 으로 들어가버린다. */}
<Route path="/" exact component={Home} />
<Route component={NotFound}></Route>
</Switch>
</BrowserRouter>
);
}
// Navigation Link
active 기능을 가진다.
즉, to 에 설정되어있는 경로 와 브라우저의 경로가 matching 된다고 판단하면 처리한다.
Route의 path 처럼 동작하기 때문에 exact 속성이 들어간다.
isActive 는 queryString 만 본다.
import { NavLink } from 'react-router-dom';
const activeStyle = { color: 'green' };
export default function NavLinks() {
return (
<ul>
<li>
{/* /를 포함하기 때문에 exact */}
<NavLink to='/' exact activeStyle={activeStyle}>Home</NavLink>
</li>
<li>
{/* profile을 포함하기 때문에 exact */}
<NavLink to='/profile' exact activeStyle={activeStyle}>Profile</NavLink>
</li>
<li>
<NavLink to='/profile/1' activeStyle={activeStyle}>Profile/1</NavLink>
</li>
<li>
<NavLink to='/About'
activeStyle={activeStyle}
isActive={(match, location) => {
console.log(match, location)
{/* match 로 About 경로가 맞는지 확인한다. */}
return match !== null && location.search ==="";
}}>About</NavLink>
</li>
<li>
<NavLink to='/about?name=mark'
activeStyle={activeStyle}
isActive={(match, location) => {
{/* search: "?name=mark" */}
return match !== null && location.search === '?name=mark';
}}>About?name=mark</NavLink>
</li>
</ul>)
}
about 주소에서만 activeStyle 이 적용되어야 하는데 about?name=mark 에도 적용된다.
이를 구분하기 위해서 isActive 사용한다.
isActive 의 조건이 location.search ===" 만 있다면
profile?name=mark 하면 about 두개의 주소 모두 적용이 되버린다.
따라서 주소의 매치여부를 보기 위해 match !== null 까지 추가해준다.