강의, 책/[React] ReactJS로 영화 웹 서비스 만들기

#2. The Basics of React

hye3193 2024. 2. 15. 12:39

CreateElement

const root = document.getElementById("root");
const h3 = React.createElement(
    "h3",
    {
        id: "title",
        onMouseEnter: () => console.log("mouse enter"),
    },
    "Hello I'm a title"
);
const btn = // 생략

const container = React.createElement("div", null, [h3, btn]);
ReactDOM.render(container, root);

가장 기본적인 방식으로, createElement(HTML tag, property, content)를 통해 엘리멘트를 만들어내어 랜더 할 수 있다

하지만 사실상 쓸 일 없다

 

JSX

const root = document.getElementById("root");
const Title = (
    <h3 id="title" onMouseEnter={() => console.log("mouse enter")}>
        Hello I'm a title
    </h3>
);

const Button = (
    <button
        style={{
            backgroundColor: "tomato",
        }}
        onclick={() => console.log("im clicked")}
    >
        Click me
    </button>
);

const container = React.createElement("div", null, [Title, Button]);
ReactDOM.render(container, root);

JSX란 Javascript를 확장한 문법으로, HTML과 비슷한 문법으로 리액트 요소를 만들 수 있게 해준다

 

랜더링을 할 때 이전 방식이 아닌 JSX를 이용하기 위한 방법으로는, 각 엘리멘트를 함수로 만들어주면 된다

const root = document.getElementById("root");
function Title() {
    return(
        <h3 id="title" onMouseEnter={() => console.log("mouse enter")}>
            Hello I'm a title
        </h3>
    );
};

const Button = () => (
    <button
        style={{
            backgroundColor: "tomato",
        }}
        onclick={() => console.log("im clicked")}
    >
        Click me
    </button>
);

const Container = () => (
    <div>
        <Title />
        <Button />
    </div>
);
ReactDOM.render(<Container />, root);

arrow function을 활용(ex. Button)하면 function을 선언(ex. Title)하고 return 값을 만들 필요 없이 작성이 가능하다

그리고 이러한 컴포넌트(Title, Button)는 반드시 대문자로 시작해야 한다(HTML 태그와의 혼동)

'강의, 책 > [React] ReactJS로 영화 웹 서비스 만들기' 카테고리의 다른 글

#6. Effects  (0) 2024.02.17
#4. Props  (0) 2024.02.16
#3. State  (0) 2024.02.15