JSX의 정의와 역할

2023. 2. 6. 12:13FrontEnd & Mobile/React

JSX란?

A syntax extension to JavaScript

=자바스크립트의 확장 문법

 

=> JavaScript + XML/HTML

 

[JSX 코드]

const element = <h1>Hello, world!</h1>;

 

 

JSX의 역할

내부적으로 XML, HTML 코드를 JS로 변환하는 과정을 거치게 됨

그렇기 때문에 실제로 우리가 JSX로 코드를 작성해도 최종적으로는 js 코드가 나오게 되는 것임

 

React.createElement(
	type,
    [props],
    [...children]
)

 

[JSX를 사용한 코드]

class Hello extends React.Compoenet {
	render() {
    	return <div>Hello {this.props.toWhat}</div>;
    }
}

ReactDOM.render(
	<Hello toWhat="World" />,
    document.getElementById('root')
};

[JSX를 사용하지 않은 코드]

class Hello extends React.Component {
	render() {
    	return React.createElement('div', null, `Hello ${this.props.toWhat}`);
    }
}

ReactDOM.render(
	React.createElement(Hello, { toWhat: 'World' }, null,),
    document.getElementById('root')
);

 

 

 


 

 

[JSX를 사용한 코드]

const element = (
	<h1 className="greeting">
    	Hello, world!
    </h1>
)

 

[JSX를 사용하지 않은 코드]

const element = React.createElement(
	'h1',
    {className: 'greeting'},
    'Hello, world!'
)

 

=> React.createElement()의 결과로 아래와 같은 객체가 생성됨

const element = {
    type: 'h1',
    props: {
    	className: 'greeting',
        chilrdren: 'Hello, world!'
    }
}

'React element'

 

[createElement()의 parameter]

React.createElement(
	type,
    [props],
    [...children]
)

*리액트에서 JSX를 쓰는 것이 필수는 아님!*

 

*JSX를 사용하면 장점들이 많기 때문에 편리함!*

 

 

 

[태그의 속성(attribute)에 값을 넣는 방법]

//큰따옴표 사이에 문자열을 넣거나
const element = <div tabIndex="0"></div>;

//중괄호 사이에 자바스크립트 코드를 넣으면 됨!
const element = <img src={user.avatarUrl}></img>;

 

JSX에서는 { }를 사용하면 무조건 js 코드가 들어간다라고 생각하면 됨

 

 

[자식(children)을 정의하는 방법]

const element = (
	<div>
    	<h1>안녕하세요</h1>
        <h2>열심히 리액트를 공부해 봅시다!</h2>
    </div>
);

 

 

 


 

(실습) JSX 코드 작성해보기

 

[src>>chapter_03>>Book.jsx]

import React from "react"

function Book(props) {

    return (
        <div>
            <h1>{`이 책의 이름은 ${props.name}입니다.`}</h1>
            <h2>{`이 책은 총 ${props.numOfPage}페이지로 이루어져 있습니다.`}</h2>
        </div>
    );
}
export default Book;

 

[src>>chapter_04>>Library.jsx]

import React from "react"
import Book from "./Book"

function Library(props) {
    
    return (
        <div>
            <Book name="처음 만난 파이썬" numOfPage={300}/>
            <Book name="처음 만난 AWS" numOfPage={400}/>
            <Book name="처음 만난 리액트" numOfPage={500}/>
        </div>
    );
}
export default Library;

 

[src>>index.js]

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

import Library from './chapter_03/Library';

ReactDOM.render(
  <React.StrictMode>
    <Library/>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

 

 

출처)

인프런>>처음만난리액트

'FrontEnd & Mobile > React' 카테고리의 다른 글

Rendering Elements  (0) 2023.02.15
React 실행 시 오류 해결 방법  (0) 2023.02.15
직접 리액트 연동하기/create-react-app  (0) 2023.02.06
React란 무엇인가?  (0) 2023.02.02
React 시작 전 개발환경 구축  (0) 2023.02.02