Common components (e.g. <div>)기본 컴포넌트 (예: <div>)

All built-in browser components, such as <div>, support some common props and events. <div>와 같은 모든 브라우저 빌트인 컴포넌트는 몇 가지 일반적인 props와 이벤트를 지원합니다.


Reference참조

Common components (e.g. <div>) 기본 컴포넌트 (예: <div>)

<div className="wrapper">Some content</div>

See more examples below. 아래에서 더 많은 예시를 확인하세요.

Props

These special React props are supported for all built-in components: 아래의 특별한 React props는 모든 빌트인 컴포넌트에서 지원됩니다:

  • children: A React node (an element, a string, a number, a portal, an empty node like null, undefined and booleans, or an array of other React nodes). Specifies the content inside the component. When you use JSX, you will usually specify the children prop implicitly by nesting tags like <div><span /></div>. children: React 노드(엘리먼트, 문자열, 숫자, portal, null, undefined 및 boolean과 같은 빈 노드 또는 기타 React 노드의 배열). 컴포넌트 내부의 콘텐츠를 지정합니다. JSX를 사용할 때 일반적으로 <div><span /></div>와 같은 태그를 중첩하여 암묵적으로 children prop을 지정합니다.

  • dangerouslySetInnerHTML: An object of the form { __html: '<p>some html</p>' } with a raw HTML string inside. Overrides the innerHTML property of the DOM node and displays the passed HTML inside. This should be used with extreme caution! If the HTML inside isn’t trusted (for example, if it’s based on user data), you risk introducing an XSS vulnerability. Read more about using dangerouslySetInnerHTML. dangerouslySetInnerHTML: 내부에 원시 HTML 문자열이 있는 { __html: '<p>일부 html</p>' } 형식의 객체로, 내부에 원시 HTML 문자열이 있습니다. DOM 노드의 innerHTML 속성을 재정의하고 전달된 HTML을 내부에 표시합니다. 이 함수는 매우 주의해서 사용해야 합니다! 내부 HTML을 신뢰할 수 없는 경우(예: 사용자 데이터를 기반으로 하는 경우) XSS 취약점이 발생할 위험이 있습니다. dangerouslySetInnerHTML 사용에 대해 자세히 알아보세요.

  • ref: A ref object from useRef or createRef, or a ref callback function, or a string for legacy refs. Your ref will be filled with the DOM element for this node. Read more about manipulating the DOM with Refs. ref: useRef또는createRef의 ref 객체, ref 콜백 함수, 또는 레거시 ref에 대한 문자열. ref는 이 노드의 DOM 엘리먼트로 채워집니다. ref로 DOM을 조작하는 방법에 대해 자세히 알아보세요.

  • suppressContentEditableWarning: A boolean. If true, suppresses the warning that React shows for elements that both have children and contentEditable={true} (which normally do not work together). Use this if you’re building a text input library that manages the contentEditable content manually. suppressContentEditableWarning: 불리언. true이면, 일반적으로 함께 작동하지 않는 (일반적으로 함께 작동하지 않는) childrencontentEditable={true}가 모두 있는 엘리먼트에 대해 React가 표시하는 경고를 억제합니다. 이 값을 사용하면 contentEditable 콘텐츠를 수동으로 관리하는 텍스트 입력 라이브러리를 빌드할 때 사용합니다.

  • suppressHydrationWarning: A boolean. If you use server rendering, normally there is a warning when the server and the client render different content. In some rare cases (like timestamps), it is very hard or impossible to guarantee an exact match. If you set suppressHydrationWarning to true, React will not warn you about mismatches in the attributes and the content of that element. It only works one level deep, and is intended to be used as an escape hatch. Don’t overuse it. Read about suppressing hydration errors. suppressHydrationWarning: 불리언. 서버 렌더링을 사용하는 경우 일반적으로 서버와 클라이언트가 서로 다른 콘텐츠를 렌더링할 때 경고가 표시됩니다. 타임스탬프와 같은 일부 드문 경우에서는 정확한 일치를 보장하기가 매우 어렵거나 불가능합니다. suppressHydrationWarningtrue로 설정하면 React는 해당 엘리먼트의 속성과 콘텐츠가 일치하지 않을 때 경고하지 않습니다. 이는 한 단계 깊이에서만 작동하며, 탈출구로 사용하기 위한 것입니다. 과도하게 사용하지 마세요. hydration 오류 억제에 대해 자세히 알아보세요.

  • style: An object with CSS styles, for example { fontWeight: 'bold', margin: 20 }. Similarly to the DOM style property, the CSS property names need to be written as camelCase, for example fontWeight instead of font-weight. You can pass strings or numbers as values. If you pass a number, like width: 100, React will automatically append px (“pixels”) to the value unless it’s a unitless property. We recommend using style only for dynamic styles where you don’t know the style values ahead of time. In other cases, applying plain CSS classes with className is more efficient. Read more about className and style. style: CSS 스타일이 있는 객체(예: { fontWeight: 'bold', margin: 20 }). DOM style 프로퍼티와 마찬가지로 CSS 프로퍼티 이름도font-weight 대신 fontWeight와 같이 camelCase로 작성해야 합니다. 문자열이나 숫자를 값으로 전달할 수 있습니다. width: 100과 같이 숫자를 전달하면 React는 단위가 없는 프로퍼티가 아니라면 값에 자동으로 px(“픽셀”)를 추가합니다. 스타일 값을 미리 알 수 없는 동적 스타일에만 style을 사용하는 것을 권장합니다. 그 외의 경우에는 className과 함께 일반 CSS 클래스를 적용하는 것이 더 효율적입니다. classNamestyle로 CSS를 적용하는 방법에 대해 자세히 알아보세요.

These standard DOM props are also supported for all built-in components: 아래의 표준 DOM props는 모든 빌트인 컴포넌트에서도 지원됩니다:

You can also pass custom attributes as props, for example mycustomprop="someValue". This can be useful when integrating with third-party libraries. The custom attribute name must be lowercase and must not start with on. The value will be converted to a string. If you pass null or undefined, the custom attribute will be removed. 사용자 정의 속성을 프로퍼티로 전달할 수도 있습니다(예: mycustomprop="someValue"). 이는 타사 라이브러리와 통합할 때 유용할 수 있습니다. 사용자 정의 속성 이름은 소문자여야 하며 on으로 시작하지 않아야 합니다. 값은 문자열로 변환됩니다. null 또는 undefined를 전달하면 사용자 정의 속성이 제거됩니다.

These events fire only for the <form> elements: 다음 이벤트들은 <form> 엘리먼트에 대해서만 호출됩니다:

These events fire only for the <dialog> elements. Unlike browser events, they bubble in React: 다음 이벤트들은 <dialog> 엘리먼트에 대해서만 호출됩니다. 브라우저 이벤트와 달리, React에서는 버블이 발생합니다:

These events fire only for the <details> elements. Unlike browser events, they bubble in React: 다음 이벤트들은 <details> 엘리먼트에 대해서만 호출됩니다. 브라우저 이벤트와 달리, React에서는 버블이 발생합니다:

These events fire for <img>, <iframe>, <object>, <embed>, <link>, and SVG <image> elements. Unlike browser events, they bubble in React: 다음 이벤트들은 <img>, <iframe>, <object>, <embed>, <link>, SVG <image> 엘리먼트에 대해서만 호출됩니다. 브라우저 이벤트와 달리, React에서는 버블이 발생합니다:

These events fire for resources like <audio> and <video>. Unlike browser events, they bubble in React: 다음 이벤트들은 <audio><video> 같은 리소스에 대해서만 호출됩니다. 브라우저 이벤트와 달리, React에서는 버블이 발생합니다:

Caveats주의사항

  • You cannot pass both children and dangerouslySetInnerHTML at the same time. childrendangerouslySetInnerHTML을 동시에 전달할 수 없습니다.

  • Some events (like onAbort and onLoad) don’t bubble in the browser, but bubble in React. 일부 이벤트(예: onAbortonLoad)는 브라우저에서는 버블링되지 않지만 React에서는 버블링됩니다.


ref callback function ref 콜백 함수

Instead of a ref object (like the one returned by useRef), you may pass a function to the ref attribute. ref 객체(예: useRef에서 반환하는 객체) 대신 ref 속성에 함수를 전달할 수 있습니다.

<div ref={(node) => console.log(node)} />

See an example of using the ref callback. ref 콜백 사용 예시를 확인하세요.

When the <div> DOM node is added to the screen, React will call your ref callback with the DOM node as the argument. When that <div> DOM node is removed, React will call your ref callback with null. <div> DOM 노드가 화면에 추가되면 React는 DOM node를 인수로 사용하여 ref 콜백을 호출합니다. 해당 <div> DOM 노드가 제거되면 React는 nullref 콜백을 호출합니다.

React will also call your ref callback whenever you pass a different ref callback. In the above example, (node) => { ... } is a different function on every render. When your component re-renders, the previous function will be called with null as the argument, and the next function will be called with the DOM node. React는 또한 다른 ref 콜백을 전달할 때마다 ref 콜백을 호출합니다. 위의 예에서 (node) => { ... }는 렌더링할 때마다 다른 기능입니다. 이것이 컴포넌트가 다시 렌더링될 때 null을 인자로 사용하여 previous 함수가 호출되고 DOM 노드로 next 함수가 호출되는 이유입니다.

Parameters매개변수

  • node: A DOM node or null. React will pass you the DOM node when the ref gets attached, and null when the ref gets detached. Unless you pass the same function reference for the ref callback on every render, the callback will get temporarily detached and re-attached during every re-render of the component. node: DOM 노드 또는 null. React는 ref가 연결될 때 DOM 노드를 전달하고, ref가 분리될 때 null을 전달합니다. 모든 렌더링에서 ref 콜백에 대해 동일한 함수 참조를 전달하지 않는 한, 컴포넌트를 다시 렌더링할 때마다 콜백이 일시적으로 분리되었다가 다시 연결됩니다.

Returns반환값

Do not return anything from the ref callback. ref 콜백에서 아무것도 반환하지 않습니다.


React event object React 이벤트 객체

Your event handlers will receive a React event object. It is also sometimes known as a “synthetic event”. 이벤트 핸들러는 React 이벤트 객체를 받게 되며, “합성 이벤트”라고도 합니다.

<button onClick={e => {
console.log(e); // React event object
// React 이벤트 객체
}} />

It conforms to the same standard as the underlying DOM events, but fixes some browser inconsistencies. 기본 DOM 이벤트와 동일한 표준을 준수하지만 일부 브라우저 간의 불일치를 수정합니다.

Some React events do not map directly to the browser’s native events. For example in onMouseLeave, e.nativeEvent will point to a mouseout event. The specific mapping is not part of the public API and may change in the future. If you need the underlying browser event for some reason, read it from e.nativeEvent. 일부 React 이벤트는 브라우저의 네이티브 이벤트에 직접 매핑되지 않습니다. 예를 들어, onMouseLeave에서 e.nativeEventmouseout 이벤트를 가리킵니다. 특정 매핑은 공개 API의 일부가 아니며 향후 변경될 수 있습니다. 어떤 이유로 기본 브라우저 이벤트가 필요한 경우 e.nativeEvent에서 읽어오세요.

Properties 프로퍼티

React event objects implement some of the standard Event properties: React 이벤트 객체는 표준 Event 프로퍼티 중 일부를 구현합니다:

  • bubbles: A boolean. Returns whether the event bubbles through the DOM. bubbles : 불리언. 이벤트가 DOM을 통해 버블을 발생시킬지 여부를 반환합니다.

  • cancelable: A boolean. Returns whether the event can be canceled. cancelable: 불리언. 이벤트를 취소할 수 있는지 여부를 반환합니다.

  • currentTarget: A DOM node. Returns the node to which the current handler is attached in the React tree. currentTarget: DOM 노드. React 트리에서 현재 핸들러가 연결된 노드를 반환합니다.

  • defaultPrevented: A boolean. Returns whether preventDefault was called. defaultPrevented: 불리언. preventDefault`가 호출되었는지 여부를 반환합니다.

  • eventPhase: A number. Returns which phase the event is currently in. eventPhase: 숫자. 이벤트가 현재 어떤 단계에 있는지 반환합니다.

  • isTrusted: A boolean. Returns whether the event was initiated by user. isTrusted: 불리언. 이벤트가 사용자에 의해 시작되었는지 여부를 반환합니다.

  • target: A DOM node. Returns the node on which the event has occurred (which could be a distant child). target: DOM 노드. 이벤트가 발생한 노드(먼 자식일 수 있음)를 반환합니다.

  • timeStamp: A number. Returns the time when the event occurred. timeStamp: 숫자. 이벤트가 발생한 시간을 반환합니다.

Additionally, React event objects provide these properties: 또한 React 이벤트 객체는 이러한 프로퍼티를 제공합니다:

  • nativeEvent: A DOM Event. The original browser event object. nativeEvent: DOM Event. 원본 브라우저 이벤트 객체입니다.

Methods 메서드

React event objects implement some of the standard Event methods: React 이벤트 객체는 표준 Event 메서드 중 일부를 구현합니다:

Additionally, React event objects provide these methods: 또한 React 이벤트 객체는 이러한 메서드를 제공합니다:

  • isDefaultPrevented(): Returns a boolean value indicating whether preventDefault was called. isDefaultPrevented(): preventDefault가 호출되었는지 여부를 나타내는 불리언 값을 반환합니다.

  • isPropagationStopped(): Returns a boolean value indicating whether stopPropagation was called. isPropagationStopped(): stopPropagation가 호출되었는지 여부를 나타내는 불리언 값을 반환합니다.

  • persist(): Not used with React DOM. With React Native, call this to read event’s properties after the event. persist(): React DOM에서는 사용되지 않습니다. React Native에서는 이벤트 이후 이벤트의 프로퍼티를 읽으려면 이 함수를 호출합니다.

  • isPersistent(): Not used with React DOM. With React Native, returns whether persist has been called. isPersistent(): React DOM에서는 사용되지 않습니다. React Native에서는 persist가 호출되었는지 여부를 반환합니다.

Caveats주의사항

  • The values of currentTarget, eventPhase, target, and type reflect the values your React code expects. Under the hood, React attaches event handlers at the root, but this is not reflected in React event objects. For example, e.currentTarget may not be the same as the underlying e.nativeEvent.currentTarget. For polyfilled events, e.type (React event type) may differ from e.nativeEvent.type (underlying type). currentTarget, eventPhase, target, type의 값은 React 코드가 기대하는 값을 반영합니다. 내부적으로 React는 이벤트 핸들러를 루트에 첨부하지만, 이는 React 이벤트 객체에는 반영되지 않습니다. 예를 들어, e.currentTarget은 기본 e.nativeEvent.currentTarget과 같지 않을 수 있습니다. 폴리필 이벤트의 경우, e.type(React 이벤트 타입)이 e.nativeEvent.type(기본 타입)과 다를 수 있습니다.

AnimationEvent handler function AnimationEvent 핸들러 함수

An event handler type for the CSS animation events. CSS 애니메이션 이벤트에 대한 이벤트 핸들러 유형입니다.

<div
onAnimationStart={e => console.log('onAnimationStart')}
onAnimationIteration={e => console.log('onAnimationIteration')}
onAnimationEnd={e => console.log('onAnimationEnd')}
/>

Parameters매개변수


ClipboardEvent handler function ClipboardEvent 핸들러 함수

An event handler type for the Clipboard API events. Clipboard API 이벤트에 대한 이벤트 핸들러 유형입니다.

<input
onCopy={e => console.log('onCopy')}
onCut={e => console.log('onCut')}
onPaste={e => console.log('onPaste')}
/>

Parameters매개변수


CompositionEvent handler function CompositionEvent 핸들러 함수

An event handler type for the input method editor (IME) events. input method editor (IME) 이벤트에 대한 이벤트 핸들러 유형입니다.

<input
onCompositionStart={e => console.log('onCompositionStart')}
onCompositionUpdate={e => console.log('onCompositionUpdate')}
onCompositionEnd={e => console.log('onCompositionEnd')}
/>

Parameters매개변수


DragEvent handler function DragEvent 핸들러 함수

An event handler type for the HTML Drag and Drop API events. HTML Drag and Drop API 이벤트에 대한 이벤트 핸들러 유형입니다.

<>
<div
draggable={true}
onDragStart={e => console.log('onDragStart')}
onDragEnd={e => console.log('onDragEnd')}
>
Drag source
</div>

<div
onDragEnter={e => console.log('onDragEnter')}
onDragLeave={e => console.log('onDragLeave')}
onDragOver={e => { e.preventDefault(); console.log('onDragOver'); }}
onDrop={e => console.log('onDrop')}
>
Drop target
</div>
</>

Parameters매개변수


FocusEvent handler function FocusEvent 핸들러 함수

An event handler type for the focus events. 포커스 이벤트에 대한 이벤트 핸들러 유형입니다.

<input
onFocus={e => console.log('onFocus')}
onBlur={e => console.log('onBlur')}
/>

See an example. 예시를 확인하세요.

Parameters매개변수


Event handler function Event 핸들러 함수

An event handler type for generic events. 일반 이벤트를 위한 이벤트 핸들러 유형입니다.

Parameters매개변수


InputEvent handler function InputEvent 핸들러 함수

An event handler type for the onBeforeInput event. onBeforeInput 이벤트에 대한 이벤트 핸들러 유형입니다.

<input onBeforeInput={e => console.log('onBeforeInput')} />

Parameters매개변수


KeyboardEvent handler function KeyboardEvent 핸들러 함수

An event handler type for keyboard events. 키보드 이벤트를 위한 이벤트 핸들러 유형입니다.

<input
onKeyDown={e => console.log('onKeyDown')}
onKeyUp={e => console.log('onKeyUp')}
/>

See an example. 예시를 확인하세요.

Parameters매개변수


MouseEvent handler function MouseEvent 핸들러 함수

An event handler type for mouse events. 마우스 이벤트에 대한 이벤트 핸들러 유형입니다.

<div
onClick={e => console.log('onClick')}
onMouseEnter={e => console.log('onMouseEnter')}
onMouseOver={e => console.log('onMouseOver')}
onMouseDown={e => console.log('onMouseDown')}
onMouseUp={e => console.log('onMouseUp')}
onMouseLeave={e => console.log('onMouseLeave')}
/>

See an example. 예시를 확인하세요.

Parameters매개변수


PointerEvent handler function PointerEvent 핸들러 함수

An event handler type for pointer events. 포인터 이벤트에 대한 이벤트 핸들러 유형입니다.

<div
onPointerEnter={e => console.log('onPointerEnter')}
onPointerMove={e => console.log('onPointerMove')}
onPointerDown={e => console.log('onPointerDown')}
onPointerUp={e => console.log('onPointerUp')}
onPointerLeave={e => console.log('onPointerLeave')}
/>

See an example. 예시를 확인하세요.

Parameters매개변수


TouchEvent handler function TouchEvent 핸들러 함수

An event handler type for touch events. 터치 이벤트에 대한 이벤트 핸들러 유형입니다.

<div
onTouchStart={e => console.log('onTouchStart')}
onTouchMove={e => console.log('onTouchMove')}
onTouchEnd={e => console.log('onTouchEnd')}
onTouchCancel={e => console.log('onTouchCancel')}
/>

Parameters매개변수


TransitionEvent handler function TransitionEvent 핸들러 함수

An event handler type for the CSS transition events. CSS 트랜지션 이벤트에 대한 이벤트 핸들러 유형입니다.

<div
onTransitionEnd={e => console.log('onTransitionEnd')}
/>

Parameters매개변수


UIEvent handler function UIEvent 핸들러 함수

An event handler type for generic UI events. 일반 UI 이벤트를 위한 이벤트 핸들러 유형입니다.

<div
onScroll={e => console.log('onScroll')}
/>

Parameters매개변수


WheelEvent handler function WheelEvent 핸들러 함수

An event handler type for the onWheel event. onWheel 이벤트에 대한 이벤트 핸들러 유형입니다.

<div
onWheel={e => console.log('onWheel')}
/>

Parameters매개변수


Usage사용법

Applying CSS styles CSS 스타일 적용하기

In React, you specify a CSS class with className. It works like the class attribute in HTML: React에서는 className으로 CSS 클래스를 지정합니다. HTML의 class 속성처럼 작동합니다:

<img className="avatar" />

Then you write the CSS rules for it in a separate CSS file: 그런 다음 별도의 CSS 파일에 해당 CSS 규칙을 작성합니다:

/* In your CSS */
.avatar {
border-radius: 50%;
}

React does not prescribe how you add CSS files. In the simplest case, you’ll add a <link> tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project. React는 CSS 파일을 추가하는 방법을 규정하지 않습니다. 가장 간단한 경우 HTML에 <link> 태그를 추가하면 됩니다. 빌드 도구나 프레임워크를 사용하는 경우 해당 문서를 참조하여 프로젝트에 CSS 파일을 추가하는 방법을 알아보세요.

Sometimes, the style values depend on data. Use the style attribute to pass some styles dynamically: 때때로 스타일 값은 데이터에 따라 달라집니다. style 속성을 사용하여 일부 스타일을 동적으로 전달할 수 있습니다:

<img
className="avatar"
style={{
width: user.imageSize,
height: user.imageSize
}}
/>

In the above example, style={{}} is not a special syntax, but a regular {} object inside the style={ } JSX curly braces. We recommend only using the style attribute when your styles depend on JavaScript variables. 위 예시에서 style={{}}은 특별한 구문이 아니라 style={ } JSX 중괄호 안에 있는 일반 {} 객체입니다. 스타일이 JavaScript 변수에 의존하는 경우에만 style 속성을 사용하는 것이 좋습니다.

export default function Avatar({ user }) {
  return (
    <img
      src={user.imageUrl}
      alt={'Photo of ' + user.name}
      className="avatar"
      style={{
        width: user.imageSize,
        height: user.imageSize
      }}
    />
  );
}

Deep Dive | 심층 탐구

How to apply multiple CSS classes conditionally? 여러 CSS 클래스를 조건부로 적용하는 방법은 무엇인가요?

To apply CSS classes conditionally, you need to produce the className string yourself using JavaScript. 조건부로 CSS 클래스를 적용하려면 JavaScript를 사용하여 className 문자열을 직접 생성해야 합니다.

For example, className={'row ' + (isSelected ? 'selected': '')} will produce either className="row" or className="row selected" depending on whether isSelected is true. 예를 들어, className={'row ' + (isSelected ? 'selected': '')}isSelectedtrue인지 여부에 따라 className="row" 또는 className="row selected"를 생성합니다.

To make this more readable, you can use a tiny helper library like classnames: 이를 더 읽기 쉽게 만들려면 classnames와 같은 작은 헬퍼 라이브러리를 사용할 수 있습니다:

import cn from 'classnames';

function Row({ isSelected }) {
return (
<div className={cn('row', isSelected && 'selected')}>
...
</div>
);
}

It is especially convenient if you have multiple conditional classes: 조건부 클래스가 여러 개 있는 경우 특히 편리합니다:

import cn from 'classnames';

function Row({ isSelected, size }) {
return (
<div className={cn('row', {
selected: isSelected,
large: size === 'large',
small: size === 'small',
})}>
...
</div>
);
}

Manipulating a DOM node with a ref ref로 DOM 노드 조작하기

Sometimes, you’ll need to get the browser DOM node associated with a tag in JSX. For example, if you want to focus an <input> when a button is clicked, you need to call focus() on the browser <input> DOM node. 때로는 JSX에서 태그와 연결된 브라우저 DOM 노드를 가져와야 할 수도 있습니다. 예를 들어, 버튼이 클릭될 때 <input>에 초점을 맞추려면 브라우저 <input> DOM 노드에서 focus()를 호출해야 합니다.

To obtain the browser DOM node for a tag, declare a ref and pass it as the ref attribute to that tag: 태그에 대한 브라우저 DOM 노드를 가져오려면 ref 선언하기를 통해 해당 태그에 ref 속성으로 전달합니다:

import { useRef } from 'react';

export default function Form() {
const inputRef = useRef(null);
// ...
return (
<input ref={inputRef} />
// ...

React will put the DOM node into inputRef.current after it’s been rendered to the screen. React는 DOM 노드가 화면에 렌더링된 후 inputRef.current에 넣습니다.

import { useRef } from 'react';

export default function Form() {
  const inputRef = useRef(null);

  function handleClick() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleClick}>
        Focus the input
      </button>
    </>
  );
}

Read more about manipulating DOM with refs and check out more examples. ref로 DOM 조작하기더 많은 예시를 확인해보세요.

For more advanced use cases, the ref attribute also accepts a callback function. 고급 사용 사례의 경우, ref 속성은 콜백 함수도 허용합니다.


Dangerously setting the inner HTML 내부 HTML을 위험하게 설정하는 경우

You can pass a raw HTML string to an element like so: 다음과 같이 원본 HTML 문자열을 요소에 전달할 수 있습니다:

const markup = { __html: '<p>some raw html</p>' };
return <div dangerouslySetInnerHTML={markup} />;

This is dangerous. As with the underlying DOM innerHTML property, you must exercise extreme caution! Unless the markup is coming from a completely trusted source, it is trivial to introduce an XSS vulnerability this way. 이렇게 작성하는 것은 위험합니다. 기본 DOM innerHTML 속성과 마찬가지로 극도의 주의를 기울여야 합니다! 마크업이 완전히 신뢰할 수 있는 출처에서 제공되지 않는 한, 이런 식으로 XSS 취약점을 도입하는 것은 위험한 일입니다.

For example, if you use a Markdown library that converts Markdown to HTML, you trust that its parser doesn’t contain bugs, and the user only sees their own input, you can display the resulting HTML like this: 예를 들어, 마크다운을 HTML로 변환하는 마크다운 라이브러리를 사용하는 경우 해당 파서에 버그가 없고 사용자가 자신의 입력만 볼 수 있다고 믿는다면 다음과 같이 결과 HTML을 표시할 수 있습니다:

import { Remarkable } from 'remarkable';

const md = new Remarkable();

function renderMarkdownToHTML(markdown) {
  // This is ONLY safe because the output HTML
  // is shown to the same user, and because you
  // trust this Markdown parser to not have bugs.
  const renderedHTML = md.render(markdown);
  return {__html: renderedHTML};
}

export default function MarkdownPreview({ markdown }) {
  const markup = renderMarkdownToHTML(markdown);
  return <div dangerouslySetInnerHTML={markup} />;
}

The {__html} object should be created as close to where the HTML is generated as possible, like the above example does in the renderMarkdownToHTML function. This ensures that all raw HTML being used in your code is explicitly marked as such, and that only variables that you expect to contain HTML are passed to dangerouslySetInnerHTML. It is not recommended to create the object inline like <div dangerouslySetInnerHTML={{__html: markup}} />.

To see why rendering arbitrary HTML is dangerous, replace the code above with this: 임의의 HTML을 렌더링하는 것이 왜 위험한지 알아보려면 위의 코드를 다음과 같이 바꾸세요:

const post = {
// Imagine this content is stored in the database.
// 이 콘텐츠가 데이터베이스에 저장되어 있다고 가정해 보겠습니다.
content: `<img src="" onerror='alert("you were hacked")'>`
};

export default function MarkdownPreview() {
// 🔴 SECURITY HOLE: passing untrusted input to dangerouslySetInnerHTML
// 🔴 보안 허점: 신뢰할 수 없는 input을 위험하게 dangerouslySetInnerHTML로 전달합니다.
const markup = { __html: post.content };
return <div dangerouslySetInnerHTML={markup} />;
}

The code embedded in the HTML will run. A hacker could use this security hole to steal user information or to perform actions on their behalf. Only use dangerouslySetInnerHTML with trusted and sanitized data. HTML에 포함된 코드가 실행됩니다. 해커는 이 보안 허점을 이용해 사용자 정보를 훔치거나 사용자 대신 작업을 수행할 수 있습니다. 신뢰할 수 있는 위생 처리된 데이터에 대해서만 dangerouslySetInnerHTML를 사용하세요.


Handling mouse events 마우스 이벤트 처리하기

This example shows some common mouse events and when they fire. 이 예시는 몇 가지 일반적인 마우스 이벤트와 이벤트 발생 시점을 보여줍니다.

export default function MouseExample() {
  return (
    <div
      onMouseEnter={e => console.log('onMouseEnter (parent)')}
      onMouseLeave={e => console.log('onMouseLeave (parent)')}
    >
      <button
        onClick={e => console.log('onClick (first button)')}
        onMouseDown={e => console.log('onMouseDown (first button)')}
        onMouseEnter={e => console.log('onMouseEnter (first button)')}
        onMouseLeave={e => console.log('onMouseLeave (first button)')}
        onMouseOver={e => console.log('onMouseOver (first button)')}
        onMouseUp={e => console.log('onMouseUp (first button)')}
      >
        First button
      </button>
      <button
        onClick={e => console.log('onClick (second button)')}
        onMouseDown={e => console.log('onMouseDown (second button)')}
        onMouseEnter={e => console.log('onMouseEnter (second button)')}
        onMouseLeave={e => console.log('onMouseLeave (second button)')}
        onMouseOver={e => console.log('onMouseOver (second button)')}
        onMouseUp={e => console.log('onMouseUp (second button)')}
      >
        Second button
      </button>
    </div>
  );
}


Handling pointer events 포인터 이벤트 처리하기

This example shows some common pointer events and when they fire. 이 예시는 몇 가지 일반적인 포인터 이벤트와 이벤트 발생 시점을 보여줍니다.

export default function PointerExample() {
  return (
    <div
      onPointerEnter={e => console.log('onPointerEnter (parent)')}
      onPointerLeave={e => console.log('onPointerLeave (parent)')}
      style={{ padding: 20, backgroundColor: '#ddd' }}
    >
      <div
        onPointerDown={e => console.log('onPointerDown (first child)')}
        onPointerEnter={e => console.log('onPointerEnter (first child)')}
        onPointerLeave={e => console.log('onPointerLeave (first child)')}
        onPointerMove={e => console.log('onPointerMove (first child)')}
        onPointerUp={e => console.log('onPointerUp (first child)')}
        style={{ padding: 20, backgroundColor: 'lightyellow' }}
      >
        First child
      </div>
      <div
        onPointerDown={e => console.log('onPointerDown (second child)')}
        onPointerEnter={e => console.log('onPointerEnter (second child)')}
        onPointerLeave={e => console.log('onPointerLeave (second child)')}
        onPointerMove={e => console.log('onPointerMove (second child)')}
        onPointerUp={e => console.log('onPointerUp (second child)')}
        style={{ padding: 20, backgroundColor: 'lightblue' }}
      >
        Second child
      </div>
    </div>
  );
}


Handling focus events 포커스 이벤트 처리하기

In React, focus events bubble. You can use the currentTarget and relatedTarget to differentiate if the focusing or blurring events originated from outside of the parent element. The example shows how to detect focusing a child, focusing the parent element, and how to detect focus entering or leaving the whole subtree. React에는 포커스 이벤트 버블이 있습니다. currentTargetrelatedTarget을 사용하여 포커스나 블러 이벤트가 부모 엘리먼트 외부에서 발생했는지 구분할 수 있습니다. 이 예는 자식 요소 포커싱, 부모 요소 포커싱, 전체 하위 트리에 들어오고 나가는 포커스를 감지하는 방법을 보여줍니다.

export default function FocusExample() {
  return (
    <div
      tabIndex={1}
      onFocus={(e) => {
        if (e.currentTarget === e.target) {
          console.log('focused parent');
        } else {
          console.log('focused child', e.target.name);
        }
        if (!e.currentTarget.contains(e.relatedTarget)) {
          // Not triggered when swapping focus between children
          // 자식 간에 포커스를 바꿀 때는 트리거되지 않습니다.
          console.log('focus entered parent');
        }
      }}
      onBlur={(e) => {
        if (e.currentTarget === e.target) {
          console.log('unfocused parent');
        } else {
          console.log('unfocused child', e.target.name);
        }
        if (!e.currentTarget.contains(e.relatedTarget)) {
          // Not triggered when swapping focus between children
          // 자식 간에 포커스를 바꿀 때는 트리거되지 않습니다.
          console.log('focus left parent');
        }
      }}
    >
      <label>
        First name:
        <input name="firstName" />
      </label>
      <label>
        Last name:
        <input name="lastName" />
      </label>
    </div>
  );
}


Handling keyboard events 키보드 이벤트 처리하기

This example shows some common keyboard events and when they fire. 이 예는 몇 가지 일반적인 키보드 이벤트와 이벤트 발생 시점을 보여줍니다.

export default function KeyboardExample() {
  return (
    <label>
      First name:
      <input
        name="firstName"
        onKeyDown={e => console.log('onKeyDown:', e.key, e.code)}
        onKeyUp={e => console.log('onKeyUp:', e.key, e.code)}
      />
    </label>
  );
}