React - Get Started
React
시작하기 - 예전부터 React
를 따로 공부해야지 하고 있다가, 잠깐 향만 맡고 말았었다.
이번에는 간단하게라도 Next.js
를 써보는데 까지 목표를 잡고 가보려 한다.
Docker랑, 정처기 실기도 공부해야되느네…….
React 기본
React
는 라이브러리냐 프레임워크냐 논란이 있는 부분이 있다. 일단 React 팀은 라이브러리
로 명명하고 있다.
일단 React 를 사용하기 위해서는 react-dom, react
라이브러리는 설치를 하여야한다.
아래는 간단한 사용 예제이며 React 는 JSX
라는 JS 에서는 조금은 변형된 문법을 사용을 하며 이를 정상 동작 하게끔 하기 위해서는 Babel
(transpiler, compiler 이것도 논란이 있는 것 같다. 바벨 홈페이지에는 Compiler 라고 되어 있다.) 이 필요하다.
// 리액트 컴포넌트 -> HTMLElement 연결 라이브러리
import ReactDom from 'react-dom'
// 리액트 컴포넌트 만들어주는 라이브러리
import React from 'react'
/*
React.createElement(
type, // 태그이름 문자열 | 리액트 컴포넌트 | React.Fragment
[props], // 컴포넌트가 받는 데이터 객체
[...children] // 자식요소들
)
*/
const Component = props => {
return React.createElement('h1', null, props.field);
}
Component.defaultProps = {
field: 'default'
}
ReactDOM.render(
React.createElement(Component, {field: 'test'}, null),
document.querySelector("body");
)
ReactDOM.render(
<div>
<h1>Test</h1>
<div>
<p>React Get started</p>
</div>
</div>,
document.querySelector("body");
)
기본적인 사용법은 공식문서나 예제를 찾아보자! 생략한다.
Fragment
Vue
도 그렇지만 React 도 컴포넌트는 단일 태그로 닫혀있어야 한다. 하지만 그렇지 않아야 할 경우가 있다. 그럴 때 사용하는 Fragment
이다. Vue 3 에서는 그냥 사용가능하고 2 는 추가 설치가 필요하다.
React 에서는 아래와 같이 쓸수 있다.
ReactDOM.render(
React.createElement(React.Fragment, {field: 'test'}, null),
document.querySelector("body");
)
ReactDOM.render(
<>
<h1>Test</h1>
<div>
<p>React Get started</p>
</div>
</>,
document.querySelector("body");
)
Props, state
컴포넌트에 주입하는 데이터 props
와 컴포넌트의 상태값 state
의 변화에 따라 컴포넌트는 리랜더링 된다.
// function Component() {
// return (
// <div>
// <button onClick{() => {
// console.log('test')
// }}>
// Click
// </button>
// </div>
// )
// }
class Component extends React.Component {
// constructor(props) {
// super(props);
// this.increaseCount = this.increaseCount.bind(this);
// }
state = {
count: 0
}
render() {
return (
<div>
<p>{ this.state.count }</p>
<button onClick{ this.increaseCount }>
Click
</button>
</div>
)
}
increaseCount = () => {
this.setSate((state) => ({
...state,
count: state.count + 1,
}));
}
}
ReactDom.render(<Component />, document.querySelector('body'));