2020. 7. 18. 10:57ㆍ위키
명령어와 코드 위주로 빠르게 ReactJS 를 시작해봐요
여기를 참고했어요.
ReactJS로 영화 웹 서비스 만들기 - 노마드 코더 Nomad Coders
React Fundamentals
nomadcoders.co
node 및 npm 설치
Node.js
Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.
nodejs.org
$ node -v
$ npm -v
npx 설치
$ npm install npx -g
create-react-app 시작
$ npx create-react-app [앱 이름]
$ cd [앱 이름]
React App 실행하기
$ npm start
src 디렉토리 불필요한 파일 지우기
src 디렉토리의 index.js 와 app.js 를 다음과 같이 수정해요.
// src/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')
);
// src/app.js
import React from 'react';
function App() {
return (
<div className="App" />
);
}
export default App;
나머지 파일은 다 지워요. App.css, App.test.js, index.css, serviceWorker.js 등 등
public 디렉토리 불필요한 파일 지우기
public 디렉토리의 logo.png 와 favicon.ico 도 지워버려요.
새로운 컴포넌트 추가하기
// src/App.js
import React from 'react';
function Component() {
return (
<div className="Component">
<h1>Component</h1>
</div>
);
}
function App() {
return (
<div className="App">
<Component />
</div>
);
}
export default App;
코드를 분리할 수도 있어요.
// src/App.js
import React from 'react';
import Component from './Component';
function App() {
return (
<div className="App">
<Component />
</div>
);
}
export default App;
// src/Component.js
import React from 'react';
function Component() {
return (
<div className="Component">
<h1>Component</h1>
</div>
);
}
export default Component;
어쨋든 결과는 똑같아요.
컴포넌트에 props 전달하기
// src/App.js
function App() {
return (
<div className="App">
<Component props1="Hello" props2="World" />
</div>
);
}
// src/Component.js
function Component(object) {
return (
<div className="Component">
<h1>{object.props1}</h1>
<h1>{object.props2}</h1>
</div>
);
}
ES6 이후로 이렇게 작성할 수도 있어요.
// src/Component.js
function Component({props1, props2}) {
return (
<div className="Component">
<h1>{props1}</h1>
<h1>{props2}</h1>
</div>
);
}
컴포넌트에 배열 props 전달하기
Component.js 코드를 약간 수정했어요.
// src/Component.js
function Component({props}) {
return (
<div className="Component">
<h1>{props}</h1>
</div>
);
}
// src/App.js
const array = ["1", "2", "3"];
function App() {
return (
<div className="App">
{array.map(number => (
<Component props={number} />
))}
</div>
);
}
함수를 이용해서 코드를 분리할 수도 있어요.
// src/App.js
const array = ["1", "2", "3"];
function renderArray(object) {
return <Component props={object}/>
}
function App() {
return (
<div className="App">
{array.map(number => (renderArray(number)))}
</div>
);
}
어쨋든 결과는 똑같아요.
prop-types 설치하기
컴포넌트에서 props 가 전달될 때 제대로 전달하는지를 체크하는 친구에요.
$ npm i prop-types
package.json 의 dependencies 에 prop-types 가 있으면 설치가 잘된거에요.
prop-types 사용하기
일단 적적할 예시를 위해 array 를 바꾸었어요.
// src/App.js
const array = [
{
number: 1,
alphabet: "A"
},
{
number: 2,
alphabet: "B"
}
];
그리고 propTypes 를 추가해요. 대소문자에 주의해요.
// src/App.js
import PropTypes from 'prop-types';
...
Component.propTypes = {
number: PropTypes.number.isRequired,
alphabet: PropTypes.string.isRequired
}
지금은 아무일도 일어나지 않지만 만약에 propTypes 에 맞지 않는 props 들이 있으면 콘솔에 에러 메세지가 나타나요, 나중에 컴포넌트가 커지고 복잡해지면 아주 유용하게 써먹을 수 있어요.
Typechecking With PropTypes – React
A JavaScript library for building user interfaces
reactjs.org
클래스 컴포넌트 사용하기
컴포넌트를 클래스로 선언할 수도 있어요. 기존의 App 컴포넌트는 function 이지만, 이를 클래스로 바꾸어 볼게요.
// src/App.js
class App extends React.Component {
render() {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
}
}
함수랑 비슷해보이지만, 클래스로 구현을 하면 state 라는 걸 사용할 수 있어요. state 란 컴포넌트의 계속 변경되거나 변경할 수 있는 오브젝트에요. 다음 코드를 보면 느낌이 올 거에요.
// src/App.js
class App extends React.Component {
state = {
count: 0
};
add = () => {
this.setState(current => ({count: current.count+1}))
};
minus = () => {
this.setState(current => ({count: this.state.count-1}))
};
render() {
return (
<div>
<h1>Number: {this.state.count}</h1>
<button onClick={this.add}>+</button>
<button onClick={this.minus}>-</button>
</div>
);
}
}
+ 버튼을 누르면 count 가 1씩 증가하고 - 버튼을 누르면 count 가 1씩 감소하는 그런 코드에요. state 의 값은 setState 를 통해서 변경되고, 변경된 부분이 다시 render 되는 방식이에요. 만약 this.state 쓰기가 너무 짜증나면 이렇게 줄일수도 있어요.
// src/App.js
render() {
const {count} = this.state;
return (
<div>
<h1>Number: {count}</h1>
<button onClick={this.add}>+</button>
<button onClick={this.minus}>-</button>
</div>
);
}
어쨋든 결과는 똑같아요.
이 외에도 알아야 되는 것들은 너무너무 많아요. 더 많은 정보를 얻고 싶다면 다음 사이트를 참고해요.
React – A JavaScript library for building user interfaces
A JavaScript library for building user interfaces
reactjs.org
'위키' 카테고리의 다른 글
장고(Django) RESTful Framework 시작하기 (1) | 2020.07.19 |
---|---|
간단한 Command-line HTTP 클라이언트, Httpie (0) | 2020.07.19 |
루비 온 레일즈를 위한 관리 프레임워크, ActiveAdmin (0) | 2020.07.03 |
루비 온 레일즈 v5.2 시작하기 (0) | 2020.07.01 |
루비 튜토리얼 (0) | 2020.06.29 |