Project using React/Cloning Netflix
React create Header.js
Cog Factory
2021. 5. 9. 07:05
Components/Header.js
import { Link, withRouter } from "react-router-dom";
import styled from "styled-components";
const Header = styled.header`
position: fixed;
top: 0;
left: 0;
height: 50px;
width: 100%;
background-color: rgba(20, 20, 20, 0.8);
z-index: 10;
box-shadow: 0px 1px 5px 2px rgba(0, 0, 0, 0.8);
`;
const List = styled.ul`
display: flex;
`;
const Item = styled.li`
width: 80px;
height: 50px;
text-align: center;
border-bottom: 3px solid
${(props) => (props.current ? "#3498db" : "transparent")};
transition: border-bottom 0.5s ease-in-out;
`;
const SLink = styled(Link)`
height: 50px;
display: flex;
align-items: center;
justify-content: center;
`;
export default withRouter(({ location: { pathname } }) => (
<Header>
<List>
<Item current={pathname === "/"}>
<SLink to="/">Movie</SLink>
</Item>
<Item current={pathname === "/tv"}>
<SLink to="/tv">TV</SLink>
</Item>
<Item current={pathname === "/search"}>
<SLink to="/search">Search</SLink>
</Item>
</List>
</Header>
));
Link
react-router-dom의 Link는 html <a>와 비슷하다. 하지만 Link는 reload를 하지 않고 바로 해당 page로 가서 필요한 components만 교체한다. 그리고 <a>의 href를 쓰지 않고 Link는 to를 사용한다. 마지막으로 Link를 사용하려면 무조건 <Router> 안에 있어야 한다.
withRouter
withRouter를 사용하면 history 객체 속성과 가장 가까운 <Route> 일치 항목에 접근할 수 있다.
console.log()를 찍어보면 위처럼 객체를 얻을 수 있다. { location : { pathname } }을 찍은 것이 아니라 withRouter주는 변수 자체를 console.log()로 찍었다.
Components/Header.js
import {
BrowserRouter as Router,
Route,
Switch,
Redirect,
} from "react-router-dom";
import Movie from "Routes/Movie";
import Search from "Routes/Search";
import TV from "Routes/TV";
import Detail from "Routes/Detail";
import Header from "./Header";
export default () => (
<Router>
<>
<Header />
<Switch>
<Route exact path="/" component={Movie} />
<Route exact path="/tv" component={TV} />
<Route exact path="/search" component={Search} />
<Route exact path="/movie/:id" component={Detail} />
<Route exact path="/tv/:id" component={Detail} />
<Redirect from="*" to="/"></Redirect>
</Switch>
</>
</Router>
);
<Header> component를 <Router> 안에 넣었다. 그 이유는 <Link>는 <Router> 밖에서는 작동을 하지 않기 때문이다.
참고 자료
- 노마드 코더의 React 멤버쉽 강의
- react-router-dom
소스 코드
github.com/zpskek/Nomflix-v2/commit/d559a4ac0a3536f4a9a184a94b65084c740e8449