Komponen umum (e.g. <div>)
Semua komponen bawaan dari sebuah peramban web (browser), seperti <div>
, mendukung beberapa props umum dan event.
- Referensi
- Komponen umum (e.g.
<div>
) ref
callback function- React event object
AnimationEvent
handler functionClipboardEvent
handler functionCompositionEvent
handler functionDragEvent
handler functionFocusEvent
handler functionEvent
handler functionInputEvent
handler functionKeyboardEvent
handler functionMouseEvent
handler functionPointerEvent
handler functionTouchEvent
handler functionTransitionEvent
handler functionUIEvent
handler functionWheelEvent
handler function
- Komponen umum (e.g.
- Usage
Referensi
Komponen umum (e.g. <div>
)
<div className="wrapper">beberapa konten</div>
Props
Beberapa props spesial React berikut didukung oleh setiap komponen bawaan:
-
children
: Sebuah node React (sebuah elemen, string, angka, portal, node kosong sepertinull
,undefined
and booleans, atau senarai dari nodes React). Menggambarkan kontent yang berada di dalam komponen. Saat menggunakan JSX, biasanya kau akan mendefinisikan prop darichildren
secara implisit dengan menggunakan tag bersarang seperti<div><span /></div>
. -
dangerouslySetInnerHTML
: Sebuah objek dengan bentuk{ __html: '<p>some html</p>' }
yang mengandung string HTML mentah. Objek ini menimpainnerHTML
yang merupakan properti dari DOM node dan menampilkan HTML yang di-passing ke dalamnya. Hal ini harus digunakan dengan sangat hati-hati! Jika HTML yang berada didalamnya tidak terpercaya (sebagai contoh, jika datanya berbasis pada data pengguna), akan beresiko pada munculnya kerentanan terhadap XSS. Baca lebih lanjut mengenai penggunaandangerouslySetInnerHTML
. -
ref
: Ref adalah sebuah objek dariuseRef
ataucreateRef
, atau sebuah fungsi callbackref
, atau sebuah string untuk legacy refs. Ref anda akan diisi dengan elemen DOM untuk node tersebut. Baca lebih lanjut mengenai memanipulasi DOM dengan refs. -
suppressContentEditableWarning
: Sebuah boolean. Jikatrue
, menekan peringatan yang ditampilkan oleh React untuk element yang memngandungchildren
dancontentEditable={true}
(yang biasanya tidak bekerja secara bersamaan). Gunakan prop ini jika anda sedang membangun sebuah library input teks yang mengelola kontencontentEditable
secara manual. -
suppressHydrationWarning
: Sebuah boolean. Jika anda menggunakan server rendering, biasanya terdapat peringatan saat server dan client me-render konten yang berbeda. Untuk beberapa kasus langka (seperti tag waktu), sangat sulit atau tidak mungkin untuk menjamin kecocokan yang tepat. Jika anda mengatursuppressHydrationWarning
menjaditrue
, React tidak akan memperingati anda mengenai ketidakcocokan dalam atribut ataupun konten dari elemen tersebut. Ini hanya bekerja sedalam satu tingkat, dan dimaksudkan untuk digunakan sebagai pintu keluar darurat. Jangan terlalu sering menggunakannya. Baca mengenai menekan kesalahan hidrasi. -
style
: Sebuah objek styles CSS, sebagai contoh{ fontWeight: 'bold', margin: 20 }
. Seperti properti dari DOMstyle
, penamaan dari properti CSS harus ditulis dalamcamelCase
, sebagai contohfontWeight
bukanfont-weight
. Anda dapat memasukkan string atau angka sebagai nilai. Jika anda memasukkan angka, sepertiwidth: 100
, React akan secara otomatis menambahkanpx
(“piksel”) ke dalam nilai tersebut kecuali jika properti tersebut merupakan properti tanpa unit. Kami merekomendasikan penggunaanstyle
hanya untuk styles yang bersifat dinamis yang mana nilai dari style tersebut masih dapat berubah-ubah. Untuk kasus lainnya, penggunaan kelas CSS biasa denganclassName
lebih efisien. Baca lebih lanjut mengenaiclassName
danstyle
.
Berikut props DOM standar yang juga didukung oleh setiap komponen bawaan:
accessKey
: Sebuah string. Menentukan pintasan (shortcut) keyboard untuk elemen. Tidak direkomendasikan secara umum.aria-*
: Atribut ARIA memungkinkan anda untuk menentukan informasi pohon aksesibilitas untuk elemen ini. Liat ARIA attributes untuk referensi yang lengkap. Dalam React, setiap atribut ARIA memiliki nama yang sama persis seperti di HTML.autoCapitalize
: Sebuah string. menentukan apakah dan bagaimana masukkan dari pengguna harus dikapitalisasi.className
: Sebuah string. Menentukan nama kelas CSS dari elemen tersebut. Baca lebih lanjut mengenai menerapkan styles CSS.contentEditable
: Sebuah boolean. Jikatrue
, peramban web (browser) akan membiarkan pengguna untuk menyunting elemen yang di-render secara langsung. Ini digunakan untuk mengimplementasi libraries masukkan teks kaya seperti Lexical. React akan memperingatkan jika anda mencoba untuk memasukkan children React ke dalam elemen tersebut dengancontentEditable={true}
karena React tidak akan bisa memperbarui konten tersebut setelah disunting oleh pengguna.data-*
: Atribut data membiarkan Anda melampirkan beberapa data string ke element, sebagai contohdata-buah="pisang"
. Dalam React, hal ini jarang digunakan karena biasanya anda membaca data dari props ataupun state.dir
: Antara'ltr'
atau'rtl'
. Menentukan arah teks dari elemen tersebut.draggable
: Sebuah boolean. Menentukan apakah elemen tersebut dapat diseret. Bagian dari API HTML Drag and Drop.enterKeyHint
: Sebuah string. Menentukan aksi apa yang direpresentasikan oleh tombol enter pada keyboard virtual.htmlFor
: Sebuah string. Untuk<label>
dan<output>
, Memungkinan anda untuk mengasosiasikan label the beberapa kontrol. Sama seperti atribut HTMLfor
. React tidak menggunakan nama dari atribut HTML melainkan menggunakan nama properti standar DOM (htmlFor
)hidden
: Sebuah boolean atau string. Menentukan apakah sebuah elemen disembunyikan atau tidak.id
: Sebuah string. Menentukan pengidentifikasi untuk untuk elemen ini, yang mana dapat digunakan untuk menemukannya kembali atau menghubungkannya dengan elemen lain. Dapatkan dengan menggunakanuseId
untuk menghidari bentrokan antara beberapa instances pada komponen yang sama.is
: Sebuah string. Jika ditentukan, maka komponen tersebut akan berperilaku seperti elemen kustom.inputMode
: Sebuah string. Menentukan jenis keyboard apa yang akan ditampilkan (sebagai contoh, teks, angka or telepon).itemProp
: Sebuah string. Menentukan properti apa yang merepresentasikan elemen untuk crawler data terstruktur.lang
: Sebuah string. Menentukan bahasa dari elemen tersebut.onAnimationEnd
: Sebuah fungsi handlerAnimationEvent
. Aktif saat sebuah animasi CSS selesai.onAnimationEndCapture
: Sebuah versi darionAnimationEnd
yang aktif pada fase penangkapan.onAnimationIteration
: Sebuah fungsi handlerAnimationEvent
. Aktif saat iterasi dari animasi CSS selesai, dan dimulainya animasi selanjutnya.onAnimationIterationCapture
: Sebuah versi darionAnimationIteration
yang aktif pada fase penangkapan.onAnimationStart
: Sebuah fungsi handlerAnimationEvent
. Aktif saat animasi CSS dimulai.onAnimationStartCapture
:onAnimationStart
, tetapi aktif pada fase penangkapan.onAuxClick
: Sebuah fungsi handlerMouseEvent
. Aktif saat tombol penunjuk non-primer diklik.onAuxClickCapture
: Sebuah versi darionAuxClick
yang aktif pada fase penangkapan.onBeforeInput
: Sebuah fungsi handlerInputEvent
. Aktif sebelum dilakukan modifikasi pada nilai dari elemen yang dapat disunting. React belum mengunakan eventbeforeinput
native, dan alih-alih mencoba mengisinya menggunakan event lain.onBeforeInputCapture
: Sebuah versi darionBeforeInput
yang aktif pada fase penangkapan.onBlur
: Sebuah fungsi handlerFocusEvent
. Aktif saat sebuah elemen kehilangan fokus. Tidak seperti eventblur
bawaan dari peramban web (browser), di React eventonBlur
menggelembung (bubbles).onBlurCapture
: Sebuah versi darionBlur
yang aktif pada fase penangkapan.onClick
: Sebuah fungsi handlerMouseEvent
. Aktif ketika tombol primer pada perangkat penunjuk diklik.onClickCapture
: Sebuah versi darionClick
yang aktif pada fase penangkapan.onCompositionStart
: Sebuah fungsi handlerCompositionEvent
. Aktif saat input method editor memulai sebuah sesi komposisi baru.onCompositionStartCapture
: Sebuah versi darionCompositionStart
yang aktif pada fase penangkapan.onCompositionEnd
: Sebuah fungsi handlerCompositionEvent
. Aktif saat input method editor menyelesaikan atau membatalkan sebuah sesi komposisi.onCompositionEndCapture
: Sebuah versi darionCompositionEnd
yang aktif pada fase penangkapan.onCompositionUpdate
: Sebuah fungsi handlerCompositionEvent
. Aktif saat input method editor menerima karakter baru.onCompositionUpdateCapture
: Sebuah versi darionCompositionUpdate
yang aktif pada fase penangkapan.onContextMenu
: Sebuah fungsi handlerMouseEvent
. Aktif saat pengguna mencoba untuk membuka menu konteks.onContextMenuCapture
: Sebuah versi darionContextMenu
yang aktif pada fase penangkapan.onCopy
: Sebuah fungsi handlerClipboardEvent
. Aktif saat pengguna mencoba menyalin (copy) sesuatu ke clipboard.onCopyCapture
: Sebuah versi darionCopy
yang aktif pada fase penangkapan.onCut
: Sebuah fungsi handlerClipboardEvent
. Aktif saat pengguna mencoba untuk memotong (cut) sesuatu ke clipboard.onCutCapture
: Sebuah versi darionCut
yang aktif pada fase penangkapan.onDoubleClick
: Sebuah fungsi handlerMouseEvent
. Aktif saat pengguna melakukan klik sebanyak dua kali. Sesuai dengan eventdblclick
pada peramban web (browser).onDoubleClickCapture
: Sebuah versi darionDoubleClick
yang aktif pada fase penangkapan.onDrag
: Sebuah fungsi handlerDragEvent
. Aktif ketika user mencoba untuk menyeret sesuatu.onDragCapture
: Sebuah versi darionDrag
yang aktif pada fase penangkapan.onDragEnd
: Sebuah fungsi handlerDragEvent
. Aksitf saat user berhenti menyeret sesuatu.onDragEndCapture
: Sebuah versi darionDragEnd
yang aktif pada fase penangkapan.onDragEnter
: Sebuah fungsi handlerDragEvent
. Aktif saat konten yang terseret memasuki suatu target penurunan yang valid.onDragEnterCapture
: Sebuah versi darionDragEnter
yang aktif pada fase penangkapan.onDragOver
: ADragEvent
handler function. Fires on a valid drop target while the dragged content is dragged over it. You must calle.preventDefault()
here to allow dropping.onDragOverCapture
: A version ofonDragOver
that fires in the capture phase.onDragStart
: ADragEvent
handler function. Fires when the user starts dragging an element.onDragStartCapture
: A version ofonDragStart
that fires in the capture phase.onDrop
: ADragEvent
handler function. Fires when something is dropped on a valid drop target.onDropCapture
: A version ofonDrop
that fires in the capture phase.onFocus
: AFocusEvent
handler function. Fires when an element lost focus. Unlike the built-in browserfocus
event, in React theonFocus
event bubbles.onFocusCapture
: A version ofonFocus
that fires in the capture phase.onGotPointerCapture
: APointerEvent
handler function. Fires when an element programmatically captures a pointer.onGotPointerCaptureCapture
: A version ofonGotPointerCapture
that fires in the capture phase.onKeyDown
: AKeyboardEvent
handler function. Fires when a key is pressed.onKeyDownCapture
: A version ofonKeyDown
that fires in the capture phase.onKeyPress
: AKeyboardEvent
handler function. Deprecated. UseonKeyDown
oronBeforeInput
instead.onKeyPressCapture
: A version ofonKeyPress
that fires in the capture phase.onKeyUp
: AKeyboardEvent
handler function. Fires when a key is released.onKeyUpCapture
: A version ofonKeyUp
that fires in the capture phase.onLostPointerCapture
: APointerEvent
handler function. Fires when an element stops capturing a pointer.onLostPointerCaptureCapture
: A version ofonLostPointerCapture
that fires in the capture phase.onMouseDown
: AMouseEvent
handler function. Fires when the pointer is pressed down.onMouseDownCapture
: A version ofonMouseDown
that fires in the capture phase.onMouseEnter
: AMouseEvent
handler function. Fires when the pointer moves inside an element. Does not have a capture phase. Instead,onMouseLeave
andonMouseEnter
propagate from the element being left to the one being entered.onMouseLeave
: AMouseEvent
handler function. Fires when the pointer moves outside an element. Does not have a capture phase. Instead,onMouseLeave
andonMouseEnter
propagate from the element being left to the one being entered.onMouseMove
: AMouseEvent
handler function. Fires when the pointer changes coordinates.onMouseMoveCapture
: A version ofonMouseMove
that fires in the capture phase.onMouseOut
: AMouseEvent
handler function. Fires when the pointer moves outside an element, or if it moves into a child element.onMouseOutCapture
: A version ofonMouseOut
that fires in the capture phase.onMouseUp
: AMouseEvent
handler function. Fires when the pointer is released.onMouseUpCapture
: A version ofonMouseUp
that fires in the capture phase.onPointerCancel
: APointerEvent
handler function. Fires when the browser cancels a pointer interaction.onPointerCancelCapture
: A version ofonPointerCancel
that fires in the capture phase.onPointerDown
: APointerEvent
handler function. Fires when a pointer becomes active.onPointerDownCapture
: A version ofonPointerDown
that fires in the capture phase.onPointerEnter
: APointerEvent
handler function. Fires when a pointer moves inside an element. Does not have a capture phase. Instead,onPointerLeave
andonPointerEnter
propagate from the element being left to the one being entered.onPointerLeave
: APointerEvent
handler function. Fires when a pointer moves outside an element. Does not have a capture phase. Instead,onPointerLeave
andonPointerEnter
propagate from the element being left to the one being entered.onPointerMove
: APointerEvent
handler function. Fires when a pointer changes coordinates.onPointerMoveCapture
: A version ofonPointerMove
that fires in the capture phase.onPointerOut
: APointerEvent
handler function. Fires when a pointer moves outside an element, if the pointer interaction is cancelled, and a few other reasons.onPointerOutCapture
: A version ofonPointerOut
that fires in the capture phase.onPointerUp
: APointerEvent
handler function. Fires when a pointer is no longer active.onPointerUpCapture
: A version ofonPointerUp
that fires in the capture phase.onPaste
: AClipboardEvent
handler function. Fires when the user tries to paste something from the clipboard.onPasteCapture
: A version ofonPaste
that fires in the capture phase.onScroll
: AnEvent
handler function. Fires when an element has been scrolled. This event does not bubble.onScrollCapture
: A version ofonScroll
that fires in the capture phase.onSelect
: AnEvent
handler function. Fires after the selection inside an editable element like an input changes. React extends theonSelect
event to work forcontentEditable={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 ofonSelect
that fires in the capture phase.onTouchCancel
: ATouchEvent
handler function. Fires when the browser cancels a touch interaction.onTouchCancelCapture
: A version ofonTouchCancel
that fires in the capture phase.onTouchEnd
: ATouchEvent
handler function. Fires when one or more touch points are removed.onTouchEndCapture
: A version ofonTouchEnd
that fires in the capture phase.onTouchMove
: ATouchEvent
handler function. Fires one or more touch points are moved.onTouchMoveCapture
: A version ofonTouchMove
that fires in the capture phase.onTouchStart
: ATouchEvent
handler function. Fires when one or more touch points are placed.onTouchStartCapture
: A version ofonTouchStart
that fires in the capture phase.onTransitionEnd
: ATransitionEvent
handler function. Fires when a CSS transition completes.onTransitionEndCapture
: A version ofonTransitionEnd
that fires in the capture phase.onWheel
: AWheelEvent
handler function. Fires when the user rotates a wheel button.onWheelCapture
: A version ofonWheel
that fires in the capture phase.role
: A string. Specifies the element role explicitly for assistive technologies. nt.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 totrue
orfalse
, enables or disables spellchecking.tabIndex
: A number. Overrides the default Tab button behavior. Avoid using values other than-1
and0
.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
: AnEvent
handler function. Fires when a form gets reset.onResetCapture
: A version ofonReset
that fires in the capture phase.onSubmit
: AnEvent
handler function. Fires when a form gets submitted.onSubmitCapture
: A version ofonSubmit
that fires in the capture phase.
These events fire only for the <dialog>
elements. Unlike browser events, they bubble in React:
onCancel
: AnEvent
handler function. Fires when the user tries to dismiss the dialog.onCancelCapture
: A version ofonCancel
that fires in the capture phase. capture-phase-events)onClose
: AnEvent
handler function. Fires when a dialog has been closed.onCloseCapture
: A version ofonClose
that fires in the capture phase.
These events fire only for the <details>
elements. Unlike browser events, they bubble in React:
onToggle
: AnEvent
handler function. Fires when the user toggles the details.onToggleCapture
: A version ofonToggle
that fires in the capture phase. capture-phase-events)
These events fire for <img>
, <iframe>
, <object>
, <embed>
, <link>
, and SVG <image>
elements. Unlike browser events, they bubble in React:
onLoad
: AnEvent
handler function. Fires when the resource has loaded.onLoadCapture
: A version ofonLoad
that fires in the capture phase.onError
: AnEvent
handler function. Fires when the resource could not be loaded.onErrorCapture
: A version ofonError
that fires in the capture phase.
These events fire for resources like <audio>
and <video>
. Unlike browser events, they bubble in React:
onAbort
: AnEvent
handler function. Fires when the resource has not fully loaded, but not due to an error.onAbortCapture
: A version ofonAbort
that fires in the capture phase.onCanPlay
: AnEvent
handler function. Fires when there’s enough data to start playing, but not enough to play to the end without buffering.onCanPlayCapture
: A version ofonCanPlay
that fires in the capture phase.onCanPlayThrough
: AnEvent
handler function. Fires when there’s enough data that it’s likely possible to start playing without buffering until the end.onCanPlayThroughCapture
: A version ofonCanPlayThrough
that fires in the capture phase.onDurationChange
: AnEvent
handler function. Fires when the media duration has updated.onDurationChangeCapture
: A version ofonDurationChange
that fires in the capture phase.onEmptied
: AnEvent
handler function. Fires when the media has become empty.onEmptiedCapture
: A version ofonEmptied
that fires in the capture phase.onEncrypted
: AnEvent
handler function. Fires when the browser encounters encrypted media.onEncryptedCapture
: A version ofonEncrypted
that fires in the capture phase.onEnded
: AnEvent
handler function. Fires when the playback stops because there’s nothing left to play.onEndedCapture
: A version ofonEnded
that fires in the capture phase.onError
: AnEvent
handler function. Fires when the resource could not be loaded.onErrorCapture
: A version ofonError
that fires in the capture phase.onLoadedData
: AnEvent
handler function. Fires when the current playback frame has loaded.onLoadedDataCapture
: A version ofonLoadedData
that fires in the capture phase.onLoadedMetadata
: AnEvent
handler function. Fires when metadata has loaded.onLoadedMetadataCapture
: A version ofonLoadedMetadata
that fires in the capture phase.onLoadStart
: AnEvent
handler function. Fires when the browser started loading the resource.onLoadStartCapture
: A version ofonLoadStart
that fires in the capture phase.onPause
: AnEvent
handler function. Fires when the media was paused.onPauseCapture
: A version ofonPause
that fires in the capture phase.onPlay
: AnEvent
handler function. Fires when the media is no longer paused.onPlayCapture
: A version ofonPlay
that fires in the capture phase.onPlaying
: AnEvent
handler function. Fires when the media starts or restarts playing.onPlayingCapture
: A version ofonPlaying
that fires in the capture phase.onProgress
: AnEvent
handler function. Fires periodically while the resource is loading.onProgressCapture
: A version ofonProgress
that fires in the capture phase.onRateChange
: AnEvent
handler function. Fires when playback rate changes.onRateChangeCapture
: A version ofonRateChange
that fires in the capture phase.onResize
: AnEvent
handler function. Fires when video changes size.onResizeCapture
: A version ofonResize
that fires in the capture phase.onSeeked
: AnEvent
handler function. Fires when a seek operation completes.onSeekedCapture
: A version ofonSeeked
that fires in the capture phase.onSeeking
: AnEvent
handler function. Fires when a seek operation starts.onSeekingCapture
: A version ofonSeeking
that fires in the capture phase.onStalled
: AnEvent
handler function. Fires when the browser is waiting for data but it keeps not loading.onStalledCapture
: A version ofonStalled
that fires in the capture phase.onSuspend
: AnEvent
handler function. Fires when loading the resource was suspended.onSuspendCapture
: A version ofonSuspend
that fires in the capture phase.onTimeUpdate
: AnEvent
handler function. Fires when the current playback time updates.onTimeUpdateCapture
: A version ofonTimeUpdate
that fires in the capture phase.onVolumeChange
: AnEvent
handler function. Fires when the volume has changed.onVolumeChangeCapture
: A version ofonVolumeChange
that fires in the capture phase.onWaiting
: AnEvent
handler function. Fires when the playback stopped due to temporary lack of data.onWaitingCapture
: A version ofonWaiting
that fires in the capture phase.
Caveats
- You cannot pass both
children
anddangerouslySetInnerHTML
at the same time. - Some events (like
onAbort
andonLoad
) 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) => console.log(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 ref
callback with null
.
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.
Parameters
node
: A DOM node ornull
. React will pass you the DOM node when the ref gets attached, andnull
when the ref gets detached. Unless you pass the same function reference for theref
callback on every render, the callback will get temporarily detached and re-attached during ever re-render of the component.
Returns
Do not return anything from the ref
callback.
React event object
Your event handlers will receive a React event object. It is also sometimes known as a “synthetic event”.
<button onClick={e => {
console.log(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
, 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
.
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 whetherpreventDefault
was called.eventPhase
: A number. Returns which phase the event is currently in.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 DOMEvent
. 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 whetherpreventDefault
was called.isPropagationStopped()
: Returns a boolean value indicating whetherstopPropagation
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 whetherpersist
has been called.
Caveats
- The values of
currentTarget
,eventPhase
,target
, andtype
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 underlyinge.nativeEvent.currentTarget
. For polyfilled events,e.type
(React event type) may differ frome.nativeEvent.type
(underlying type).
AnimationEvent
handler function
An event handler type for the CSS animation events.
<div
onAnimationStart={e => console.log('onAnimationStart')}
onAnimationIteration={e => console.log('onAnimationIteration')}
onAnimationEnd={e => console.log('onAnimationEnd')}
/>
Parameters
e
: A React event object with these extraAnimationEvent
properties:
ClipboardEvent
handler function
An event handler type for the Clipboard API events.
<input
onCopy={e => console.log('onCopy')}
onCut={e => console.log('onCut')}
onPaste={e => console.log('onPaste')}
/>
Parameters
-
e
: A React event object with these extraClipboardEvent
properties:
CompositionEvent
handler function
An event handler type for the input method editor (IME) events.
<input
onCompositionStart={e => console.log('onCompositionStart')}
onCompositionUpdate={e => console.log('onCompositionUpdate')}
onCompositionEnd={e => console.log('onCompositionEnd')}
/>
Parameters
e
: A React event object with these extraCompositionEvent
properties:
DragEvent
handler function
An event handler type for the HTML Drag and Drop API events.
<>
<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
-
e
: A React event object with these extraDragEvent
properties: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:
FocusEvent
handler function
An event handler type for the focus events.
<input
onFocus={e => console.log('onFocus')}
onBlur={e => console.log('onBlur')}
/>
Parameters
-
e
: A React event object with these extraFocusEvent
properties:It also includes the inherited
UIEvent
properties:
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 => console.log('onBeforeInput')} />
Parameters
e
: A React event object with these extraInputEvent
properties:
KeyboardEvent
handler function
An event handler type for keyboard events.
<input
onKeyDown={e => console.log('onKeyDown')}
onKeyUp={e => console.log('onKeyUp')}
/>
Parameters
-
e
: A React event object with these extraKeyboardEvent
properties:altKey
charCode
code
ctrlKey
getModifierState(key)
key
keyCode
locale
metaKey
location
repeat
shiftKey
which
It also includes the inherited
UIEvent
properties:
MouseEvent
handler function
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')}
/>
Parameters
-
e
: A React event object with these extraMouseEvent
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:
PointerEvent
handler function
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')}
/>
Parameters
-
e
: A React event object with these extraPointerEvent
properties: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:
TouchEvent
handler function
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
-
e
: A React event object with these extraTouchEvent
properties:It also includes the inherited
UIEvent
properties:
TransitionEvent
handler function
An event handler type for the CSS transition events.
<div
onTransitionEnd={e => console.log('onTransitionEnd')}
/>
Parameters
e
: A React event object with these extraTransitionEvent
properties:
UIEvent
handler function
An event handler type for generic UI events.
<div
onScroll={e => console.log('onScroll')}
/>
Parameters
e
: A React event object with these extraUIEvent
properties:
WheelEvent
handler function
An event handler type for the onWheel
event.
<div
onScroll={e => console.log('onScroll')}
/>
Parameters
-
e
: A React event object with these extraWheelEvent
properties: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:
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%;
}
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: 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.
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
To apply CSS classes conditionally, you need to produce the className
string yourself using JavaScript.
For example, className={'row ' + (isSelected ? 'selected': '')}
will produce either className="row"
or className="row selected"
depending on whether isSelected
is true
.
To make this more readable, you can use a tiny helper library like 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
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} />
// ...
React will put the DOM node into inputRef.current
after it’s been rendered to the screen.
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.
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:
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} />; }
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: 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.
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> ); }
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.
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> ); }
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> ); }