0% found this document useful (0 votes)
11 views38 pages

Common Components (E.g. - Div - ) - React

The document provides a comprehensive reference for common components in React, specifically focusing on built-in browser components like <div>. It details the supported props, events, and usage examples, including handling various types of events such as mouse, keyboard, and touch events. Additionally, it emphasizes the importance of certain props like 'dangerouslySetInnerHTML' and 'ref' for manipulating DOM elements safely.

Uploaded by

dungeon.dad87
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views38 pages

Common Components (E.g. - Div - ) - React

The document provides a comprehensive reference for common components in React, specifically focusing on built-in browser components like <div>. It details the supported props, events, and usage examples, including handling various types of events such as mouse, keyboard, and touch events. Additionally, it emphasizes the importance of certain props like 'dangerouslySetInnerHTML' and 'ref' for manipulating DOM elements safely.

Uploaded by

dungeon.dad87
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

20/02/2025, 10:01 Common components (e.g.

<div>) – React

v19

API REFERENCE COMPONENTS

Common components (e.g.


<div>)
All built-in browser components, such as <div> , support some
common props and events.

Reference

Common components (e.g. <div> )


ref callback function

React event object


AnimationEvent handler function

ClipboardEvent handler function

CompositionEvent handler function

DragEvent handler function

FocusEvent handler function

Event handler function

InputEvent handler function

KeyboardEvent handler function

MouseEvent handler function

PointerEvent handler function

TouchEvent handler function

TransitionEvent handler function

UIEvent handler function

WheelEvent handler function

Usage

Applying CSS styles


Manipulating a DOM node with a ref
Dangerously setting the inner HTML

[Link] 1/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

Handling mouse events


Handling pointer events
Handling focus events
Handling keyboard events

Reference

Common components (e.g. <div> )

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

See more examples below.

Props

These special React props are supported for all built-in components:

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> .

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 .

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.

suppressContentEditableWarning : A boolean. If true , suppresses the


warning that React shows for elements that both have children and

[Link] 2/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

contentEditable={true} (which normally do not work together). Use this


if you’re building a text input library that manages the contentEditable
content manually.

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.

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 .

These standard DOM props are also supported for all built-in components:

accessKey : A string. Specifies a keyboard shortcut for the element. Not


generally recommended.
aria-* : ARIA attributes let you specify the accessibility tree information
for this element. See ARIA attributes for a complete reference. In React,
all ARIA attribute names are exactly the same as in HTML.
autoCapitalize : A string. Specifies whether and how the user input
should be capitalized.
className : A string. Specifies the element’s CSS class name. Read more
about applying CSS styles.
contentEditable : A boolean. If true , the browser lets the user edit the
rendered element directly. This is used to implement rich text input
libraries like Lexical. React warns if you try to pass React children to an

[Link] 3/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

element with contentEditable={true} because React will not be able to


update its content after user edits.
data-* : Data attributes let you attach some string data to the element,
for example data-fruit="banana" . In React, they are not commonly used
because you would usually read data from props or state instead.
dir : Either 'ltr' or 'rtl' . Specifies the text direction of the element.

draggable : A boolean. Specifies whether the element is draggable. Part


of HTML Drag and Drop API.
enterKeyHint : A string. Specifies which action to present for the enter
key on virtual keyboards.
htmlFor : A string. For <label> and <output> , lets you associate the
label with some control. Same as for HTML attribute. React uses the
standard DOM property names ( htmlFor ) instead of HTML attribute
names.
hidden : A boolean or a string. Specifies whether the element should be
hidden.
id : A string. Specifies a unique identifier for this element, which can be
used to find it later or connect it with other elements. Generate it with
useId to avoid clashes between multiple instances of the same
component.
is : A string. If specified, the component will behave like a custom
element.
inputMode : A string. Specifies what kind of keyboard to display (for
example, text, number or telephone).
itemProp : A string. Specifies which property the element represents for
structured data crawlers.
lang : A string. Specifies the language of the element.

onAnimationEnd : An AnimationEvent handler function. Fires when a CSS


animation completes.
onAnimationEndCapture : A version of onAnimationEnd that fires in the
capture phase.
onAnimationIteration : An AnimationEvent handler function. Fires when
an iteration of a CSS animation ends, and another one begins.
onAnimationIterationCapture : A version of onAnimationIteration that
fires in the capture phase.

[Link] 4/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onAnimationStart : An AnimationEvent handler function. Fires when a


CSS animation starts.
onAnimationStartCapture : onAnimationStart , but fires in the capture
phase.
onAuxClick : A MouseEvent handler function. Fires when a non-primary
pointer button was clicked.
onAuxClickCapture : A version of onAuxClick that fires in the capture
phase.
onBeforeInput : An InputEvent handler function. Fires before the value
of an editable element is modified. React does not yet use the native
beforeinput event, and instead attempts to polyfill it using other events.

onBeforeInputCapture : A version of onBeforeInput that fires in the


capture phase.
onBlur : A FocusEvent handler function. Fires when an element lost
focus. Unlike the built-in browser blur event, in React the onBlur event
bubbles.
onBlurCapture : A version of onBlur that fires in the capture phase.

onClick : A MouseEvent handler function. Fires when the primary button


was clicked on the pointing device.
onClickCapture : A version of onClick that fires in the capture phase.

onCompositionStart : A CompositionEvent handler function. Fires when


an input method editor starts a new composition session.
onCompositionStartCapture : A version of onCompositionStart that fires
in the capture phase.
onCompositionEnd : A CompositionEvent handler function. Fires when an
input method editor completes or cancels a composition session.
onCompositionEndCapture : A version of onCompositionEnd that fires in
the capture phase.
onCompositionUpdate : A CompositionEvent handler function. Fires when
an input method editor receives a new character.
onCompositionUpdateCapture : A version of onCompositionUpdate that
fires in the capture phase.
onContextMenu : A MouseEvent handler function. Fires when the user tries
to open a context menu.

[Link] 5/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onContextMenuCapture : A version of onContextMenu that fires in the


capture phase.
onCopy : A ClipboardEvent handler function. Fires when the user tries to
copy something into the clipboard.
onCopyCapture : A version of onCopy that fires in the capture phase.

onCut : A ClipboardEvent handler function. Fires when the user tries to


cut something into the clipboard.
onCutCapture : A version of onCut that fires in the capture phase.

onDoubleClick : A MouseEvent handler function. Fires when the user


clicks twice. Corresponds to the browser dblclick event.
onDoubleClickCapture : A version of onDoubleClick that fires in the
capture phase.
onDrag : A DragEvent handler function. Fires while the user is dragging
something.
onDragCapture : A version of onDrag that fires in the capture phase.

onDragEnd : A DragEvent handler function. Fires when the user stops


dragging something.
onDragEndCapture : A version of onDragEnd that fires in the capture
phase.
onDragEnter : A DragEvent handler function. Fires when the dragged
content enters a valid drop target.
onDragEnterCapture : A version of onDragEnter that fires in the capture
phase.
onDragOver : A DragEvent handler function. Fires on a valid drop target
while the dragged content is dragged over it. You must call
[Link]() here to allow dropping.

onDragOverCapture : A version of onDragOver that fires in the capture


phase.
onDragStart : A DragEvent handler function. Fires when the user starts
dragging an element.
onDragStartCapture : A version of onDragStart that fires in the capture
phase.
onDrop : A DragEvent handler function. Fires when something is dropped
on a valid drop target.
onDropCapture : A version of onDrop that fires in the capture phase.

[Link] 6/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onFocus : A FocusEvent handler function. Fires when an element receives


focus. Unlike the built-in browser focus event, in React the onFocus
event bubbles.
onFocusCapture : A version of onFocus that fires in the capture phase.

onGotPointerCapture : A PointerEvent handler function. Fires when an


element programmatically captures a pointer.
onGotPointerCaptureCapture : A version of onGotPointerCapture that
fires in the capture phase.
onKeyDown : A KeyboardEvent handler function. Fires when a key is
pressed.
onKeyDownCapture : A version of onKeyDown that fires in the capture
phase.
onKeyPress : A KeyboardEvent handler function. Deprecated. Use
onKeyDown or onBeforeInput instead.

onKeyPressCapture : A version of onKeyPress that fires in the capture


phase.
onKeyUp : A KeyboardEvent handler function. Fires when a key is released.

onKeyUpCapture : A version of onKeyUp that fires in the capture phase.

onLostPointerCapture : A PointerEvent handler function. Fires when an


element stops capturing a pointer.
onLostPointerCaptureCapture : A version of onLostPointerCapture that
fires in the capture phase.
onMouseDown : A MouseEvent handler function. Fires when the pointer is
pressed down.
onMouseDownCapture : A version of onMouseDown that fires in the capture
phase.
onMouseEnter : A MouseEvent handler function. Fires when the pointer
moves inside an element. Does not have a capture phase. Instead,
onMouseLeave and onMouseEnter propagate from the element being left
to the one being entered.
onMouseLeave : A MouseEvent handler function. Fires when the pointer
moves outside an element. Does not have a capture phase. Instead,
onMouseLeave and onMouseEnter propagate from the element being left
to the one being entered.

[Link] 7/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onMouseMove : A MouseEvent handler function. Fires when the pointer


changes coordinates.
onMouseMoveCapture : A version of onMouseMove that fires in the capture
phase.
onMouseOut : A MouseEvent handler function. Fires when the pointer
moves outside an element, or if it moves into a child element.
onMouseOutCapture : A version of onMouseOut that fires in the capture
phase.
onMouseUp : A MouseEvent handler function. Fires when the pointer is
released.
onMouseUpCapture : A version of onMouseUp that fires in the capture
phase.
onPointerCancel : A PointerEvent handler function. Fires when the
browser cancels a pointer interaction.
onPointerCancelCapture : A version of onPointerCancel that fires in the
capture phase.
onPointerDown : A PointerEvent handler function. Fires when a pointer
becomes active.
onPointerDownCapture : A version of onPointerDown that fires in the
capture phase.
onPointerEnter : A PointerEvent handler function. Fires when a pointer
moves inside an element. Does not have a capture phase. Instead,
onPointerLeave and onPointerEnter propagate from the element being
left to the one being entered.
onPointerLeave : A PointerEvent handler function. Fires when a pointer
moves outside an element. Does not have a capture phase. Instead,
onPointerLeave and onPointerEnter propagate from the element being
left to the one being entered.
onPointerMove : A PointerEvent handler function. Fires when a pointer
changes coordinates.
onPointerMoveCapture : A version of onPointerMove that fires in the
capture phase.
onPointerOut : A PointerEvent handler function. Fires when a pointer
moves outside an element, if the pointer interaction is cancelled, and a
few other reasons.

[Link] 8/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onPointerOutCapture : A version of onPointerOut that fires in the


capture phase.
onPointerUp : A PointerEvent handler function. Fires when a pointer is
no longer active.
onPointerUpCapture : A version of onPointerUp that fires in the capture
phase.
onPaste : A ClipboardEvent handler function. Fires when the user tries to
paste something from the clipboard.
onPasteCapture : A version of onPaste that fires in the capture phase.

onScroll : An Event handler function. Fires when an element has been


scrolled. This event does not bubble.
onScrollCapture : A version of onScroll that fires in the capture phase.

onSelect : An Event handler function. Fires after the selection inside an


editable element like an input changes. React extends the onSelect
event to work for contentEditable={true} elements as well. In addition,
React extends it to fire for empty selection and on edits (which may affect
the selection).
onSelectCapture : A version of onSelect that fires in the capture phase.

onTouchCancel : A TouchEvent handler function. Fires when the browser


cancels a touch interaction.
onTouchCancelCapture : A version of onTouchCancel that fires in the
capture phase.
onTouchEnd : A TouchEvent handler function. Fires when one or more
touch points are removed.
onTouchEndCapture : A version of onTouchEnd that fires in the capture
phase.
onTouchMove : A TouchEvent handler function. Fires one or more touch
points are moved.
onTouchMoveCapture : A version of onTouchMove that fires in the capture
phase.
onTouchStart : A TouchEvent handler function. Fires when one or more
touch points are placed.
onTouchStartCapture : A version of onTouchStart that fires in the
capture phase.

[Link] 9/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onTransitionEnd : A TransitionEvent handler function. Fires when a


CSS transition completes.
onTransitionEndCapture : A version of onTransitionEnd that fires in the
capture phase.
onWheel : A WheelEvent handler function. Fires when the user rotates a
wheel button.
onWheelCapture : A version of onWheel that fires in the capture phase.

role : A string. Specifies the element role explicitly for assistive


technologies.
slot : A string. Specifies the slot name when using shadow DOM. In
React, an equivalent pattern is typically achieved by passing JSX as props,
for example <Layout left={<Sidebar />} right={<Content />} /> .
spellCheck : A boolean or null. If explicitly set to true or false , enables
or disables spellchecking.
tabIndex : A number. Overrides the default Tab button behavior. Avoid
using values other than -1 and 0 .
title : A string. Specifies the tooltip text for the element.

translate : Either 'yes' or 'no' . Passing 'no' excludes the element


content from being translated.

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.

These events fire only for the <form> elements:

onReset : An Event handler function. Fires when a form gets reset.

onResetCapture : A version of onReset that fires in the capture phase.

onSubmit : An Event handler function. Fires when a form gets submitted.

onSubmitCapture : A version of onSubmit that fires in the capture phase.

These events fire only for the <dialog> elements. Unlike browser events,
they bubble in React:

[Link] 10/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onCancel : An Event handler function. Fires when the user tries to


dismiss the dialog.
onCancelCapture : A version of onCancel that fires in the capture phase.

onClose : An Event handler function. Fires when a dialog has been closed.

onCloseCapture : A version of onClose that fires in the capture phase.

These events fire only for the <details> elements. Unlike browser events,
they bubble in React:

onToggle : An Event handler function. Fires when the user toggles the
details.
onToggleCapture : A version of onToggle that fires in the capture phase.

These events fire for <img> , <iframe> , <object> , <embed> , <link> , and
SVG <image> elements. Unlike browser events, they bubble in React:

onLoad : An Event handler function. Fires when the resource has loaded.

onLoadCapture : A version of onLoad that fires in the capture phase.

onError : An Event handler function. Fires when the resource could not
be loaded.
onErrorCapture : A version of onError that fires in the capture phase.

These events fire for resources like <audio> and <video> . Unlike browser
events, they bubble in React:

onAbort : An Event handler function. Fires when the resource has not
fully loaded, but not due to an error.
onAbortCapture : A version of onAbort that fires in the capture phase.

onCanPlay : An Event handler function. Fires when there’s enough data


to start playing, but not enough to play to the end without buffering.
onCanPlayCapture : A version of onCanPlay that fires in the capture
phase.
onCanPlayThrough : An Event handler function. Fires when there’s
enough data that it’s likely possible to start playing without buffering until
the end.
onCanPlayThroughCapture : A version of onCanPlayThrough that fires in
the capture phase.

[Link] 11/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onDurationChange : An Event handler function. Fires when the media


duration has updated.
onDurationChangeCapture : A version of onDurationChange that fires in
the capture phase.
onEmptied : An Event handler function. Fires when the media has
become empty.
onEmptiedCapture : A version of onEmptied that fires in the capture
phase.
onEncrypted : An Event handler function. Fires when the browser
encounters encrypted media.
onEncryptedCapture : A version of onEncrypted that fires in the capture
phase.
onEnded : An Event handler function. Fires when the playback stops
because there’s nothing left to play.
onEndedCapture : A version of onEnded that fires in the capture phase.

onError : An Event handler function. Fires when the resource could not
be loaded.
onErrorCapture : A version of onError that fires in the capture phase.

onLoadedData : An Event handler function. Fires when the current


playback frame has loaded.
onLoadedDataCapture : A version of onLoadedData that fires in the
capture phase.
onLoadedMetadata : An Event handler function. Fires when metadata has
loaded.
onLoadedMetadataCapture : A version of onLoadedMetadata that fires in
the capture phase.
onLoadStart : An Event handler function. Fires when the browser started
loading the resource.
onLoadStartCapture : A version of onLoadStart that fires in the capture
phase.
onPause : An Event handler function. Fires when the media was paused.

onPauseCapture : A version of onPause that fires in the capture phase.

onPlay : An Event handler function. Fires when the media is no longer


paused.
onPlayCapture : A version of onPlay that fires in the capture phase.
[Link] 12/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onPlaying : An Event handler function. Fires when the media starts or


restarts playing.
onPlayingCapture : A version of onPlaying that fires in the capture
phase.
onProgress : An Event handler function. Fires periodically while the
resource is loading.
onProgressCapture : A version of onProgress that fires in the capture
phase.
onRateChange : An Event handler function. Fires when playback rate
changes.
onRateChangeCapture : A version of onRateChange that fires in the
capture phase.
onResize : An Event handler function. Fires when video changes size.

onResizeCapture : A version of onResize that fires in the capture phase.

onSeeked : An Event handler function. Fires when a seek operation


completes.
onSeekedCapture : A version of onSeeked that fires in the capture phase.

onSeeking : An Event handler function. Fires when a seek operation


starts.
onSeekingCapture : A version of onSeeking that fires in the capture
phase.
onStalled : An Event handler function. Fires when the browser is waiting
for data but it keeps not loading.
onStalledCapture : A version of onStalled that fires in the capture
phase.
onSuspend : An Event handler function. Fires when loading the resource
was suspended.
onSuspendCapture : A version of onSuspend that fires in the capture
phase.
onTimeUpdate : An Event handler function. Fires when the current
playback time updates.
onTimeUpdateCapture : A version of onTimeUpdate that fires in the
capture phase.
onVolumeChange : An Event handler function. Fires when the volume has
changed.
[Link] 13/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onVolumeChangeCapture : A version of onVolumeChange that fires in the


capture phase.
onWaiting : An Event handler function. Fires when the playback stopped
due to temporary lack of data.
onWaitingCapture : A version of onWaiting that fires in the capture
phase.

Caveats

You cannot pass both children and dangerouslySetInnerHTML at the


same time.
Some events (like onAbort and onLoad ) don’t bubble in the browser, but
bubble in React.

ref callback function

Instead of a ref object (like the one returned by useRef ), you may pass a
function to the ref attribute.

<div ref={(node) => {


[Link]('Attached', node);

return () => {
[Link]('Clean up', node)
}
}}>

See an example of using the ref callback.

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 the cleanup function returned from the
callback.

React will also call your ref callback whenever you pass a different ref
callback. In the above example, (node) => { ... } is a different function on
[Link] 14/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

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.

Parameters

node : A DOM node. React will pass you the DOM node when the ref gets
attached. Unless you pass the same function reference for the ref
callback on every render, the callback will get temporarily cleanup and re-
create during every re-render of the component.

Note

React 19 added cleanup functions for ref callbacks.

To support backwards compatibility, if a cleanup function is not


returned from the ref callback, node will be called with null when
the ref is detached. This behavior will be removed in a future
version.

Returns

optional cleanup function : When the ref is detached, React will call the
cleanup function. If a function is not returned by the ref callback, React
will call the callback again with null as the argument when the ref gets
detached. This behavior will be removed in a future version.

Caveats

When Strict Mode is on, React will run one extra development-only
setup+cleanup cycle before the first real setup. This is a stress-test that
ensures that your cleanup logic “mirrors” your setup logic and that it stops
or undoes whatever the setup is doing. If this causes a problem,
implement the cleanup function.

[Link] 15/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

When you pass a different ref callback, React will call the previous
callback’s cleanup function if provided. If no cleanup function is defined,
the ref callback will be called with null as the argument. The next
function will be called with the DOM node.

React event object

Your event handlers will receive a React event object. It is also sometimes
known as a “synthetic event”.

<button onClick={e => {


[Link](e); // React event object
}} />

It conforms to the same standard as the underlying DOM events, but fixes
some browser inconsistencies.

Some React events do not map directly to the browser’s native events. For
example in onMouseLeave , [Link] 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 [Link] .

Properties

React event objects implement some of the standard Event properties:

bubbles : A boolean. Returns whether the event bubbles through the


DOM.
cancelable : A boolean. Returns whether the event can be canceled.

currentTarget : A DOM node. Returns the node to which the current


handler is attached in the React tree.
defaultPrevented : A boolean. Returns whether preventDefault was
called.
eventPhase : A number. Returns which phase the event is currently in.

[Link] 16/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

isTrusted : A boolean. Returns whether the event was initiated by user.

target : A DOM node. Returns the node on which the event has occurred
(which could be a distant child).
timeStamp : A number. Returns the time when the event occurred.

Additionally, React event objects provide these properties:

nativeEvent : A DOM Event . The original browser event object.

Methods

React event objects implement some of the standard Event methods:

preventDefault() : Prevents the default browser action for the event.

stopPropagation() : Stops the event propagation through the React tree.

Additionally, React event objects provide these methods:

isDefaultPrevented() : Returns a boolean value indicating whether


preventDefault was called.

isPropagationStopped() : Returns a boolean value indicating whether


stopPropagation was called.

persist() : Not used with React DOM. With React Native, call this to read
event’s properties after the event.
isPersistent() : Not used with React DOM. With React Native, returns
whether persist has been called.

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, [Link] may not be the same as the underlying
[Link] . For polyfilled events, [Link] (React
event type) may differ from [Link] (underlying type).

AnimationEvent handler function

[Link] 17/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

An event handler type for the CSS animation events.

<div
onAnimationStart={e => [Link]('onAnimationStart')}
onAnimationIteration={e => [Link]('onAnimationIteration')}
onAnimationEnd={e => [Link]('onAnimationEnd')}
/>

Parameters

e : A React event object with these extra AnimationEvent properties:

animationName

elapsedTime

pseudoElement

ClipboardEvent handler function

An event handler type for the Clipboard API events.

<input
onCopy={e => [Link]('onCopy')}
onCut={e => [Link]('onCut')}
onPaste={e => [Link]('onPaste')}
/>

Parameters

e : A React event object with these extra ClipboardEvent properties:

clipboardData

CompositionEvent handler function

[Link] 18/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

An event handler type for the input method editor (IME) events.

<input
onCompositionStart={e => [Link]('onCompositionStart')}
onCompositionUpdate={e => [Link]('onCompositionUpdate')}
onCompositionEnd={e => [Link]('onCompositionEnd')}
/>

Parameters

e : A React event object with these extra CompositionEvent properties:

data

DragEvent handler function

An event handler type for the HTML Drag and Drop API events.

<>
<div
draggable={true}
onDragStart={e => [Link]('onDragStart')}
onDragEnd={e => [Link]('onDragEnd')}
>
Drag source
</div>

<div
onDragEnter={e => [Link]('onDragEnter')}
onDragLeave={e => [Link]('onDragLeave')}
onDragOver={e => { [Link](); [Link]('onDragOver'); }}
onDrop={e => [Link]('onDrop')}
>
Drop target
</div>
</>

[Link] 19/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

Parameters

e : A React event object with these extra DragEvent properties:

dataTransfer

It also includes the inherited MouseEvent properties:

altKey

button

buttons

ctrlKey

clientX

clientY

getModifierState(key)

metaKey

movementX

movementY

pageX

pageY

relatedTarget

screenX

screenY

shiftKey

It also includes the inherited UIEvent properties:

detail

view

FocusEvent handler function

An event handler type for the focus events.

<input
onFocus={e => [Link]('onFocus')}

[Link] 20/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

onBlur={e => [Link]('onBlur')}


/>

See an example.

Parameters

e : A React event object with these extra FocusEvent properties:

relatedTarget

It also includes the inherited UIEvent properties:

detail

view

Event handler function

An event handler type for generic events.

Parameters

e : A React event object with no additional properties.

InputEvent handler function

An event handler type for the onBeforeInput event.

<input onBeforeInput={e => [Link]('onBeforeInput')} />

Parameters

e : A React event object with these extra InputEvent properties:

data

[Link] 21/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

KeyboardEvent handler function

An event handler type for keyboard events.

<input
onKeyDown={e => [Link]('onKeyDown')}
onKeyUp={e => [Link]('onKeyUp')}
/>

See an example.

Parameters

e : A React event object with these extra KeyboardEvent properties:

altKey

charCode

code

ctrlKey

getModifierState(key)

key

keyCode

locale

metaKey

location

repeat

shiftKey

which

It also includes the inherited UIEvent properties:

detail

view

MouseEvent handler function


[Link] 22/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

An event handler type for mouse events.

<div
onClick={e => [Link]('onClick')}
onMouseEnter={e => [Link]('onMouseEnter')}
onMouseOver={e => [Link]('onMouseOver')}
onMouseDown={e => [Link]('onMouseDown')}
onMouseUp={e => [Link]('onMouseUp')}
onMouseLeave={e => [Link]('onMouseLeave')}
/>

See an example.

Parameters

e : A React event object with these extra MouseEvent properties:

altKey

button

buttons

ctrlKey

clientX

clientY

getModifierState(key)

metaKey

movementX

movementY

pageX

pageY

relatedTarget

screenX

screenY

shiftKey

It also includes the inherited UIEvent properties:

[Link] 23/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

detail

view

PointerEvent handler function

An event handler type for pointer events.

<div
onPointerEnter={e => [Link]('onPointerEnter')}
onPointerMove={e => [Link]('onPointerMove')}
onPointerDown={e => [Link]('onPointerDown')}
onPointerUp={e => [Link]('onPointerUp')}
onPointerLeave={e => [Link]('onPointerLeave')}
/>

See an example.

Parameters

e : A React event object with these extra PointerEvent properties:

height

isPrimary

pointerId

pointerType

pressure

tangentialPressure

tiltX

tiltY

twist

width

It also includes the inherited MouseEvent properties:

altKey

button

[Link] 24/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

buttons

ctrlKey

clientX

clientY

getModifierState(key)

metaKey

movementX

movementY

pageX

pageY

relatedTarget

screenX

screenY

shiftKey

It also includes the inherited UIEvent properties:

detail

view

TouchEvent handler function

An event handler type for touch events.

<div
onTouchStart={e => [Link]('onTouchStart')}
onTouchMove={e => [Link]('onTouchMove')}
onTouchEnd={e => [Link]('onTouchEnd')}
onTouchCancel={e => [Link]('onTouchCancel')}
/>

Parameters

e : A React event object with these extra TouchEvent properties:

[Link] 25/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

altKey

ctrlKey

changedTouches

getModifierState(key)

metaKey

shiftKey

touches

targetTouches

It also includes the inherited UIEvent properties:

detail

view

TransitionEvent handler function

An event handler type for the CSS transition events.

<div
onTransitionEnd={e => [Link]('onTransitionEnd')}
/>

Parameters

e : A React event object with these extra TransitionEvent properties:

elapsedTime

propertyName

pseudoElement

UIEvent handler function

An event handler type for generic UI events.

[Link] 26/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

<div
onScroll={e => [Link]('onScroll')}
/>

Parameters

e : A React event object with these extra UIEvent properties:

detail

view

WheelEvent handler function

An event handler type for the onWheel event.

<div
onWheel={e => [Link]('onWheel')}
/>

Parameters

e : A React event object with these extra WheelEvent properties:

deltaMode

deltaX

deltaY

deltaZ

It also includes the inherited MouseEvent properties:

altKey

button

buttons

ctrlKey

clientX

[Link] 27/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

clientY

getModifierState(key)

metaKey

movementX

movementY

pageX

pageY

relatedTarget

screenX

screenY

shiftKey

It also includes the inherited UIEvent properties:

detail

view

Usage

Applying CSS styles

In React, you specify a CSS class with className . It works like the class
attribute in HTML:

<img className="avatar" />

Then you write the CSS rules for it in a separate CSS file:

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

[Link] 28/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

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.

Sometimes, the style values depend on data. Use the style attribute to
pass some styles dynamically:

<img
className="avatar"
style={{
width: [Link],
height: [Link]
}}
/>

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.

[Link] [Link] Reset

export default function Avatar({ user }) {


return (
<img
src={[Link]}
alt={'Photo of ' + [Link]}
className="avatar"
style={{
width: [Link],
height: [Link]
}}
/>
);

[Link] 29/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

DEEP DIVE

How to apply multiple CSS classes conditionally?

Show Details

Manipulating a DOM node with a ref

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.

To obtain the browser DOM node for a tag, declare a ref and pass it as the
ref attribute to that tag:

import { useRef } from 'react';

export default function Form() {


const inputRef = useRef(null);
// ...
return (
<input ref={inputRef} />
[Link] 30/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

// ...

React will put the DOM node into [Link] after it’s been rendered
to the screen.

[Link] Download Reset

import { useRef } from 'react';

export default function Form() {


const inputRef = useRef(null);

function handleClick() {
[Link]();
}

return (
<>
<input ref={inputRef} />

Show more

Read more about manipulating DOM with refs and check out more examples.

[Link] 31/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

For more advanced use cases, the ref attribute also accepts a callback
function.

Dangerously setting the inner HTML

You can pass a raw HTML string to an element like so:

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.

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:

[Link] [Link] [Link] Reset

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 = [Link](markdown);
return {__html: renderedHTML};
}

Show more

[Link] 32/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

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:

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
const markup = { __html: [Link] };
return <div dangerouslySetInnerHTML={markup} />;
}

[Link] 33/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

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.

Handling mouse events

This example shows some common mouse events and when they fire.

[Link] Download Reset

export default function MouseExample() {


return (
<div
onMouseEnter={e => [Link]('onMouseEnter (parent)')}
onMouseLeave={e => [Link]('onMouseLeave (parent)')}
>
<button
onClick={e => [Link]('onClick (first button)')}
onMouseDown={e => [Link]('onMouseDown (first button)')}
onMouseEnter={e => [Link]('onMouseEnter (first button)')
onMouseLeave={e => [Link]('onMouseLeave (first button)')

Show more

[Link] 34/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

Handling pointer events

This example shows some common pointer events and when they fire.

[Link] Download Reset

export default function PointerExample() {


return (
<div
onPointerEnter={e => [Link]('onPointerEnter (parent)')}
onPointerLeave={e => [Link]('onPointerLeave (parent)')}
style={{ padding: 20, backgroundColor: '#ddd' }}
>
<div
onPointerDown={e => [Link]('onPointerDown (first child)
onPointerEnter={e => [Link]('onPointerEnter (first child
onPointerLeave={e => [Link]('onPointerLeave (first child

Show more

[Link] 35/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

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.

[Link] Download Reset

export default function FocusExample() {


return (
<div
tabIndex={1}
onFocus={(e) => {
if ([Link] === [Link]) {
[Link]('focused parent');
} else {
[Link]('focused child', [Link]);
}
if (![Link]([Link])) {
// Not triggered when swapping focus between children

Show more

[Link] 36/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

Handling keyboard events

This example shows some common keyboard events and when they fire.

[Link] Download Reset

export default function KeyboardExample() {


return (
<label>
First name:
<input
name="firstName"
onKeyDown={e => [Link]('onKeyDown:', [Link], [Link])}
onKeyUp={e => [Link]('onKeyUp:', [Link], [Link])}
/>
</label>
);
}

[Link] 37/38
20/02/2025, 10:01 Common components (e.g. <div>) – React

PREVIOUS

Components

NEXT

<form>

Copyright © Meta Platforms, Inc

uwu?

Learn React API Reference

Quick Start React APIs

Installation React DOM APIs

Describing the UI

Adding Interactivity

Managing State

Escape Hatches

Community More

Code of Conduct Blog

Meet the Team React Native

Docs Contributors Privacy

Acknowledgements Terms

[Link] 38/38

You might also like