JSX [React]

SnowCat·2023년 1월 5일
0

React - Main Concepts

목록 보기
1/11
post-thumbnail

※ 공식문서를 읽고 정리한 글입니다.

JSX란?

  • React => 렌더링 로직과 UI로직이 연결된다는 사실을 받아들임 => 컴포넌트를 통해 둘을 분리하지 않고 사용
  • JSX는 HTML 스타일로 리액트 컴포넌트를 생성할 수 있게 해주는 기술

JSX와 문법

example

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
);

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>{element}</h1>); // "Hello, Harper Perez!
  • 객채를 생성할 때 createElement()없이 HTML문법으로 객체 생성 가능
  • 중괄호 표현을 사용해 JSX내부에 자바스크립트 표현식 사용 가능

JSX와 속성

const element = <a href="https://www.reactjs.org"> link </a>;  // 문자열
const element = <img src={user.avatarUrl}></img>; // 표현식
  • 따옴표나 중괄호 표현을 사용해 프로퍼티 정의 가능
    둘을 동시에 사용하면 안됨에 주의
  • 프로퍼티 이름은 camelCase를 따르며 className(Html에서는 class)처럼 이름이 다른 경우도 있음

JSX와 자식

const element = (
  <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
);
  • HTML을 쓰듯 자식 태그를 포함할 수 있음

태그가 비어있는 경우

const element = <img src={user.avatarUrl} />;
  • 태그의 내용물이 비어있는 경우 />로 바로 태그를 닫아줘야함

JSX와 보안

const title = response.potentiallyMaliciousInput; //보안상 문제가 될 수 있음
const element = <h1>{title}</h1>;
  • React DOM은 JSX에 삽입된 값을 렌더링하기전에 이스케이프(HTML 태그가 원래 기능을 못하게 변환하는 행위)를 함
  • element에 들어가는 title은 렌더링 전에 문자열로 변환이 되어 의도하지 않은 스크립트를 실행 방지함

JSX는 객체

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

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

//that create (not accurate expression)
const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, world!'
  }
};
  • JSX표현은 Babel을 사용해 React.createElement() 표현으로 변환되고, 이는 다시 자바스크립트 객체로 변환됨
function getGreeting(user) {
  if (user) {
    return <h1>Hello, {formatName(user)}!</h1>;
  }
  return <h1>Hello, Stranger.</h1>;
}
  • JSX는 결국 객체이기 때문에 반복문에 사용하거나, 변수값으로 할당하고, 함수의 반환값이나 input으로 활용 가능

출처:
https://ko.reactjs.org/docs/introducing-jsx.html

profile
냐아아아아아아아아앙

0개의 댓글