React 프로젝트 초기세팅 복습

박은정·2021년 11월 23일
0

프로젝트

목록 보기
32/34
post-thumbnail

React 프로젝트 설치

  1. npx create-react-app 프로젝트명(폴더명)
  2. cd 프로젝트명
  3. 초기세팅 진행

React 초기세팅

1. 프로젝트 폴더에 남기는 것을 제외하고 대부분 삭제한다

  • node_modules
  • public/index.html
  • src/components/
  • App.js ⭐️
  • index.js
  • main.css
  • main.css.map

1번과정의 설명

  • components 폴더: 반복적으로 사용하는 컴포넌트들을 저장하는 폴더
  • pages 폴더: 페이지 jsx파일 저장하는 폴더
  • main.css 와 main.css.map은 scss 파일들을 하나로 매핑할 때 사용한다
  • 만약 main.cssmain.css.map을 사용하지 않으면 각각의 페이지.jsx 파일에서 각각의 페이지 혹은 컴포넌트.scss 파일을 import 헤야한다

react-router-dom이 버전 6으로 업그레이드

  1. Switch 컴포넌트가 사라지고, Routes 컴포넌트로 변경

  2. Route 컴포넌트가 기본으로 exact 속성을 가짐 + component 속성이 element 속성으로 변경

    • 따라서 exact 속성을 부여하는 것이 불필요하다
    • element 속성에는 컴포넌트의 형태 로 값을 부여해야 한다
  3. 상대 경로 (Relative Route)

    • Link 혹은 Route에서 라우팅 경로를 입력할 때, / 없이 작성하면 -> 헌재 라우팅 경로 위에 새로운 경로가 작성된다
    • Link to={'${match.url}'}>contents</Link> 대신 <Link to='me'>contents</Link> 으로 작성하면 된다
    • <Link to='.'> : 현재경로
    • <Link to ='..'>: 한 단계 윗 경로
  4. 새로운 Route Path 패턴: *

    • Route 컴포넌트가 기본적으로 exact 속성을 가지기 때문에 서브라우터를 구성하고 싶은 경우 *로 표기하면 된다
    • *: Route Path의 마지막에만 사용이 가능하다 (* 가 중간에 있으면 안됨)
  5. useHistory Hook, withRouterHOC 대신 useNavigate Hook이 생김

    • withRouterHOC가 사라졌기 때문에, class형 컴포넌트에서 해당 기능을 사용하려면 직접 구현을 해야 한다
  6. 서브라우터를 구성할 때 유용한 <Outlet> 컴포넌트 등장

    • 기존에는 서브라우터를 구성할 때 메인라우터가 있고, 서브라우터가 구성될 컴포넌트 안에 또 다른 라우터가 존재했지만
    • Outlet 컴포넌트를 사용하면 모든 라우터를 메인 라우터에서 관리할 수 있어, 서브 라우터가 많이 있을 시 프로젝트 내 여러 컴포넌트에 산발적으로 라우터가 존재하게 되는 문제점을 해결할 수 있다.

Reference

https://reactrouter.com/docs/en/v6/upgrading/v5#upgrade-to-react-router-v6
https://www.youtube.com/watch?v=CHHXeHVK-8U

Before & After


function App() {
  return (
    // Before 🙅‍♂️
<BrowserRouter>
  <Switch>
    <Route exact path="/" component={Login} />
    <Route exact path="/signup" component={Signup} />
    <Route exact path="/main" component={Main} />
  </Switch>
</BrowserRouter>

// After 🙆‍♂️
<BrowserRouter>
  <Routes>
    <Route path="/" element={<Login />} />
    <Route path="/signup" element={<Signup />} />
    <Route path="/main" element={<Main />} />
  	<Route path="/users/*" element={<Users />} />
  </Routes>
</BrowserRouter>
 )
}

function Users() {
  return {
    <div className='Users'>
      <nav>
        <Link to='me'>My Profile</Link>
      </nav>
      <Routes>
        <Route path=':id' element={<UserProfile/>}/>
        <Route path='me' element={<OwnUserProfile/>}/>
      </Routes>
    </div>
  )
}

1번과정의 결과

// App.js
import React, { Component } from 'react'
import { BrowserRouter as Router, Routes, Route } from "react-router-dom"

import ProductList from './pages/ProductList'
import ProductDetail from './pages/ProductDetail'
import Cart from './pages/Cart'

class App extends Component {
  render() {
    return (
      <Router>
        <Routes>
        <Route exact path='/' element={<ProductList />} />
        <Route exact path='/productDetail' element={<ProductDetail/>} />
        <Route exact path='/cart' element={<Cart/>} />
        </Routes>
      </Router>
    )
  }
}

export default App
// index.js
import React from "react"
import ReactDOM from "react-dom"
import { ThemeProvider } from "styled-components"

import GlobalStyles from "./styles/GlobalStyles"
import App from "./App"
import theme from "./styles/theme"

ReactDOM.render(
  <>
    <GlobalStyles />
    <ThemeProvider theme={theme}>
      <App />
    </ThemeProvider>
  </>,
  document.getElementById("root")
);

css 초기화설정

node-sass를 사용하면 reset.scss에
styled-components를 사용하면 GlobalStyles.js에 해당 내용을 넣어주면 된다

// GlobalStyles.js
import { createGlobalStyle } from "styled-components";

const GlobalStyles = createGlobalStyle`
body,
div,
span,
h1,
h2,
h3,
h4,
h5,
h6,
p,
a,
abbr,
address,
em,
img,
q,
strong,
b,
i,
ol,
ul,
li,
form,
label,
article,
figure,
figcaption,
footer,
nav,
section,
main {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
}
ol,
ul,
li {
  list-style: none;
}
h1,
h2,
h3,
h4,
h5,
h6,
b,
strong,
i,
em {
  font-weight: normal;
  font-style: normal;
}
textarea {
  border: none;
  overflow: auto;
  outline: none;
  box-shadow: none;
  resize: none;
  cursor: text;
}
input,
button {
  border: none;
  outline: none;
  background: transparent;
}
a {
  text-decoration: none;
  color: inherit;
}
blockquote,
q {
  quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
*{
  box-sizing: border-box;
}
`;

export default GlobalStyles;

공통적으로 사용하는 스타일링

node-sass를 사용하는 경우 common.scss
styled-components 사용하는 경우 ThemeProvider.js에 해당 내용 넣고
index.js에서 <ThemeProvider theme={theme}> 내용 불러오기

// ThemeProvider.js
const theme = {
  logoRed: "rgb(233,0,22)",
  buttonGray: "rgb(255,255,255)",
};

export default theme;

2. 사용할 패키지 설치

styled-components 혹은 node-scss 등 해당하는 프로젝트에서 사용할 패키지를 사용하고
React 프로젝트를 실행했을 때 별 다른 문제가 없는 지 확인한다

$ npm start
profile
새로운 것을 도전하고 노력한다

0개의 댓글