Describing the UIUI 구성하기

React is a JavaScript library for rendering user interfaces (UI). UI is built from small units like buttons, text, and images. React lets you combine them into reusable, nestable components. From web sites to phone apps, everything on the screen can be broken down into components. In this chapter, you’ll learn to create, customize, and conditionally display React components. React는 사용자 인터페이스(UI)를 렌더링하기 위한 JavaScript 라이브러리입니다. UI는 버튼, 텍스트, 이미지와 같은 작은 단위로 구성됩니다. React를 사용하면 재사용 가능하고 중첩 가능한 컴포넌트로 결합할 수 있습니다. 웹 사이트부터 휴대폰 앱까지 화면의 모든 것을 컴포넌트로 분류할 수 있습니다. 이 장에서는 React 컴포넌트를 만들고, 사용자 정의하고, 조건부로 표시하는 방법을 배웁니다.

Your first component첫 번째 컴포넌트

React applications are built from isolated pieces of UI called components. A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a Gallery component rendering three Profile components: React 애플리케이션은 컴포넌트라고 불리는 분리된 UI 조각으로 구축됩니다. React 컴포넌트는 마크업으로 뿌릴 수 있는 JavaScript 함수입니다. 컴포넌트는 버튼처럼 작을 수도 있고 전체 페이지처럼 클 수도 있습니다. 다음은 세 개의 Profile 컴포넌트를 렌더링하는 Gallery 컴포넌트입니다:

function Profile() {
  return (
    <img
      src="https://i.imgur.com/MK3eW3As.jpg"
      alt="Katherine Johnson"
    />
  );
}

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

Ready to learn this topic?

Read Your First Component to learn how to declare and use React components. React 컴포넌트를 선언하고 사용하는 방법을 알아보려면 첫 번째 컴포넌트를 읽어보세요.

Read More

Importing and exporting components 컴포넌트 import 및 export

You can declare many components in one file, but large files can get difficult to navigate. To solve this, you can export a component into its own file, and then import that component from another file: 하나의 파일에 여러 컴포넌트를 선언할 수 있지만 파일이 크면 탐색하기 어려울 수 있습니다. 이 문제를 해결하려면 컴포넌트를 자체 파일로 export(내보내기)한 다음 다른 파일에서 해당 컴포넌트를 import(가져오기)하면 됩니다:

import Profile from './Profile.js';

export default function Gallery() {
  return (
    <section>
      <h1>Amazing scientists</h1>
      <Profile />
      <Profile />
      <Profile />
    </section>
  );
}

Ready to learn this topic?

Read Importing and Exporting Components to learn how to split components into their own files. 컴포넌트를 자체 파일로 분할하는 방법을 알아보려면 컴포넌트 import 및 export를 읽어보세요.

Read More

Writing markup with JSXJSX로 마크업 작성하기

Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information. 각 React 컴포넌트는 React가 브라우저에 렌더링하는 일부 마크업을 포함할 수 있는 JavaScript 함수입니다. React 컴포넌트는 JSX라는 구문 확장자를 사용해 해당 마크업을 표현합니다. JSX는 HTML과 매우 비슷해 보이지만 조금 더 엄격하고 동적 정보를 표시할 수 있습니다.

If we paste existing HTML markup into a React component, it won’t always work: 기존 HTML 마크업을 React 컴포넌트에 붙여넣으면 항상 작동하는 것은 아닙니다:

export default function TodoList() {
  return (
    // This doesn't quite work!
    <h1>Hedy Lamarr's Todos</h1>
    <img
      src="https://i.imgur.com/yXOvdOSs.jpg"
      alt="Hedy Lamarr"
      class="photo"
    >
    <ul>
      <li>Invent new traffic lights
      <li>Rehearse a movie scene
      <li>Improve spectrum technology
    </ul>

If you have existing HTML like this, you can fix it using a converter: 이와 같은 기존 HTML이 있다면 converter를 사용하여 수정할 수 있습니다:

export default function TodoList() {
  return (
    <>
      <h1>Hedy Lamarr's Todos</h1>
      <img
        src="https://i.imgur.com/yXOvdOSs.jpg"
        alt="Hedy Lamarr"
        className="photo"
      />
      <ul>
        <li>Invent new traffic lights</li>
        <li>Rehearse a movie scene</li>
        <li>Improve spectrum technology</li>
      </ul>
    </>
  );
}

Ready to learn this topic?

Read Writing Markup with JSX to learn how to write valid JSX. 유효한 JSX를 작성하는 방법을 알아보려면 JSX로 마크업 작성하기를 참조하세요.

Read More

JavaScript in JSX with curly bracesJSX에서 JavaScript 사용하기

JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to “open a window” to JavaScript: JSX를 사용하면 JavaScript 파일 내에 HTML과 유사한 마크업을 작성하여 렌더링 로직과 콘텐츠를 같은 위치에 유지할 수 있습니다. 때로는 마크업 안에 약간의 JavaScript 로직을 추가하거나 동적 프로퍼티를 참조하고 싶을 때가 있습니다. 이 경우 JSX에서 중괄호를 사용하여 JavaScript로의 ‘창을 열’ 수 있습니다:

const person = {
  name: 'Gregorio Y. Zara',
  theme: {
    backgroundColor: 'black',
    color: 'pink'
  }
};

export default function TodoList() {
  return (
    <div style={person.theme}>
      <h1>{person.name}'s Todos</h1>
      <img
        className="avatar"
        src="https://i.imgur.com/7vQD0fPs.jpg"
        alt="Gregorio Y. Zara"
      />
      <ul>
        <li>Improve the videophone</li>
        <li>Prepare aeronautics lectures</li>
        <li>Work on the alcohol-fuelled engine</li>
      </ul>
    </div>
  );
}

Ready to learn this topic?

Read JavaScript in JSX with Curly Braces to learn how to access JavaScript data from JSX. JSX에서 JavaScript 사용하기를 읽고 JSX에서 JavaScript 데이터에 액세스하는 방법을 알아보세요.

Read More

Passing props to a component컴포넌트에 props 전달하기

React components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, functions, and even JSX! React 컴포넌트는 서로 통신하기 위해 props를 사용합니다. 모든 부모 컴포넌트는 자식 컴포넌트에 props를 전달하여 일부 정보를 전달할 수 있습니다. props라고 하면 HTML 어트리뷰트를 떠올릴 수 있지만 객체, 배열, 함수, 심지어 JSX를 포함한 모든 JavaScript 값을 전달할 수 있습니다!

import { getImageUrl } from './utils.js'

export default function Profile() {
  return (
    <Card>
      <Avatar
        size={100}
        person={{
          name: 'Katsuko Saruhashi',
          imageId: 'YfeOqp2'
        }}
      />
    </Card>
  );
}

function Avatar({ person, size }) {
  return (
    <img
      className="avatar"
      src={getImageUrl(person)}
      alt={person.name}
      width={size}
      height={size}
    />
  );
}

function Card({ children }) {
  return (
    <div className="card">
      {children}
    </div>
  );
}

Ready to learn this topic?

Read Passing Props to a Component to learn how to pass and read props. 컴포넌트에 props 전달하기를 읽고 props를 전달하고 읽는 방법을 알아보세요.

Read More

Conditional rendering조건부 렌더링

Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like if statements, &&, and ? : operators. 컴포넌트는 여러 조건에 따라 다른 것을 표시해야 하는 경우가 많습니다. React에서는 if 문, &&, ? : 연산자 같은 JavaScript 구문을 사용해 조건부로 JSX를 렌더링할 수 있습니다. In this example, the JavaScript && operator is used to conditionally render a checkmark: 이 예제에서는 JavaScript && 연산자를 사용하여 체크 표시를 조건부로 렌더링합니다:

function Item({ name, isPacked }) {
  return (
    <li className="item">
      {name} {isPacked && '✔'}
    </li>
  );
}

export default function PackingList() {
  return (
    <section>
      <h1>Sally Ride's Packing List</h1>
      <ul>
        <Item
          isPacked={true}
          name="Space suit"
        />
        <Item
          isPacked={true}
          name="Helmet with a golden leaf"
        />
        <Item
          isPacked={false}
          name="Photo of Tam"
        />
      </ul>
    </section>
  );
}

Ready to learn this topic?

Read Conditional Rendering to learn the different ways to render content conditionally. 조건부 렌더링을 읽고 콘텐츠를 조건부로 렌더링하는 다양한 방법을 알아보세요.

Read More

Rendering lists 목록 렌더링

You will often want to display multiple similar components from a collection of data. You can use JavaScript’s filter() and map() with React to filter and transform your array of data into an array of components. 데이터 모음에서 유사한 컴포넌트를 여러 개 표시하고 싶을 때가 많습니다. React에서 JavaScript의 filter()map()을 사용해 데이터 배열을 필터링하고 컴포넌트 배열로 변환할 수 있습니다.

For each array item, you will need to specify a key. Usually, you will want to use an ID from the database as a key. Keys let React keep track of each item’s place in the list even if the list changes. 각 배열 항목마다 key를 지정해야 합니다. 보통 데이터베이스의 ID를 key로 사용하는 것이 좋습니다. 키를 사용하면 목록이 변경되더라도 React가 목록에서 각 항목의 위치를 추적할 수 있습니다.

import { people } from './data.js';
import { getImageUrl } from './utils.js';

export default function List() {
  const listItems = people.map(person =>
    <li key={person.id}>
      <img
        src={getImageUrl(person)}
        alt={person.name}
      />
      <p>
        <b>{person.name}:</b>
        {' ' + person.profession + ' '}
        known for {person.accomplishment}
      </p>
    </li>
  );
  return (
    <article>
      <h1>Scientists</h1>
      <ul>{listItems}</ul>
    </article>
  );
}

Ready to learn this topic?

Read Rendering Lists to learn how to render a list of components, and how to choose a key. 컴포넌트 목록을 렌더링하는 방법과 키를 선택하는 방법을 알아보려면 목록 렌더링을 읽어보세요.

Read More

Keeping components pure컴포넌트 순수성 유지

Some JavaScript functions are pure. A pure function: 일부 JavaScript 함수는 순수 함수입니다. 순수함수는:

  • Minds its own business. It does not change any objects or variables that existed before it was called.
  • Same inputs, same output. Given the same inputs, a pure function should always return the same result.
  • 자신의 일만 처리합니다. 호출되기 전에 존재했던 객체나 변수를 변경하지 않습니다.
  • 동일 입력, 동일 출력. 순수 함수는 동일한 입력이 주어지면 항상 동일한 결과를 반환해야 합니다.

By strictly only writing your components as pure functions, you can avoid an entire class of baffling bugs and unpredictable behavior as your codebase grows. Here is an example of an impure component: 컴포넌트를 순수 함수로만 엄격하게 작성하면 코드베이스가 커짐에 따라 당황스러운 버그와 예측할 수 없는 동작이 발생하는 것을 방지할 수 있습니다. 다음은 불순한 컴포넌트의 예시입니다:

let guest = 0;

function Cup() {
  // Bad: changing a preexisting variable!
  guest = guest + 1;
  return <h2>Tea cup for guest #{guest}</h2>;
}

export default function TeaSet() {
  return (
    <>
      <Cup />
      <Cup />
      <Cup />
    </>
  );
}

You can make this component pure by passing a prop instead of modifying a preexisting variable: 기존 변수를 수정하는 대신 prop을 전달하여 이 컴포넌트를 순수하게 만들 수 있습니다:

function Cup({ guest }) {
  return <h2>Tea cup for guest #{guest}</h2>;
}

export default function TeaSet() {
  return (
    <>
      <Cup guest={1} />
      <Cup guest={2} />
      <Cup guest={3} />
    </>
  );
}

Ready to learn this topic?

Read Keeping Components Pure to learn how to write components as pure, predictable functions. 컴포넌트를 순수하고 예측 가능한 함수로 작성하는 방법을 알아보려면 컴포넌트 순수성 유지를 읽어보세요.

Read More

Your UI as a tree트리로서의 UI

React uses trees to model the relationships between components and modules. React는 모듈과 컴포넌트 사이의 관계를 트리 형태로 구성합니다.

A React render tree is a representation of the parent and child relationship between components. React의 렌더 트리는 컴포넌트간의 부모와 자식관계를 나타낼 수 있습니다.

A tree graph with five nodes, with each node representing a component. The root node is located at the top the tree graph and is labelled 'Root Component'. It has two arrows extending down to two nodes labelled 'Component A' and 'Component C'. Each of the arrows is labelled with 'renders'. 'Component A' has a single 'renders' arrow to a node labelled 'Component B'. 'Component C' has a single 'renders' arrow to a node labelled 'Component D'.
A tree graph with five nodes, with each node representing a component. The root node is located at the top the tree graph and is labelled 'Root Component'. It has two arrows extending down to two nodes labelled 'Component A' and 'Component C'. Each of the arrows is labelled with 'renders'. 'Component A' has a single 'renders' arrow to a node labelled 'Component B'. 'Component C' has a single 'renders' arrow to a node labelled 'Component D'.

An example React render tree. React 렌더 트리의 예시

Components near the top of the tree, near the root component, are considered top-level components. Components with no child components are leaf components. This categorization of components is useful for understanding data flow and rendering performance. 트리 상단 근처, 루트 컴포넌트 근처에 있는 컴포넌트는 최상위 컴포넌트로 간주됩니다. 하위 컴포넌트가 없는 컴포넌트는 리프 컴포넌트입니다. 이러한 컴포넌트 분류는 데이터 흐름 및 렌더링 성능을 이해하는 데 유용합니다.

Modelling the relationship between JavaScript modules is another useful way to understand your app. We refer to it as a module dependency tree. 자바스크립트 모듈 간의 관계를 모델링하는 것은 앱을 이해하는 또 다른 유용한 방법입니다. 이를 모듈 종속성 트리라고 합니다.

A tree graph with five nodes. Each node represents a JavaScript module. The top-most node is labelled 'RootModule.js'. It has three arrows extending to the nodes: 'ModuleA.js', 'ModuleB.js', and 'ModuleC.js'. Each arrow is labelled as 'imports'. 'ModuleC.js' node has a single 'imports' arrow that points to a node labelled 'ModuleD.js'.
A tree graph with five nodes. Each node represents a JavaScript module. The top-most node is labelled 'RootModule.js'. It has three arrows extending to the nodes: 'ModuleA.js', 'ModuleB.js', and 'ModuleC.js'. Each arrow is labelled as 'imports'. 'ModuleC.js' node has a single 'imports' arrow that points to a node labelled 'ModuleD.js'.

An example module dependency tree. 모듈 의존성 트리의 예시

A dependency tree is often used by build tools to bundle all the relevant JavaScript code for the client to download and render. A large bundle size regresses user experience for React apps. Understanding the module dependency tree is helpful to debug such issues. 종속성 트리는 클라이언트가 다운로드하고 렌더링할 모든 관련 JavaScript 코드를 묶기 위해 빌드 도구에서 자주 사용됩니다. 번들 크기가 크면 React 앱의 사용자 경험이 저하됩니다. 모듈 종속성 트리를 이해하면 이러한 문제를 디버깅하는 데 도움이 됩니다.

Ready to learn this topic?

Read Your UI as a Tree to learn how to create a render and module dependency trees for a React app and how they’re useful mental models for improving user experience and performance. React 앱을 위한 렌더 트리 및 모듈 종속성 트리를 만드는 방법과 이것이 사용자 경험과 성능을 향상시키는 데 유용한 멘탈 모델인지 알아보려면 트리로서의 UI를 읽어보세요.

Read More

What’s next?다음 단계

Head over to Your First Component to start reading this chapter page by page! 첫 번째 컴포넌트로 이동하여 이 챕터를 한 페이지씩 읽어보세요!

Or, if you’re already familiar with these topics, why not read about Adding Interactivity? 또는 이러한 주제에 이미 익숙하다면 상호작용 추가하기를 읽어보는 것은 어떨까요?