WEB/React

[영화 웹] #5. react Project 준비(create-react-app, prop-type, module.css)

Harimad 2022. 1. 28. 15:16

노마더코드 깃 히스토리: https://github.com/nomadcoders/react-for-beginners/commits/master

#5.0 Introduction - 시작 파일 만들기

 

npx create-react-app my-app 했을때 아래와 같은 오류가 난다면?
You are running `create-react-app` 4.0.3, which is behind the latest release (5.0.0).


-> npx create-react-app@5.0.0 my-app으로 진행하면 된다

https://github.com/facebook/create-react-app

 

GitHub - facebook/create-react-app: Set up a modern web app by running one command.

Set up a modern web app by running one command. Contribute to facebook/create-react-app development by creating an account on GitHub.

github.com

 

프로젝트 시작 준비로 파일을 이렇게 만들어 놓는다. 

- src폴더에 App.js, index.js 파일만 살려놓는다.

- package-lock.json 또는 yarn-lock.json파일을 지운다.

- public 파일을 그대로 둔다.

//App.js

function App() {
  return (
    <div>
      <h1>Welcome Back!!!</h1>
    </div>
  );
}

export default App;

 

//index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

 

 

#5.1 Tour of CRA

 

  • 컴포넌트의 인자를 관리하기 위한 패키지를 하나 추가한다.
npm i prop-type

 

  • MODULE.CSS

목적 : css 코드를 자바스크립트 객체로 변환시켜준다
방법 : import styles from "./~";

설명: 
해당 css코드에 작성된 class name(여기서는 btn)은 프로퍼티 접근 연산자(.)으로 사용가능하다.

컴포넌트 파일에서 이와 같이 사용해서 css스타일링을 할 수 있다. ex) < Button style={styles.btn} / >

브라우저를 통해 html 코드를 확인해보면 해당 컴포넌트의 style적용 Tag에 무작위의 class name이 붙는다. ex) class="App_title__JHStz"
이는 일일이 class name을 기억해서 스타일링 할 필요가 없다

 

css 파일 명은 넣어줄 컴포넌트 파일명 + modue.css 으로 한다.

module을 사용하면 css에서 클래스가 중첩되는 것을 방지할 수 있다

 

 

/*Button.module.css*/
.btn {
  color: white;
  background-color: tomato;
}
//Button.js
import PropTypes from 'prop-types';
import styles from './Button.module.css';

function Button({text}) {
	return <button className={styles.btn}>{text}</button>;
}

Button.propTypes = {
	text: PropTypes.string.isRequired,
}

export default Button;

 

/* App.module.css */
.title {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  font-size: 24px;
}
import Button from './Button';
import styles from './App.module.css';

function App() {
  return (
    <div>
      <h1 className={styles.title}>Welcome Back!!!</h1>
      <Button text={'Continue'}/>
    </div>
  );
}

export default App;

 

MODULE.CSS 복습하기 :

CRA의 고유 기능으로, className을 활용하여 전역이 아닌 컴포넌트에 한정해서 스타일을 정해줄 수 있다.