1 - 06. JS와 JSX 섞어쓰기

msg016·2022년 6월 18일
0

React lecture

목록 보기
5/8
패스트캠퍼스 '한 번에 끝내는 React의 모든 것' 수강 후 정리.

Custom Component를 함수로 호출할 수 있다.

const $root = document.getElementById("root");
const Paint = ({ title, description, children }) => (
  <>
    <h1>{title}</h1>
    <h3>{description}</h3>
    {children}
  </>
);

const $element = (
  <Paint title="Good" description="good">
    {Paint({ title: "Bad", description: "bad", children: "hi" })}
  </Paint>
);

ReactDOM.render($element, $root);

위 코드의 <Paint />{ Paint(...args) }는 동일하게 동작한다.

JSX와 JS를 함께 작성할 수 있다.

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

const Text = ({ text }) => {
  if (text[0] === text[0].toUpperCase()) {
    return <h1>{text}</h1>;
  } else {
    return <h3>{text}</h3>;
  }
};

const $element = (
  <>
    <Text text="Text" />
    <Text text="text" />
  </>
);

ReactDOM.render($element, $root);

위의 Text 컴포넌트는 자바스크립트의 if ~ else 문법과 템플릿 문자열 그리고 JSX 문법을 함께 사용하고 있다.
해당 컴포넌트는 if문에 따라 입력받은 text의 맨 앞 글자가 대문자라면 <h1> 태그를, 아니라면 <h3> 태그를 반환하여 그려질 것이다.
자바스크립트의 여러 문법을 함께 사용할 수 있다.

  • 삼항연산자

    function Number({ number }) {
      return number % 2 === 0 ? <h1>{number}</h1> : <h3>{number}</h3>;
    }
    
    const $element = (
      <>
        <Number number={1} />
        <Number number={2} />
      </>
    );
  • 반복문(for loop, Array.prototype.map 등)

    function Number({ number }) {
      return number % 2 === 0 ? <h1>{number}</h1> : <h3>{number}</h3>;
    }
    
    const $element = (
      <>
        {[1, 2, 3, 4, 5].map((number) => (
          <Number number={number} />
        ))}
      </>
    );
profile
프론트엔드 개발자 지망생

0개의 댓글