🌟 https://github.com/JIWON-MIN/react-router-test 연습 프로젝트 코드 참고!

1. React의 라우팅

  • SPA(Single Page Application): 서버에서 각각의 페이지를 받아오는 것이 아니라, 전체 Application을 받아온 후 내부에서 url에 맞춰 해당하는 정보만 보여주는 것
  • SPA 라우팅 과정:
    1) 브라우저에서 최초에 '/' 경로로 요청하면 React Web App 내려줌
    2) 내려받은 React App에서 '/' 경로에 맞는 Component 보여줌
    3) React App에서 다른 페이지로 이동하는 동작 수행하면 새로운 경로에 맞는 Component 보여줌
  • React Router: 어떤 컴포넌트 보여줄지 결정하는 로직
    $ npx create-reate-app react-router-test React 프로젝트 생성
    $ cd react-router-test
    $ npm i react-router-dom
    // react-router-dom: CRA 기본 내장 패키지 아니고, facebook 공식 패키지도 아님 (가장 대표적인 라우팅 패키지)
    $ code .
    App.js의 return 안에 Route 컴포넌트에 path와 component 설정해 나열 -> BrowserRouter 태그로 Route 태그들 감싸기 -> 브라우저에서 요청한 경로에 Route의 path 있으면 해당 component 보여줌
<BrowserRouter>
  <Route path="/" exact component={Home} />
  <Route path="/profile" component={Profile} />
</BrowserRouter>
  • 하위 컴포넌트(profile)에는 상위 컴포넌트(home) 내용까지 적용됨
    -> 상위 컴포넌트의 path 뒤에 exact 넣어주기

2. Dynamic 라우팅

  • path와 component 연결하면 특정한 url을 지정하게 됨 -> 정적
  • <Route path=”/profile/:id” component={Profile} />
    :id 자리에 사용자의 id를 받아오기
    (localhost:3000/profile/1 로 접속했을 때 id는 1)
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>
  );
}
  • query string: localhost:3000/profile?name=mark에서 ?부터는 optional
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”} 객체 저장

3. Switch와 NotFound

  • Switch: 여러 Route중 순서대로 먼저 맞는 하나만 보여줌
    -> exact 줄일 수 있고, 어느 path에도 맞지 않으면 보여지는 component 설정해 Not Found 페이지 만들 수 있음
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>
}
  • 위에서 아래로 작은 범위부터 나열 필요
  • 루트경로에는 exact 붙여줘야 함 (모든 경로가 해당되므로)

4. JSX 링크로 라우팅 이동하기

1) Link 태그 이용

  • react에서 a태그 사용하면 모든 파일을 새로 로딩하므로 사용X
    -> Link 태그 이용해 로딩 없이 빠르게 페이지 전환 가능 (내부적으로는 a태그 포함)
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’;
  • activeClassName, activeStyle 등 active 상태에 대한 스타일 지정 가능
    (태그 내 to의 경로와 현재 브라우저의 경로가 같을 때)
    const activeStyle = {color: "green"};
    <NavLink to="/" exact activeStyle={activeStyle}>Home</Link>
  • query string 사용하는 주소에 대해서는 active 적용 시 isActive 함수 사용해 정확하게 맞춰주기
<NavLink 
  to="/about?name=mark"
  activeStyle={activeStyle}
  isActive={(match, location) => {
    return match !== null && location.search === "?name=mark";
  }}
>
  About?name=mark
</NavLink>

5. JS로 라우팅 이동하기

  • Route component에서 props.history.push(‘경로’); 통해 페이지 이동 가능
  • props는 Route component 자신만 사용할 수 있어 여러단계 전달 이 번거로움
    -> import {withRouter} from “react-router-dom”; 이후 withRouter 함수 안에 자신이 만든 함수를 매개변수처럼 넣어 사용하면 아무대서나 props 사용 가능

6. Redirect

  • import {Redirect} from ‘react-router-dom’;
    <Redirect to=”/” /> 형태로 사용
<Route 
  path="/login" 
  render={() => (isLogin ? <Redirect to="/" /> : <Login />)} 
/>
  • component={Login} 대신 render=함수 형태로 사용 가능
  • Redirect 적용되면 즉시 경로 바뀜
profile
2년차 프론트엔드 개발자의 소소한 기록을 담습니다 :-)

0개의 댓글

Powered by GraphCDN, the GraphQL CDN