[React] JSX, Component
๐๋ฆฌ์กํธ ๊ธฐ์ด ๊ฐ๋
๐JSX
JavaScript๋ฅผ ํ์ฅํ ๋ฌธ๋ฒ
React์์๋ DOM๊ณผ๋ ๋ค๋ฅด๊ฒ css,jsx ๋ฌธ๋ฒ๋ง์ ๊ฐ์ง๊ณ ์น ์ ํ๋ฆฌ์ผ์ด์ ์ ๊ฐ๋ฐํ ์ ์๋ค.
DOM์์ JS์ ํจ๊ป ์ฌ์ฉํ๊ธฐ ์ํด์๋ js์ html์ ์ฐ๊ฒฐํ๊ธฐ ์ํ ์์ ์ด ํ์
Inline ๋ฐฉ์์ด๋ script ํ๊ทธ๋ฅผ ์ด์ฉํด ์ธ๋ถ js ํ์ผ์ ์ฐ๊ฒฐ ๊ฐ๋ฅ
๐ jsx๋ฅผ ์จ์ผํ๋ ์ด์
๋ช ์์ ์ฝ๋ ์์ฑ : js ๋ฌธ๋ฒ๊ณผ html ๋ฌธ๋ฒ์ ๋์์ ์ด์ฉํด ๊ธฐ๋ฅ ๊ตฌ์กฐ๋ฅผ ํ๋์ ํ์ธ ๊ฐ๋ฅ
์ฝ๋๋จ์ํ, ๊ฐ๋ ์ฑ
import React from "react";
import "./styles.css";
function App() {
const user = {
firstName: "React",
lastName: "JSX Activity"
};
function formatName(user) {
return user.firstName + " " + user.lastName;
}
// ์ฃผ์์ ์์ ์ ์ค์ตํด๋ณด๊ธฐ
// JSX ์์ด ํ์ฉํ React
// return React.createElement("h1", null, `Hello, ${formatName(user)}!`);
// JSX ๋ฅผ ํ์ฉํ React
// return <h1>Hello, {formatName(user)}!</h1>;
}
export default App;
๐ jsx ํ์ฉ
1๏ธโฃ ํ๋์ ์๋ฆฌ๋จผํธ ์์ ๋ชจ๋ ์๋ฆฌ๋จผํธ๊ฐ ํฌํจ
<div> // ํ๋์ ์๋ฆฌ๋จผํธ ์์
<div> // ๋ชจ๋ ์๋ฆฌ๋จผํธ๊ฐ ํฌํจ
<h1>Hello</h1>
<div>
<h2>world</h2>
<div>
<div>
</div>
2๏ธโฃ ์๋ฆฌ๋จผํธ ํด๋์ค ์ฌ์ฉ ์, className ์ผ๋ก ํ๊ธฐ
<div className="greeting">Hello!</div> // className
3๏ธโฃ js ํํ์ ์ฌ์ฉ ์, ์ค๊ดํธ({ }) ์ด์ฉ
function App() {
const name = 'Josh Perez';
return(
<div>
Hello, {name}! // jsx์์ js๋ฅผ ์ฐ๊ณ ์ ํ๋ค๋ฉด ๊ผญ ์ค๊ดํธ๋ฅผ ์ด์ฉ!
</div>
);
}
4๏ธโฃ ์ฌ์ฉ์ ์ ์ ์ปดํฌ๋ํธ๋ ๋๋ฌธ์๋ก ์์
function Hello() { // ๊ผญ ๋๋ฌธ์๋ก!
return ~
}
function HelloWorld() {
return <Hello />;
}
5๏ธโฃ ์กฐ๊ฑด๋ถ ๋ ๋๋ง์๋ ์ผํญ์ฐ์ฐ์ ์ฌ์ฉ
์กฐ๊ฑด๋ถ ๋ ๋๋ง์ if๋ฌธ์ด ์๋ ์ผํญ์ฐ์ฐ์๋ฅผ ์ด์ฉํด์ผ ํฉ๋๋ค
<div>
{
(1+1 === 2) ? (<p>์ ๋ต</p>) : (<p>ํ๋ฝ</p>)
}
</div>
6๏ธโฃ ์ฌ๋ฌ ๊ฐ์ html ์๋ฆฌ๋จผํธ๋ฅผ ํ์ํ ๋, map() ํจ์๋ฅผ ์ด์ฉ
const posts = {
{id:1, title: 'Hello World', content : 'Welcome to learning React!'},
{id:2, title: 'Installation', content: 'You can install React from npm.'}
};
function Blog() {
const content = posts.map((post) => // html ์๋ฆฌ๋จผํธ ํ์ "map()" ํจ์
<div key = {post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
<div>
);
}
return (
<div>
{content}
</div>
);
}
post ์ ๋ณด๋ฅผ ๋ด์ ๊ฐ์ฒด๋ฅผ jsx ํํ์์ผ๋ก ๋ฐ๊ฟ ๋ฆฌํดํด์ฃผ๋ ํจ์
๐Component-Based
"ํ๋์ ๊ธฐ๋ฅ ๊ตฌํ์ ์ํ ์ฌ๋ฌ ์ข ๋ฅ์ ์ฝ๋ ๋ฌถ์"
"UI๋ฅผ ๊ตฌ์ฑํ๋ ํ์ ์์"
"์ปดํฌ๋ํธ๋ ๋ฆฌ์กํธ์ ์ฌ์ฅ"
๋ชจ๋ ๋ฆฌ์กํธ ์ฑ์ ์ต์ ํ ๊ฐ์ ์ปดํฌ๋ํธ๋ฅผ ๊ฐ์ง๊ณ ์์ผ๋ฉฐ,
์ด ์ปดํฌ๋ํธ๋ ์ต์์ ์ปดํฌ๋ํธ - ๊ทผ์(root) ์ญํ ์ ํ๋ฉฐ ์์ ์ปดํฌ๋ํธ๋ฅผ ๊ฐ์ง์ ์๋ค.(๊ณ์ธต์ ๊ตฌ์กฐ(ํธ๋ฆฌ๊ตฌ์กฐ))