관리 메뉴

Silver Library (Archived)

뭘 놓쳤을까? - react props 본문

Face the fear, build the future/Revision Sector

뭘 놓쳤을까? - react props

Chesed Kim 2022. 7. 25. 11:48
반응형

지금 까지 알고 있었던 react props 는 오직, document 에 예시로 올라온 그 props 만 알고 있었습니다.

 

아래의 이 코드들 말이죠.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

그리고 컴포넌트 렌더링은 이런 식으로 예시가 나와있습니다.

function Welcome(props) {  
	return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;ReactDOM.render(
  element,
  document.getElementById('root')
);

 

그런데 독학으로 지금까지 오신 분들이라면 어쩌면 처음 볼 지도 모르는 유형이 있을거라 생각됩니다.

아래 코드의 constructor 생성자 다음의 state 부분에 template literal 을 사용해서, string 이 아닌, props 로서 참조 하도록 표현식이 작성 된 경우 입니다.

import React, { Component } from 'react';
import Img from 'gatsby-image';
import cx from 'classnames';

import styles from './imagery.module.scss';

export class Imagery extends Component {
  constructor(props) {
    super()
    this.state = {
    // props 가 쓰이긴 쓰였는데, 좌우로 ``backtick 이 있습니다.
      sizer: `styles.${props.size.toLowerCase()}`
    }
  }
  render() {
    return (
      <React.Fragment>
        <Img
          className={cx([this.state.sizer], {
            [styles.firstImage]: this.props.firstImage,
          })}
          fluid={this.props.image}
        />
        {this.props.caption ? (
          <p className={styles.caption}>{this.props.caption}</p>
        ) : (
          false
        )}
      </React.Fragment>
    );
  }
}

export default Imagery;
 

Pass a template literal into props as an expression and not a string

So I'm trying to use the classnames package to conditionally set classNames for my component but the argument needs to be an expression rather than a string, otherwise it parses it incorrectly. H...

stackoverflow.com

이게 도대체 왜 쓰인 걸까?

우선 문제를 세분화 해서 알아보았습니다.

먼저, 저 template literamls (또는 template string) 은 무엇일까요?

 

Template literals (Template strings) - JavaScript | MDN

Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, for string interpolation with embedded expressions, and for special constructs called tagged templates.

developer.mozilla.org

Along with having normal strings, template literals can also contain other parts called placeholders, which are embedded expressions delimited by a dollar sign and curly braces: ${expression}. 

저 ${expression} 같이 달러 사인과 함께 curly bracket (이거 -> {}) 을 사용해서, 그 내부에 props 명들을 여러개 나열하며 코드를 구성한 경우라고 이해 할 수 있겠습니다.

 

예시를 다시 보면, 분명히 달러 사인 안에 curly bracket 으로 감싸져 있습니다.

sizer: `styles.${props.size.toLowerCase()}`

 

이걸 사용 하는 방법은?

정확히는, "어떨 때 사용할 수 있을까?" 라고 볼 수도 있겠습니다.

더 생소한, 생전 처음보는 코드를 하나 참고용으로 가져와 봤습니다.

마찬가지로, 문제의 리터럴 템플릿 표현식을 사용 한 경우입니다.

...
return () {
    <div>
      <SomeComponent key={`some-${someVariable}`} />
      <AnotherComponent />
    </div>
}

 

 

JavaScript React Syntax - Template literal inside component props breaks highlighting · Issue #51171 · microsoft/vscode

Issue Type: Bug Inside a .jsx file (JavaScript React Syntax) call a component in render and pass a prop with template literals. Example: ... return () { <div> <SomeComponent key={`some-${s...

github.com

그런데 잠깐! 이거, 왠지 낯익은 방식입니다.

만약 당신이 금융 과목을 대학 때 한번이라도 들어 봤다면,

꽤 높은 확률로 다뤄 봤을 그 엑셀에서 쓰이는 매크로 함수가 떠오르지 않나요?

당시에는 뭐가 뭔지 몰라도, '메크로 였고, 뭔가 체인 역할 비슷한 걸 했었다!' 라는 것만은 확실하게 기억에 남습니다.

 

저는 그것과 비슷하다고 봅니다. 지금 저 리터럴 템플릿 표현식 중에, {`some-${someVariable}`} 이라고, 달러사인 옆에 dash(-) 가 있습니다. 어쩌면 저걸 토대로, 해당 함수가 자동적으로 생성되도록 하는 create instance 같은 기능이 구현 될 예정 인 건지도 모르겠습니다.

<section 
    class="slider" 
    data-slick={`{"slidesToShow":${props.number},"autoplay": ${props.autoplay},  "responsive": [{"breakpoint":${props.breakpoint},"settings":{"slidesToShow": ${props.show}}}]}`}
>
 

template literals in jsx

I want to use this but props <section class="slider" data-slick='{"slidesToShow": 3,"autoplay": true, "responsive": [{"breakpoint":600,"se...

stackoverflow.com

그래서, 이거 왜 사용하죠?

저도 알아 보면서, 감은 오는데 이걸 써야 한다니 하면서 극혐 언제 사용하나에 대해 고민을 해보며 이리저리 알아 봤습니다. 이 리터럴 템플릿은 다음과 같이 그 필요성에 대해 설명 한 분이 있습니다.

플릿 리터럴은 내장된 표현식을 허용하는 문자열 리터럴입니다.
템플릿 리터럴은 표현식/문자열 삽입, 여러 줄 문자열, 문자열 형식화, 문자열 태깅 등 다양한 기능을 제공합니다.
ES2015 사양명세서에선 template strings라고 불렸습니다.
템플릿 리터럴은 런타임 시점에 일반 자바스크립트 문자열로 처리/변환됩니다.

프론트엔드에서는 HTML을 데이터와 결합해서 DOM을 다시 그려야 하는 일이 빈번하기 때문에, 템플릿을 좀 더 쉽게 편집하고 작성해야 할 필요가 있어서, 이러한 기능이 추가되었습니다.(자바스크립트 자체적으로 지원하기 전에도 라이브러리로 존재했습니다.)

참고 (추천)

 

 

[JavaScript] ES6 템플릿 리터럴에 대해 알아보자!!

[JavaScript] ES6 템플릿 리터럴에 대해 알아보자!! 안녕하세요. 이번 포스팅은 ES6의 템플릿 리터럴과 활용법에 대해 알아봅니다. Template literals 템플릿 리터럴 은 내장된 표현식을 허용하는 문자열

eblee-repo.tistory.com

 

 

How to use Props in React

Everything you need to know about props in React. How to pass props to components, how to set default props, how to know the difference between props and state, and how to pass components or functions as props, ...

www.robinwieruch.de

비고.

여기에서 좀 더 나아가면 dependecy 고려 요소도 있던데, 그건 useEffect 때 다뤄보겠습니다.