This is one stop global knowledge base where you can learn about all the products, solutions and support features.
The
react-dom
package provides DOM-specific methods that can be used at the top level of your app and as an escape hatch to get outside the React model if you need to.
import * as ReactDOM from 'react-dom';
If you use ES5 with npm, you can write:
var ReactDOM = require('react-dom');
The
react-dom
package also provides modules specific to client and server apps:
react-dom/client
react-dom/server
The
react-dom
package exports these methods:
createPortal()
flushSync()
These
react-dom
methods are also exported, but are considered legacy:
render()
hydrate()
findDOMNode()
unmountComponentAtNode()
Note:
Both
render
andhydrate
have been replaced with new client methods in React 18. These methods will warn that your app will behave as if it’s running React 17 (learn more here).
React supports all modern browsers, although some polyfills are required for older versions.
Note
We do not support older browsers that don’t support ES5 methods or microtasks such as Internet Explorer. You may find that your apps do work in older browsers if polyfills such as es5-shim and es5-sham are included in the page, but you’re on your own if you choose to take this path.
createPortal()
createPortal(child, container)
Creates a portal. Portals provide a way to render children into a DOM node that exists outside the hierarchy of the DOM component.
flushSync()
flushSync(callback)
Force React to flush any updates inside the provided callback synchronously. This ensures that the DOM is updated immediately.
// Force this state update to be synchronous.
flushSync(() => {
setCount(count + 1);
});
// By this point, DOM is updated.
Note:
flushSync
can significantly hurt performance. Use sparingly.
flushSync
may force pending Suspense boundaries to show theirfallback
state.
flushSync
may also run pending effects and synchronously apply any updates they contain before returning.
flushSync
may also flush updates outside the callback when necessary to flush the updates inside the callback. For example, if there are pending updates from a click, React may flush those before flushing the updates inside the callback.
render()
render(element, container[, callback])
Note:
render
has been replaced withcreateRoot
in React 18. See createRoot for more info.
Render a React element into the DOM in the supplied
container
and return a reference to the component (or returns
null
for stateless components).
If the React element was previously rendered into
container
, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element.
If the optional callback is provided, it will be executed after the component is rendered or updated.
Note:
render()
controls the contents of the container node you pass in. Any existing DOM elements inside are replaced when first called. Later calls use React’s DOM diffing algorithm for efficient updates.
render()
does not modify the container node (only modifies the children of the container). It may be possible to insert a component to an existing DOM node without overwriting the existing children.
render()
currently returns a reference to the rootReactComponent
instance. However, using this return value is legacy
and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the rootReactComponent
instance, the preferred solution is to attach a
callback ref to the root element.
Using
render()
to hydrate a server-rendered container is deprecated. UsehydrateRoot()
instead.
hydrate()
hydrate(element, container[, callback])
Note:
hydrate
has been replaced withhydrateRoot
in React 18. See hydrateRoot for more info.
Same as
render()
, but is used to hydrate a container whose HTML contents were rendered by
ReactDOMServer
. React will attempt to attach event listeners to the existing markup.
React expects that the rendered content is identical between the server and the client. It can patch up differences in text content, but you should treat mismatches as bugs and fix them. In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the warning by adding
suppressHydrationWarning={true}
to the element. It only works one level deep, and is intended to be an escape hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates.
If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a state variable like
this.state.isClient
, which you can set to
true
in
componentDidMount()
. This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. Note that this approach will make your components slower because they have to render twice, so use it with caution.
Remember to be mindful of user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so if you render something different in the client-only pass, the transition can be jarring. However, if executed well, it may be beneficial to render a “shell” of the application on the server, and only show some of the extra widgets on the client. To learn how to do this without getting the markup mismatch issues, refer to the explanation in the previous paragraph.
unmountComponentAtNode()
unmountComponentAtNode(container)
Note:
unmountComponentAtNode
has been replaced withroot.unmount()
in React 18. See createRoot for more info.
Remove a mounted React component from the DOM and clean up its event handlers and state. If no component was mounted in the container, calling this function does nothing. Returns
true
if a component was unmounted and
false
if there was no component to unmount.
findDOMNode()
Note:
findDOMNode
is an escape hatch used to access the underlying DOM node. In most cases, use of this escape hatch is discouraged because it pierces the component abstraction. It has been deprecated inStrictMode
.
findDOMNode(component)
If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements.
In most cases, you can attach a ref to the DOM node and avoid using
findDOMNode
at all.
When a component renders to
null
or
false
,
findDOMNode
returns
null
. When a component renders to a string,
findDOMNode
returns a text DOM node containing that value. As of React 16, a component may return a fragment with multiple children, in which case
findDOMNode
will return the DOM node corresponding to the first non-empty child.
Note:
findDOMNode
only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like callingfindDOMNode()
inrender()
on a component that has yet to be created) an exception will be thrown.
findDOMNode
cannot be used on function components.
The
react-dom/client
package provides client-specific methods used for initializing an app on the client. Most of your components should not need to use this module.
import * as ReactDOM from 'react-dom/client';
If you use ES5 with npm, you can write:
var ReactDOM = require('react-dom/client');
The following methods can be used in client environments:
createRoot()
hydrateRoot()
React supports all modern browsers, although some polyfills are required for older versions.
Note
We do not support older browsers that don’t support ES5 methods or microtasks such as Internet Explorer. You may find that your apps do work in older browsers if polyfills such as es5-shim and es5-sham are included in the page, but you’re on your own if you choose to take this path.
createRoot()
createRoot(container[, options]);
Create a React root for the supplied
container
and return the root. The root can be used to render a React element into the DOM with
render
:
const root = createRoot(container);
root.render(element);
createRoot
accepts two options:
onRecoverableError
: optional callback called when React automatically recovers from errors.
identifierPrefix
: optional prefix React uses for ids generated by
React.useId
. Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix used on the server.
The root can also be unmounted with
unmount
:
root.unmount();
Note:
createRoot()
controls the contents of the container node you pass in. Any existing DOM elements inside are replaced when render is called. Later calls use React’s DOM diffing algorithm for efficient updates.
createRoot()
does not modify the container node (only modifies the children of the container). It may be possible to insert a component to an existing DOM node without overwriting the existing children.
Using
createRoot()
to hydrate a server-rendered container is not supported. UsehydrateRoot()
instead.
hydrateRoot()
hydrateRoot(container, element[, options])
Same as
createRoot()
, but is used to hydrate a container whose HTML contents were rendered by
ReactDOMServer
. React will attempt to attach event listeners to the existing markup.
hydrateRoot
accepts two options:
onRecoverableError
: optional callback called when React automatically recovers from errors.
identifierPrefix
: optional prefix React uses for ids generated by
React.useId
. Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix used on the server.
Note
React expects that the rendered content is identical between the server and the client. It can patch up differences in text content, but you should treat mismatches as bugs and fix them. In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
The
ReactDOMServer
object enables you to render components to static markup. Typically, it’s used on a Node server:
// ES modules
import * as ReactDOMServer from 'react-dom/server';
// CommonJS
var ReactDOMServer = require('react-dom/server');
These methods are only available in the environments with Node.js Streams:
renderToPipeableStream()
renderToNodeStream()
(Deprecated)
renderToStaticNodeStream()
These methods are only available in the environments with Web Streams (this includes browsers, Deno, and some modern edge runtimes):
renderToReadableStream()
The following methods can be used in the environments that don’t support streams:
renderToString()
renderToStaticMarkup()
renderToPipeableStream()
ReactDOMServer.renderToPipeableStream(element, options)
Render a React element to its initial HTML. Returns a stream with a
pipe(res)
method to pipe the output and
abort()
to abort the request. Fully supports Suspense and streaming of HTML with “delayed” content blocks “popping in” via inline
<script>
tags later. Read more
If you call
ReactDOM.hydrateRoot()
on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
let didError = false;
const stream = renderToPipeableStream(
<App />,
{
onShellReady() {
// The content above all Suspense boundaries is ready.
// If something errored before we started streaming, we set the error code appropriately.
res.statusCode = didError ? 500 : 200;
res.setHeader('Content-type', 'text/html');
stream.pipe(res);
},
onShellError(error) {
// Something errored before we could complete the shell so we emit an alternative shell.
res.statusCode = 500;
res.send(
'<!doctype html><p>Loading...</p><script src="clientrender.js"></script>'
);
},
onAllReady() {
// If you don't want streaming, use this instead of onShellReady.
// This will fire after the entire page content is ready.
// You can use this for crawlers or static generation.
// res.statusCode = didError ? 500 : 200;
// res.setHeader('Content-type', 'text/html');
// stream.pipe(res);
},
onError(err) {
didError = true;
console.error(err);
},
}
);
See the full list of options.
Note:
This is a Node.js-specific API. Environments with Web Streams, like Deno and modern edge runtimes, should use
renderToReadableStream
instead.
renderToReadableStream()
ReactDOMServer.renderToReadableStream(element, options);
Streams a React element to its initial HTML. Returns a Promise that resolves to a Readable Stream. Fully supports Suspense and streaming of HTML. Read more
If you call
ReactDOM.hydrateRoot()
on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
let controller = new AbortController();
let didError = false;
try {
let stream = await renderToReadableStream(
<html>
<body>Success</body>
</html>,
{
signal: controller.signal,
onError(error) {
didError = true;
console.error(error);
}
}
);
// This is to wait for all Suspense boundaries to be ready. You can uncomment
// this line if you want to buffer the entire HTML instead of streaming it.
// You can use this for crawlers or static generation:
// await stream.allReady;
return new Response(stream, {
status: didError ? 500 : 200,
headers: {'Content-Type': 'text/html'},
});
} catch (error) {
return new Response(
'<!doctype html><p>Loading...</p><script src="clientrender.js"></script>',
{
status: 500,
headers: {'Content-Type': 'text/html'},
}
);
}
See the full list of options.
Note:
This API depends on Web Streams. For Node.js, use
renderToPipeableStream
instead.
renderToNodeStream()
(Deprecated)
ReactDOMServer.renderToNodeStream(element)
Render a React element to its initial HTML. Returns a Node.js Readable stream that outputs an HTML string. The HTML output by this stream is exactly equal to what
ReactDOMServer.renderToString
would return. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call
ReactDOM.hydrateRoot()
on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
Note:
Server-only. This API is not available in the browser.
The stream returned from this method will return a byte stream encoded in utf-8. If you need a stream in another encoding, take a look at a project like iconv-lite, which provides transform streams for transcoding text.
renderToStaticNodeStream()
ReactDOMServer.renderToStaticNodeStream(element)
Similar to
renderToNodeStream
, except this doesn’t create extra DOM attributes that React uses internally, such as
data-reactroot
. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes.
The HTML output by this stream is exactly equal to what
ReactDOMServer.renderToStaticMarkup
would return.
If you plan to use React on the client to make the markup interactive, do not use this method. Instead, use
renderToNodeStream
on the server and
ReactDOM.hydrateRoot()
on the client.
Note:
Server-only. This API is not available in the browser.
The stream returned from this method will return a byte stream encoded in utf-8. If you need a stream in another encoding, take a look at a project like iconv-lite, which provides transform streams for transcoding text.
renderToString()
ReactDOMServer.renderToString(element)
Render a React element to its initial HTML. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call
ReactDOM.hydrateRoot()
on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
Note
This API has limited Suspense support and does not support streaming.
On the server, it is recommended to use either
renderToPipeableStream
(for Node.js) orrenderToReadableStream
(for Web Streams) instead.
renderToStaticMarkup()
ReactDOMServer.renderToStaticMarkup(element)
Similar to
renderToString
, except this doesn’t create extra DOM attributes that React uses internally, such as
data-reactroot
. This is useful if you want to use React as a simple static page generator, as stripping away the extra attributes can save some bytes.
If you plan to use React on the client to make the markup interactive, do not use this method. Instead, use
renderToString
on the server and
ReactDOM.hydrateRoot()
on the client.
React implements a browser-independent DOM system for performance and cross-browser compatibility. We took the opportunity to clean up a few rough edges in browser DOM implementations.
In React, all DOM properties and attributes (including event handlers) should be camelCased. For example, the HTML attribute
tabindex
corresponds to the attribute
tabIndex
in React. The exception is
aria-*
and
data-*
attributes, which should be lowercased. For example, you can keep
aria-label
as
aria-label
.
There are a number of attributes that work differently between React and HTML:
The
checked
attribute is supported by
<input>
components of type
checkbox
or
radio
. You can use it to set whether the component is checked. This is useful for building controlled components.
defaultChecked
is the uncontrolled equivalent, which sets whether the component is checked when it is first mounted.
To specify a CSS class, use the
className
attribute. This applies to all regular DOM and SVG elements like
<div>
,
<a>
, and others.
If you use React with Web Components (which is uncommon), use the
class
attribute instead.
dangerouslySetInnerHTML
is React’s replacement for using
innerHTML
in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out
dangerouslySetInnerHTML
and pass an object with a
__html
key, to remind yourself that it’s dangerous. For example:
function createMarkup() {
return {__html: 'First · Second'};
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />;
}
Since
for
is a reserved word in JavaScript, React elements use
htmlFor
instead.
The
onChange
event behaves as you would expect it to: whenever a form field is changed, this event is fired. We intentionally do not use the existing browser behavior because
onChange
is a misnomer for its behavior and React relies on this event to handle user input in real time.
If you want to mark an
<option>
as selected, reference the value of that option in the
value
of its
<select>
instead.
Check out “The select Tag” for detailed instructions.
Note
Some examples in the documentation use
style
for convenience, but using thestyle
attribute as the primary means of styling elements is generally not recommended. In most cases,className
should be used to reference classes defined in an external CSS stylesheet.style
is most often used in React applications to add dynamically-computed styles at render time. See also FAQ: Styling and CSS.
The
style
attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM
style
JavaScript property, is more efficient, and prevents XSS security holes. For example:
const divStyle = {
color: 'blue',
backgroundImage: 'url(' + imgUrl + ')',
};
function HelloWorldComponent() {
return <div style={divStyle}>Hello World!</div>;
}
Note that styles are not autoprefixed. To support older browsers, you need to supply corresponding style properties:
const divStyle = {
WebkitTransition: 'all', // note the capital 'W' here
msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};
function ComponentWithTransition() {
return <div style={divStyle}>This should work cross-browser</div>;
}
Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g.
node.style.backgroundImage
). Vendor prefixes other than
ms
should begin with a capital letter. This is why
WebkitTransition
has an uppercase “W”.
React will automatically append a “px” suffix to certain numeric inline style properties. If you want to use units other than “px”, specify the value as a string with the desired unit. For example:
// Result style: '10px'
<div style={{ height: 10 }}>
Hello World!
</div>
// Result style: '10%'
<div style={{ height: '10%' }}>
Hello World!
</div>
Not all style properties are converted to pixel strings though. Certain ones remain unitless (eg
zoom
,
order
,
flex
). A complete list of unitless properties can be seen here.
Normally, there is a warning when an element with children is also marked as
contentEditable
, because it won’t work. This attribute suppresses that warning. Don’t use this unless you are building a library like Draft.js that manages
contentEditable
manually.
If you use server-side React rendering, normally there is a warning when the server and the client render different content. However, in some rare cases, it is very hard or impossible to guarantee an exact match. For example, timestamps are expected to differ on the server and on the client.
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. You can read more about hydration in the
ReactDOM.hydrateRoot()
documentation.
The
value
attribute is supported by
<input>
,
<select>
and
<textarea>
components. You can use it to set the value of the component. This is useful for building controlled components.
defaultValue
is the uncontrolled equivalent, which sets the value of the component when it is first mounted.
As of React 16, any standard or custom DOM attributes are fully supported.
React has always provided a JavaScript-centric API to the DOM. Since React components often take both custom and DOM-related props, React uses the
camelCase
convention just like the DOM APIs:
<div tabIndex={-1} /> // Just like node.tabIndex DOM API
<div className="Button" /> // Just like node.className DOM API
<input readOnly={true} /> // Just like node.readOnly DOM API
These props work similarly to the corresponding HTML attributes, with the exception of the special cases documented above.
Some of the DOM attributes supported by React include:
accept acceptCharset accessKey action allowFullScreen alt async autoComplete
autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked
cite classID className colSpan cols content contentEditable contextMenu controls
controlsList coords crossOrigin data dateTime default defer dir disabled
download draggable encType form formAction formEncType formMethod formNoValidate
formTarget frameBorder headers height hidden high href hrefLang htmlFor
httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list
loop low manifest marginHeight marginWidth max maxLength media mediaGroup method
min minLength multiple muted name noValidate nonce open optimum pattern
placeholder poster preload profile radioGroup readOnly rel required reversed
role rowSpan rows sandbox scope scoped scrolling seamless selected shape size
sizes span spellCheck src srcDoc srcLang srcSet start step style summary
tabIndex target title type useMap value width wmode wrap
Similarly, all SVG attributes are fully supported:
accentHeight accumulate additive alignmentBaseline allowReorder alphabetic
amplitude arabicForm ascent attributeName attributeType autoReverse azimuth
baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight
clip clipPath clipPathUnits clipRule colorInterpolation
colorInterpolationFilters colorProfile colorRendering contentScriptType
contentStyleType cursor cx cy d decelerate descent diffuseConstant direction
display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground
end exponent externalResourcesRequired fill fillOpacity fillRule filter
filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize
fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy
g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef
gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic
imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength
kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor
limitingConeAngle local markerEnd markerHeight markerMid markerStart
markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode
numOctaves offset opacity operator order orient orientation origin overflow
overlinePosition overlineThickness paintOrder panose1 pathLength
patternContentUnits patternTransform patternUnits pointerEvents points
pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits
r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions
requiredFeatures restart result rotate rx ry scale seed shapeRendering slope
spacing specularConstant specularExponent speed spreadMethod startOffset
stdDeviation stemh stemv stitchTiles stopColor stopOpacity
strikethroughPosition strikethroughThickness string stroke strokeDasharray
strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity
strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor
textDecoration textLength textRendering to transform u1 u2 underlinePosition
underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic
vHanging vIdeographic vMathematical values vectorEffect version vertAdvY
vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing
writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole
xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlns xmlnsXlink xmlBase
xmlLang xmlSpace y y1 y2 yChannelSelector z zoomAndPan
You may also use custom attributes as long as they’re fully lowercase.
This reference guide documents the
SyntheticEvent
wrapper that forms part of React’s Event System. See the
Handling Events guide to learn more.
Your event handlers will be passed instances of
SyntheticEvent
, a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including
stopPropagation()
and
preventDefault()
, except the events work identically across all browsers.
If you find that you need the underlying browser event for some reason, simply use the
nativeEvent
attribute to get it. The synthetic events are different from, and do not map directly to, the browser’s native events. For example in
onMouseLeave
event.nativeEvent
will point to a
mouseout
event. The specific mapping is not part of the public API and may change at any time. Every
SyntheticEvent
object has the following attributes:
boolean bubbles
boolean cancelable
DOMEventTarget currentTarget
boolean defaultPrevented
number eventPhase
boolean isTrusted
DOMEvent nativeEvent
void preventDefault()
boolean isDefaultPrevented()
void stopPropagation()
boolean isPropagationStopped()
void persist()
DOMEventTarget target
number timeStamp
string type
Note:
As of v17,
e.persist()
doesn’t do anything because theSyntheticEvent
is no longer pooled.
Note:
As of v0.14, returning
false
from an event handler will no longer stop event propagation. Instead,e.stopPropagation()
ore.preventDefault()
should be triggered manually, as appropriate.
React normalizes events so that they have consistent properties across different browsers.
The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append
Capture
to the event name; for example, instead of using
onClick
, you would use
onClickCapture
to handle the click event in the capture phase.
Event names:
onCopy onCut onPaste
Properties:
DOMDataTransfer clipboardData
Event names:
onCompositionEnd onCompositionStart onCompositionUpdate
Properties:
string data
Event names:
onKeyDown onKeyPress onKeyUp
Properties:
boolean altKey
number charCode
boolean ctrlKey
boolean getModifierState(key)
string key
number keyCode
string locale
number location
boolean metaKey
boolean repeat
boolean shiftKey
number which
The
key
property can take any of the values documented in the DOM Level 3 Events spec.
Event names:
onFocus onBlur
These focus events work on all elements in the React DOM, not just form elements.
Properties:
DOMEventTarget relatedTarget
The
onFocus
event is called when the element (or some element inside of it) receives focus. For example, it’s called when the user clicks on a text input.
function Example() {
return (
<input
onFocus={(e) => {
console.log('Focused on input');
}}
placeholder="onFocus is triggered when you click this input."
/>
)
}
The
onBlur
event handler is called when focus has left the element (or left some element inside of it). For example, it’s called when the user clicks outside of a focused text input.
function Example() {
return (
<input
onBlur={(e) => {
console.log('Triggered because this input lost focus');
}}
placeholder="onBlur is triggered when you click this input and then you click outside of it."
/>
)
}
You can use the
currentTarget
and
relatedTarget
to differentiate if the focusing or blurring events originated from
outside
of the parent element. Here is a demo you can copy and paste that shows how to detect focusing a child, focusing the element itself, and focus entering or leaving the whole subtree.
function Example() {
return (
<div
tabIndex={1}
onFocus={(e) => {
if (e.currentTarget === e.target) {
console.log('focused self');
} else {
console.log('focused child', e.target);
}
if (!e.currentTarget.contains(e.relatedTarget)) {
// Not triggered when swapping focus between children
console.log('focus entered self');
}
}}
onBlur={(e) => {
if (e.currentTarget === e.target) {
console.log('unfocused self');
} else {
console.log('unfocused child', e.target);
}
if (!e.currentTarget.contains(e.relatedTarget)) {
// Not triggered when swapping focus between children
console.log('focus left self');
}
}}
>
<input id="1" />
<input id="2" />
</div>
);
}
Event names:
onChange onInput onInvalid onReset onSubmit
For more information about the onChange event, see Forms.
Event names:
onError onLoad
Event names:
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
The
onMouseEnter
and
onMouseLeave
events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.
Properties:
boolean altKey
number button
number buttons
number clientX
number clientY
boolean ctrlKey
boolean getModifierState(key)
boolean metaKey
number pageX
number pageY
DOMEventTarget relatedTarget
number screenX
number screenY
boolean shiftKey
Event names:
onPointerDown onPointerMove onPointerUp onPointerCancel onGotPointerCapture
onLostPointerCapture onPointerEnter onPointerLeave onPointerOver onPointerOut
The
onPointerEnter
and
onPointerLeave
events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.
Properties:
As defined in the W3 spec, pointer events extend Mouse Events with the following properties:
number pointerId
number width
number height
number pressure
number tangentialPressure
number tiltX
number tiltY
number twist
string pointerType
boolean isPrimary
A note on cross-browser support:
Pointer events are not yet supported in every browser (at the time of writing this article, supported browsers include: Chrome, Firefox, Edge, and Internet Explorer). React deliberately does not polyfill support for other browsers because a standard-conform polyfill would significantly increase the bundle size of
react-dom
.
If your application requires pointer events, we recommend adding a third party pointer event polyfill.
Event names:
onSelect
Event names:
onTouchCancel onTouchEnd onTouchMove onTouchStart
Properties:
boolean altKey
DOMTouchList changedTouches
boolean ctrlKey
boolean getModifierState(key)
boolean metaKey
boolean shiftKey
DOMTouchList targetTouches
DOMTouchList touches
Event names:
onScroll
Note
Starting with React 17, the
onScroll
event does not bubble in React. This matches the browser behavior and prevents the confusion when a nested scrollable element fires events on a distant parent.
Properties:
number detail
DOMAbstractView view
Event names:
onWheel
Properties:
number deltaMode
number deltaX
number deltaY
number deltaZ
Event names:
onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted
onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay
onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend
onTimeUpdate onVolumeChange onWaiting
Event names:
onLoad onError
Event names:
onAnimationStart onAnimationEnd onAnimationIteration
Properties:
string animationName
string pseudoElement
float elapsedTime
Event names:
onTransitionEnd
Properties:
string propertyName
string pseudoElement
float elapsedTime
Event names:
onToggle
Importing
import ReactTestUtils from 'react-dom/test-utils'; // ES6
var ReactTestUtils = require('react-dom/test-utils'); // ES5 with npm
ReactTestUtils
makes it easy to test React components in the testing framework of your choice. At Facebook we use Jest for painless JavaScript testing. Learn how to get started with Jest through the Jest website’s React Tutorial.
Note:
We recommend using React Testing Library which is designed to enable and encourage writing tests that use your components as the end users do.
For React versions <= 16, the Enzyme library makes it easy to assert, manipulate, and traverse your React Components’ output.
act()
mockComponent()
isElement()
isElementOfType()
isDOMComponent()
isCompositeComponent()
isCompositeComponentWithType()
findAllInRenderedTree()
scryRenderedDOMComponentsWithClass()
findRenderedDOMComponentWithClass()
scryRenderedDOMComponentsWithTag()
findRenderedDOMComponentWithTag()
scryRenderedComponentsWithType()
findRenderedComponentWithType()
renderIntoDocument()
Simulate
act()
To prepare a component for assertions, wrap the code rendering it and performing updates inside an
act()
call. This makes your test run closer to how React works in the browser.
Note
If you use
react-test-renderer
, it also provides anact
export that behaves the same way.
For example, let’s say we have this
Counter
component:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {count: 0};
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
document.title = `You clicked ${this.state.count} times`;
}
componentDidUpdate() {
document.title = `You clicked ${this.state.count} times`;
}
handleClick() {
this.setState(state => ({
count: state.count + 1,
}));
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.handleClick}>
Click me
</button>
</div>
);
}
}
Here is how we can test it:
import React from 'react';
import ReactDOM from 'react-dom/client';
import { act } from 'react-dom/test-utils';import Counter from './Counter';
let container;
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('can render and update a counter', () => {
// Test first render and componentDidMount
act(() => { ReactDOM.createRoot(container).render(<Counter />); }); const button = container.querySelector('button');
const label = container.querySelector('p');
expect(label.textContent).toBe('You clicked 0 times');
expect(document.title).toBe('You clicked 0 times');
// Test second render and componentDidUpdate
act(() => { button.dispatchEvent(new MouseEvent('click', {bubbles: true})); }); expect(label.textContent).toBe('You clicked 1 times');
expect(document.title).toBe('You clicked 1 times');
});
document
. You can use a library like React Testing Library to reduce the boilerplate code.
recipes
document contains more details on how
act()
behaves, with examples and usage.
mockComponent()
mockComponent(
componentClass,
[mockTagName]
)
Pass a mocked component module to this method to augment it with useful methods that allow it to be used as a dummy React component. Instead of rendering as usual, the component will become a simple
<div>
(or other tag if
mockTagName
is provided) containing any provided children.
Note:
mockComponent()
is a legacy API. We recommend usingjest.mock()
instead.
isElement()
isElement(element)
Returns
true
if
element
is any React element.
isElementOfType()
isElementOfType(
element,
componentClass
)
Returns
true
if
element
is a React element whose type is of a React
componentClass
.
isDOMComponent()
isDOMComponent(instance)
Returns
true
if
instance
is a DOM component (such as a
<div>
or
<span>
).
isCompositeComponent()
isCompositeComponent(instance)
Returns
true
if
instance
is a user-defined component, such as a class or a function.
isCompositeComponentWithType()
isCompositeComponentWithType(
instance,
componentClass
)
Returns
true
if
instance
is a component whose type is of a React
componentClass
.
findAllInRenderedTree()
findAllInRenderedTree(
tree,
test
)
Traverse all components in
tree
and accumulate all components where
test(component)
is
true
. This is not that useful on its own, but it’s used as a primitive for other test utils.
scryRenderedDOMComponentsWithClass()
scryRenderedDOMComponentsWithClass(
tree,
className
)
Finds all DOM elements of components in the rendered tree that are DOM components with the class name matching
className
.
findRenderedDOMComponentWithClass()
findRenderedDOMComponentWithClass(
tree,
className
)
Like
scryRenderedDOMComponentsWithClass()
but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
scryRenderedDOMComponentsWithTag()
scryRenderedDOMComponentsWithTag(
tree,
tagName
)
Finds all DOM elements of components in the rendered tree that are DOM components with the tag name matching
tagName
.
findRenderedDOMComponentWithTag()
findRenderedDOMComponentWithTag(
tree,
tagName
)
Like
scryRenderedDOMComponentsWithTag()
but expects there to be one result, and returns that one result, or throws exception if there is any other number of matches besides one.
scryRenderedComponentsWithType()
scryRenderedComponentsWithType(
tree,
componentClass
)
Finds all instances of components with type equal to
componentClass
.
findRenderedComponentWithType()
findRenderedComponentWithType(
tree,
componentClass
)
Same as
scryRenderedComponentsWithType()
but expects there to be one result and returns that one result, or throws exception if there is any other number of matches besides one.
renderIntoDocument()
renderIntoDocument(element)
Render a React element into a detached DOM node in the document. This function requires a DOM. It is effectively equivalent to:
const domContainer = document.createElement('div');
ReactDOM.createRoot(domContainer).render(element);
Note:
You will need to have
window
,window.document
andwindow.document.createElement
globally available before you importReact
. Otherwise React will think it can’t access the DOM and methods likesetState
won’t work.
Simulate
Simulate.{eventName}(
element,
[eventData]
)
Simulate an event dispatch on a DOM node with optional
eventData
event data.
Simulate
has a method for every event that React understands.
Clicking an element
// <button ref={(node) => this.button = node}>...</button>
const node = this.button;
ReactTestUtils.Simulate.click(node);
Changing the value of an input field and then pressing ENTER.
// <input ref={(node) => this.textInput = node} />
const node = this.textInput;
node.value = 'giraffe';
ReactTestUtils.Simulate.change(node);
ReactTestUtils.Simulate.keyDown(node, {key: "Enter", keyCode: 13, which: 13});
Note
You will have to provide any event property that you’re using in your component (e.g. keyCode, which, etc…) as React is not creating any of these for you.