리액트에는 특히 JSX 라는 문법을 써야한다.
JSX를 쓰면 얼마나 편리한지 알아보자
import "./styles.css";
const user = {
firstName: "HTML",
lastName: "DOM"
};
function formatName(user) {
return user.firstName + " " + user.lastName;
}
var heading = document.createElement("h1");
heading.textContent = `Hello, ${formatName(user)}`;
document.body.appendChild(heading);
결과
Hello, HTML DOM
HTML과 DOM 이라는 글자가 들어있는 변수를 가지고 출력하기 위해서는,
하지만 리액트를 통해 JSX를 쓸 경우
import React from "react";
import "./styles.css";
function App() {
const user = {
firstName: "React",
lastName: "JSX Activity"
};
function formatName(user) {
return user.firstName + " " + user.lastName;
}
return <h1>Hello, {formatName(user)}!</h1>;
}
export default App;
html과 js파일을 따로 분리시켜서 할필요없이 한 페이지에서 가능하다.
1, 2, 3, 4과정에 하나로 단축이 된다.
function App() {
const name = '리액트';
return {
<div>
<h1>
{name}
</h1>
</div>
}
}
{} 괄호 안에 변수 이름을 넣어서 사용할 수 있음
{name === '리액트'? (
<h1>리액트</h1>
) : (
<h2>리액트가 아님</h2>
)}
if 문으로 하면 이렇다
if (name === '리액트) {
return <h1>리액트</h1>
}
return <h2>리액트가 아님</h2>
}
const element = <img src= />
function App() {
return (
<div>
<h1>test</h1>
<h2>test1</h2>
</div>
)
}
div가 빠지면 안됨!
const posts = [
{ id : 1, title : 'Hello World', content : 'Welcome to learning React!' },
{ id : 2, title : 'Installation', content : 'You can install React via npm.' },
{ id : 3, title : 'reusable component', content : 'render easy with reusable component.' },
// ...
{ id : 100, title : 'I just got hired!', content : 'OMG!' },
];
function Blog() {
const postToElement = (post) => (
<div>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
const blogs = posts.map(postToElement);
return <div className="post-wrapper">{blogs}</div>;
}
직접 작성해서 사용법 익숙해질 것!
<ul>
<li>first</li>
<li>second</li>
</ul>
이러한 코드가 있을 때, second 뒤에 third라는 걸 추가하면 아무 문제가 없지만 first앞에 zero라는 걸 추가할 경우, 최적화가 필요
최적화를 하기 위해 사용되는 방법이 key!
<ul>
<li key="zero" >zero</li>
<li key="first" >first</li>
<li key="second" >second</li>
</ul>
이렇게하면
zero를 key로 가지는 , 자식노드 추가허고
first와 second를 키로 가지는 자식 노드는 변경이 없음, 이렇게 최적화가 이루어짐
const todoItems = todos.map((todo) =>
<li key ={todo.id}>
{todo.text}
</li>
);
<div className = "classEx1">