ReactJS/Basic

[React JS] React JS 입문 & JSX

Gaeun Lee 2022. 7. 1. 13:41

00. React 를 사용하기 위해서는!

아래의 source를 import 해줘야 한다

<script src="https://unpkg.com/react@17/umd/react.development.js"></script> <!--react-->
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <!--react dom-->

 

 

01. ReactJS 코드 어려운 방식으로 작성하기

createElement는 현직 개발자들이 사용하지 않지만 ReactJS의 기초이자 핵심이다

    /*어려운 방식으로 React-JS 코드 작성하는 방법*/

    const root = document.getElementById("root") // element 가 배치될 위치

    const span = React.createElement("span", {id: "sexy-span"}, "hello"); // span 생성
    // 위 함수의 argument 작성을 통해 element를 생성함
    // argument 1) 괄호 안에 태그명을 넣어 element를 생성함
    // argument 2) 대괄호를 통해 property 추가도 가능함
    // argumnet 3) 따옴표 안에 content를 작성함
    // argument 작성 필요 없을 시 => null 

    // 이렇게 생성한 span을 body에 두어야 하는데
    // 이를 위해서 React-DOM 을 이용함
    // React-JS 는 interactive한 UI를 만들 수 있게 하고
    // React-DOM 은 element를 HTML에 두는 역할을 함
   
    ReactDOM.render(span, root)
    // render: React element를 HTML로 만들어 배치함을 뜻함 (사용자에게 보여줌)
    // 괄호 안에 배치할 element와 위치를 적음


    /*
    Vanilla JS 는 HTML을 JS로 가져와 HTML을 수정하는 방식이지만
    React JS 는 모든 것이 JS로부터 시작되어 HTML로 끝남 (수정이 모두 JS에서 이루어짐)
    =>JS를 이용해 element를 생성하고 React JS가 이를 HTML로 번역함
    */

 

 

>>  이벤트 리스너 작성법 + element 배치 방법

    const root = document.getElementById("root"); // element 가 배치될 위치

    const txt = React.createElement("h3", 
    {
        //onMouseEnter property !!EVENTLISTENER!!
        onMouseEnter: () => console.log("mouse enter"),
    }
    , "hello"); // h3 생성
    const btn = React.createElement("button", 
    {
        //onClick property !!EVENTLISTENER!!
        onClick: () => console.log("I'm clicked"),
        
        //style property
        style: {backgroundColor: "tomato"},

    }, "click me"); // button 생성

    /*h3와 button을 배치할 div 생성*/
    const container = React.createElement("div", null, [txt, btn]); // array로 배치함
 
    ReactDOM.render(container, root) // 생성한 container을 #root에 넣어 HTML로 보여줌

 

 

02. ReactJS 코드 쉬운 방식으로 작성하기 : JSX

JSX  는 Javascript를 확장한 문법으로 HTML의 문법과 흡사하기 때문에 React element를 만들기 편하다.

 

Babel (링크): JSX로 적은 코드를 브라우저가 이해할 수 있는 형태로 바꿔주기 위해 설치해야 한다

>> Babel standalone 설치

      standalone은 느리다는 단점을 지녔기 때문에 이것 말고 다른 방식으로 해도 된다

<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
	//여기 안에 JSX 코드 작성
</script>

 

 

(+) Element 와 Component 의 차이

Element는 화면에 나타나게 할 무언가로 Component에 의하여 반환되는 것이고,

Component 는 화면에 렌더링되는 Element를 의미한다

React는 Component 단위로 구성되어 있고, Component는 Element를 반환한다

 

참고 링크 >> https://reactjs.org/docs/glossary.html#elements

 

 

a. element 생성하기

JSX 로 element를 생성하는 것은 HTML 코드를 작성하는 것과 유사하다

<body>
    <div id="root"></div>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
        // element가 배치될 위치
        const root = document.getElementById("root");

        // h3 element 생성
        const Title = (
            <h3 
            id="title" 
            onMouseEnter={() => console.log('mouse enter')}>
                Hello I'm a title
            </h3>
        );
        
        // button element 생성
        const Button = (
           <button 
           style={{
            backgroundColor: "tomato",
           }}
           onClick={() => console.log('clicked')}
           >
                Click Me!
           </button> 
        );
        
        // div element를 생성하여 Title과 Button을 배치
        const container = React.createElement("div",null,[Title,Button]);
        
        // container 위치를 root로 지정하여 HTML로 나타냄
        ReactDOM.render(container, root)
    </script>
</body>

 

 

b. component 생성하기

const root = document.getElementById("root");

// element를 JSX 문법으로 배치하려면
// element 생성시 함수로 만들어야 함
// Arrow Function을 사용함 ... () => 
// element를 component로 사용하기 위해서
// HTML 태그와 구별하기 위해 첫문자를 대문자로 작성해야 함

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('clicked')}
    >
        Click Me!
    </button> 
);

// Title과 Button element를 container에 JSX 문법으로 배치
// Title과 Button을 HTML 태그처럼 취급

const Container = () => (
    <div>
        <Title />
        <Button />
    </div>
);

ReactDOM.render(<Container />, root)