JSX : JS eXtended
React.JS 개발에 사용되는 문법으로, JS의 공식적인 문법이 아님
Babel 라이브러리를 이용해 컴파일 과정에서 일반적인 JS 형태로 변환됨
// JSX 형태로 작성한 코드
const App = () => {
return (
<h1> Hello, World! </h1>
);
}
// 컴파일 이후 Babel 라이브러리에 의해 일반적인 JS 형태로 변환된 코드
const App = () => {
return React.createElement("h1", null, "Hello, World!");
}
JSX 대표 문법
JSX의 return문 내에서는 반드시 하나의 요소가 나머지를 감싸는 형태여야 한다.
// 올바른 코드 1 <div></div>
const App = () => {
return (
<div>
<h1> Hello, World! </h1>
<h1> Bye, World! </h1>
</div>
);
}
// 올바른 코드 2 <Fragment></Fragment>
const App = () => {
return (
<Fragment>
<h1> Hello, World! </h1>
<h1> Bye, World! </h1>
</Fragment>
);
}
// 올바른 코드 3 <></>
const App = () => {
return (
<>
<h1> Hello, World! </h1>
<h1> Bye, World! </h1>
</>
);
}
// 오류가 발생하는 코드
const App = () => {
return (
<h1> Hello, World! </h1>
<h1> Bye, World! </h1>
);
}
JSX의 return 문 내에서의 JS 표현식은 { } 로 감싸서 표현한다.
// 예시 1
const App = () => {
let date = "2022. 07. 08.";
return (
<div>
<h1> {date} </h1>
</div>
);
}
// 예시 2
const App = () => {
let a = 1;
let b = 2;
return (
<div>
<h1> {a + b} </h1>
</div>
);
}
단, if 구문과 for 구문의 경우는 "표현식"이 아니기 때문에 조금 특별하게 구현됨
// 방법 1 : JSX 외부에서 사용
const App = () => {
let a = 1;
if(a == 1){
return (
<div>
<h1> This is 1 </h1>
</div>
);
}else{
return (
<div>
<h1> This is Not 1 </h1>
</div>
);
}
}
// 방법 2 : 삼항연산 사용
const App = () => {
let a = 1;
return (
<div>
{
a == 1 ? (
<h1> This is 1 </h1>
) : (
<h1> This is Not 1 </h1>
)
}
</div>
);
}
// AND 연산, 임시함수 등의 방법도 있으나 위의 두가지를 주로 사용
JSX 내에서의 주석 표현
const App = () => {
return (
<div>
{/* 와! 주석! 아시는구나! */}
<h1> Hello, World! </h1>
</div>
);
}
컴포넌트 : React.JS로 개발된 웹을 이루는 최소한의 단위
클래스형 컴포넌트 (Deprecated)
컴포넌트의 구성 요소와 리액트의 생명주기를 모두 다룰 수 있는 형태
React.JS는 함수형 프로그래밍을 지향하는 프로젝트라는 이유로 최근 버전에서는 다루지 않음
class App extends React.Component {
constructor(props){
super(props);
}
render(){
return (
<div>
<h1> Hello, World! </h1>
</div>
);
}
}
함수형 컴포넌트
컴포넌트의 구성 요소는 다룰 수 있지만, React.JS의 생명주기는 다룰 수 없는 형태
생명주기를 다룰 수 없는 대신, useEffect Hook을 이용해 생명주기 구현
const App = (props) => {
return (
<div>
<h1> Hello, World! </h1>
</div>
);
}
React.JS 컴포넌트 생명주기 : 함수형 컴포넌트에서는 다루지 않는 내용이므로 이런게 있다~ 정도로만 알고 넘어가기
Mount : DOM에 요소가 추가되는 과정
생명주기 함수 | 호출되는 시점 |
---|---|
constructor() | 가장 먼저 호출되어 State와 Props를 비롯한 초기 값을 설정 |
getDerivedStateFromProps() | DOM에 요소가 렌더링되기 직전에 호출 |
Props 값에 기반하여 State의 초기 값을 설정 | |
render() | 이름 그대로 DOM에 요소를 렌더링 |
componentDidMount() | DOM에 요소가 렌더링이 완료된 직후 호출 |
Update : DOM에 존재하는 요소의 값이 업데이트되는 과정
생명주기 함수 | 호출되는 시점 |
---|---|
getDerivedStateFromProps() | DOM의 컴포넌트가 업데이트 될 때 가장 먼저 호출 |
shouldComponentUpdate() | React 엔진이 렌더링을 이어나갈지, 멈출지에 대한 Boolean 값 결정 |
render() | 이름 그대로 DOM에 새로 업데이트된 요소를 렌더링 |
getSnapshotBeforeUpdate() | 값이 업데이트되기 직전의 State와 Props 값에 접근할 수 있음 |
componentDidUpdate() | DOM에 요소가 업데이트된 직후 호출 |
Unmount : 요소가 DOM으로부터 제거되는 과정
생명주기 함수 | 호출되는 시점 |
---|---|
componentWillUnmount() | 요소가 제거될 때 호출되는 유일한 함수 |
React.JS의 컴포넌트를 나누어 개발하는 방식
Props : 상위 컴포넌트에서 하위 컴포넌트로 전달하는 변수
const App = () => {
return(
<>
<Child month={7}/>
</>
);
}
const Child = (props) => {
return(
<>
<h1> 지금은 {props.month}월 {props.day}일 입니다. </h1>
</>
);
}
// Props 변수의 자료형 지정
Child.propTypes = {
month: PropTypes.number,
day: PropTypes.string
}
// Props 변수의 기본값 지정
Child.defaultProps = {
month: 1,
day: "1"
}
State : 컴포넌트가 갖는 상태 변수 관리. Hook에서 자세히 다루는 내용
import {useState} from "react";
const App = () => {
// month 라는 이름으로 상태 변수에 접근
// setMonth(값) 의 형태로 함수를 호출하여 상태 변수 값 업데이트
const [month, setMonth] = useState(7);
const add = () => {
setMonth(month + 1)
}
return(
<>
<button onClick={add}></button>
<h1> 지금은 {month}월 입니다. </h1>
</>
);
}
export default App;
-------------------------------
const App = () => {
let month = 7;
const add = () => {
month++;
}
return(
<>
<button onClick={add} ></button>
<h1> 지금은 {month}월 입니다. </h1>
</>
);
}
export default App;