This is one stop global knowledge base where you can learn about all the products, solutions and support features.
This page contains a detailed API reference for the React component class definition. It assumes you’re familiar with fundamental React concepts, such as Components and Props, as well as State and Lifecycle. If you’re not, read them first.
React lets you define components as classes or functions. Components defined as classes currently provide more features which are described in detail on this page. To define a React component class, you need to extend
React.Component
:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
The only method you
must
define in a
React.Component
subclass is called
render()
. All the other methods described on this page are optional.
We strongly recommend against creating your own base component classes. In React components, code reuse is primarily achieved through composition rather than inheritance.
Note:
React doesn’t force you to use the ES6 class syntax. If you prefer to avoid it, you may use the
create-react-class
module or a similar custom abstraction instead. Take a look at Using React without ES6 to learn more.
Each component has several “lifecycle methods” that you can override to run code at particular times in the process. You can use this lifecycle diagram as a cheat sheet. In the list below, commonly used lifecycle methods are marked as bold . The rest of them exist for relatively rare use cases.
These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
Note:
This method is considered legacy and you should avoid it in new code:
UNSAFE_componentWillMount()
An update can be caused by changes to props or state. These methods are called in the following order when a component is being re-rendered:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
Note:
These methods are considered legacy and you should avoid them in new code:
UNSAFE_componentWillUpdate()
UNSAFE_componentWillReceiveProps()
This method is called when a component is being removed from the DOM:
componentWillUnmount()
These methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component.
static getDerivedStateFromError()
componentDidCatch()
Each component also provides some other APIs:
setState()
forceUpdate()
defaultProps
displayName
props
state
The methods in this section cover the vast majority of use cases you’ll encounter creating React components. For a visual reference, check out this lifecycle diagram.
render()
render()
The
render()
method is the only required method in a class component.
When called, it should examine
this.props
and
this.state
and return one of the following types:
<div />
and
<MyComponent />
are React elements that instruct React to render a DOM node, or another user-defined component, respectively.
null
or
undefined
. Render nothing. (Mostly exists to support
return test && <Child />
pattern, where
test
is boolean).
The
render()
function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.
If you need to interact with the browser, perform your work in
componentDidMount()
or the other lifecycle methods instead. Keeping
render()
pure makes components easier to think about.
Note
render()
will not be invoked ifshouldComponentUpdate()
returns false.
constructor()
constructor(props)
If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component.
The constructor for a React component is called before it is mounted. When implementing the constructor for a
React.Component
subclass, you should call
super(props)
before any other statement. Otherwise,
this.props
will be undefined in the constructor, which can lead to bugs.
Typically, in React constructors are only used for two purposes:
this.state
.
You
should not call
setState()
in the
constructor()
. Instead, if your component needs to use local state,
assign the initial state to
this.state
directly in the constructor:
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
Constructor is the only place where you should assign
this.state
directly. In all other methods, you need to use
this.setState()
instead.
Avoid introducing any side-effects or subscriptions in the constructor. For those use cases, use
componentDidMount()
instead.
Note
Avoid copying props into state! This is a common mistake:
constructor(props) {
super(props);
// Don't do this!
this.state = { color: props.color };
}
The problem is that it’s both unnecessary (you can use
this.props.color
directly instead), and creates bugs (updates to thecolor
prop won’t be reflected in the state).
Only use this pattern if you intentionally want to ignore prop updates. In that case, it makes sense to rename the prop to be called
initialColor
ordefaultColor
. You can then force a component to “reset” its internal state by changing itskey
when necessary.
Read our blog post on avoiding derived state to learn about what to do if you think you need some state to depend on the props.
componentDidMount()
componentDidMount()
componentDidMount()
is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.
This method is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in
componentWillUnmount()
.
You
may call
setState()
immediately
in
componentDidMount()
. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the
render()
will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the
constructor()
instead. It can, however, be necessary for cases like modals and tooltips when you need to measure a DOM node before rendering something that depends on its size or position.
componentDidUpdate()
componentDidUpdate(prevProps, prevState, snapshot)
componentDidUpdate()
is invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
You
may call
setState()
immediately
in
componentDidUpdate()
but note that
it must be wrapped in a condition
like in the example above, or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If you’re trying to “mirror” some state to a prop coming from above, consider using the prop directly instead. Read more about why copying props into state causes bugs.
If your component implements the
getSnapshotBeforeUpdate()
lifecycle (which is rare), the value it returns will be passed as a third “snapshot” parameter to
componentDidUpdate()
. Otherwise this parameter will be undefined.
Note
componentDidUpdate()
will not be invoked ifshouldComponentUpdate()
returns false.
componentWillUnmount()
componentWillUnmount()
componentWillUnmount()
is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in
componentDidMount()
.
You
should not call
setState()
in
componentWillUnmount()
because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.
The methods in this section correspond to uncommon use cases. They’re handy once in a while, but most of your components probably don’t need any of them. You can see most of the methods below on this lifecycle diagram if you click the “Show less common lifecycles” checkbox at the top of it.
shouldComponentUpdate()
shouldComponentUpdate(nextProps, nextState)
Use
shouldComponentUpdate()
to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
shouldComponentUpdate()
is invoked before rendering when new props or state are being received. Defaults to
true
. This method is not called for the initial render or when
forceUpdate()
is used.
This method only exists as a
performance optimization.
Do not rely on it to “prevent” a rendering, as this can lead to bugs.
Consider using the built-in
PureComponent
instead of writing
shouldComponentUpdate()
by hand.
PureComponent
performs a shallow comparison of props and state, and reduces the chance that you’ll skip a necessary update.
If you are confident you want to write it by hand, you may compare
this.props
with
nextProps
and
this.state
with
nextState
and return
false
to tell React the update can be skipped. Note that returning
false
does not prevent child components from re-rendering when
their
state changes.
We do not recommend doing deep equality checks or using
JSON.stringify()
in
shouldComponentUpdate()
. It is very inefficient and will harm performance.
Currently, if
shouldComponentUpdate()
returns
false
, then
UNSAFE_componentWillUpdate()
,
render()
, and
componentDidUpdate()
will not be invoked. In the future React may treat
shouldComponentUpdate()
as a hint rather than a strict directive, and returning
false
may still result in a re-rendering of the component.
static getDerivedStateFromProps()
static getDerivedStateFromProps(props, state)
getDerivedStateFromProps
is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or
null
to update nothing.
This method exists for rare use cases where the state depends on changes in props over time. For example, it might be handy for implementing a
<Transition>
component that compares its previous and next children to decide which of them to animate in and out.
Deriving state leads to verbose code and makes your components difficult to think about.
Make sure you’re familiar with simpler alternatives:
componentDidUpdate
lifecycle instead.
key
instead.
This method doesn’t have access to the component instance. If you’d like, you can reuse some code between
getDerivedStateFromProps()
and the other class methods by extracting pure functions of the component props and state outside the class definition.
Note that this method is fired on
every
render, regardless of the cause. This is in contrast to
UNSAFE_componentWillReceiveProps
, which only fires when the parent causes a re-render and not as a result of a local
setState
.
getSnapshotBeforeUpdate()
getSnapshotBeforeUpdate(prevProps, prevState)
getSnapshotBeforeUpdate()
is invoked right before the most recently rendered output is committed to e.g. the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed. Any value returned by this lifecycle method will be passed as a parameter to
componentDidUpdate()
.
This use case is not common, but it may occur in UIs like a chat thread that need to handle scroll position in a special way.
A snapshot value (or
null
) should be returned.
For example:
class ScrollingList extends React.Component {
constructor(props) {
super(props);
this.listRef = React.createRef();
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// Are we adding new items to the list?
// Capture the scroll position so we can adjust scroll later.
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// If we have a snapshot value, we've just added new items.
// Adjust scroll so these new items don't push the old ones out of view.
// (snapshot here is the value returned from getSnapshotBeforeUpdate)
if (snapshot !== null) {
const list = this.listRef.current;
list.scrollTop = list.scrollHeight - snapshot;
}
}
render() {
return (
<div ref={this.listRef}>{/* ...contents... */}</div>
);
}
}
In the above examples, it is important to read the
scrollHeight
property in
getSnapshotBeforeUpdate
because there may be delays between “render” phase lifecycles (like
render
) and “commit” phase lifecycles (like
getSnapshotBeforeUpdate
and
componentDidUpdate
).
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.
A class component becomes an error boundary if it defines either (or both) of the lifecycle methods
static getDerivedStateFromError()
or
componentDidCatch()
. Updating state from these lifecycles lets you capture an unhandled JavaScript error in the below tree and display a fallback UI.
Only use error boundaries for recovering from unexpected exceptions; don’t try to use them for control flow.
For more details, see Error Handling in React 16 .
Note
Error boundaries only catch errors in the components below them in the tree. An error boundary can’t catch an error within itself.
static getDerivedStateFromError()
static getDerivedStateFromError(error)
This lifecycle is invoked after an error has been thrown by a descendant component.
It receives the error that was thrown as a parameter and should return a value to update state.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI. return { hasError: true }; }
render() {
if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; }
return this.props.children;
}
}
Note
getDerivedStateFromError()
is called during the “render” phase, so side-effects are not permitted.
For those use cases, usecomponentDidCatch()
instead.
componentDidCatch()
componentDidCatch(error, info)
This lifecycle is invoked after an error has been thrown by a descendant component.
It receives two parameters:
error
- The error that was thrown.
info
- An object with a
componentStack
key containing information about which component threw the error.
componentDidCatch()
is called during the “commit” phase, so side-effects are permitted.
It should be used for things like logging errors:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, info) { // Example "componentStack": // in ComponentThatThrows (created by App) // in ErrorBoundary (created by App) // in div (created by App) // in App logComponentStackToMyService(info.componentStack); }
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Production and development builds of React slightly differ in the way
componentDidCatch()
handles errors.
On development, the errors will bubble up to
window
, this means that any
window.onerror
or
window.addEventListener('error', callback)
will intercept the errors that have been caught by
componentDidCatch()
.
On production, instead, the errors will not bubble up, which means any ancestor error handler will only receive errors not explicitly caught by
componentDidCatch()
.
Note
In the event of an error, you can render a fallback UI with
componentDidCatch()
by callingsetState
, but this will be deprecated in a future release.
Usestatic getDerivedStateFromError()
to handle fallback rendering instead.
The lifecycle methods below are marked as “legacy”. They still work, but we don’t recommend using them in the new code. You can learn more about migrating away from legacy lifecycle methods in this blog post.
UNSAFE_componentWillMount()
UNSAFE_componentWillMount()
Note
This lifecycle was previously named
componentWillMount
. That name will continue to work until version 17. Use therename-unsafe-lifecycles
codemod to automatically update your components.
UNSAFE_componentWillMount()
is invoked just before mounting occurs. It is called before
render()
, therefore calling
setState()
synchronously in this method will not trigger an extra rendering. Generally, we recommend using the
constructor()
instead for initializing state.
Avoid introducing any side-effects or subscriptions in this method. For those use cases, use
componentDidMount()
instead.
This is the only lifecycle method called on server rendering.
UNSAFE_componentWillReceiveProps()
UNSAFE_componentWillReceiveProps(nextProps)
Note
This lifecycle was previously named
componentWillReceiveProps
. That name will continue to work until version 17. Use therename-unsafe-lifecycles
codemod to automatically update your components.
Note:
Using this lifecycle method often leads to bugs and inconsistencies
- If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use
componentDidUpdate
lifecycle instead.
- If you used
componentWillReceiveProps
for re-computing some data only when a prop changes , use a memoization helper instead.
- If you used
componentWillReceiveProps
to “reset” some state when a prop changes , consider either making a component fully controlled or fully uncontrolled with akey
instead.
For other use cases, follow the recommendations in this blog post about derived state.
UNSAFE_componentWillReceiveProps()
is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare
this.props
and
nextProps
and perform state transitions using
this.setState()
in this method.
Note that if a parent component causes your component to re-render, this method will be called even if props have not changed. Make sure to compare the current and next values if you only want to handle changes.
React doesn’t call
UNSAFE_componentWillReceiveProps()
with initial props during mounting. It only calls this method if some of component’s props may update. Calling
this.setState()
generally doesn’t trigger
UNSAFE_componentWillReceiveProps()
.
UNSAFE_componentWillUpdate()
UNSAFE_componentWillUpdate(nextProps, nextState)
Note
This lifecycle was previously named
componentWillUpdate
. That name will continue to work until version 17. Use therename-unsafe-lifecycles
codemod to automatically update your components.
UNSAFE_componentWillUpdate()
is invoked just before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render.
Note that you cannot call
this.setState()
here; nor should you do anything else (e.g. dispatch a Redux action) that would trigger an update to a React component before
UNSAFE_componentWillUpdate()
returns.
Typically, this method can be replaced by
componentDidUpdate()
. If you were reading from the DOM in this method (e.g. to save a scroll position), you can move that logic to
getSnapshotBeforeUpdate()
.
Note
UNSAFE_componentWillUpdate()
will not be invoked ifshouldComponentUpdate()
returns false.
Unlike the lifecycle methods above (which React calls for you), the methods below are the methods you can call from your components.
There are just two of them:
setState()
and
forceUpdate()
.
setState()
setState(updater[, callback])
setState()
enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
Think of
setState()
as a
request
rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. In the rare case that you need to force the DOM update to be applied synchronously, you may wrap it in
flushSync
, but this may hurt performance.
setState()
does not always immediately update the component. It may batch or defer the update until later. This makes reading
this.state
right after calling
setState()
a potential pitfall. Instead, use
componentDidUpdate
or a
setState
callback (
setState(updater, callback)
), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the
updater
argument below.
setState()
will always lead to a re-render unless
shouldComponentUpdate()
returns
false
. If mutable objects are being used and conditional rendering logic cannot be implemented in
shouldComponentUpdate()
, calling
setState()
only when the new state differs from the previous state will avoid unnecessary re-renders.
The first argument is an
updater
function with the signature:
(state, props) => stateChange
state
is a reference to the component state at the time the change is being applied. It should not be directly mutated. Instead, changes should be represented by building a new object based on the input from
state
and
props
. For instance, suppose we wanted to increment a value in state by
props.step
:
this.setState((state, props) => {
return {counter: state.counter + props.step};
});
Both
state
and
props
received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with
state
.
The second parameter to
setState()
is an optional callback function that will be executed once
setState
is completed and the component is re-rendered. Generally we recommend using
componentDidUpdate()
for such logic instead.
You may optionally pass an object as the first argument to
setState()
instead of a function:
setState(stateChange[, callback])
This performs a shallow merge of
stateChange
into the new state, e.g., to adjust a shopping cart item quantity:
this.setState({quantity: 2})
This form of
setState()
is also asynchronous, and multiple calls during the same cycle may be batched together. For example, if you attempt to increment an item quantity more than once in the same cycle, that will result in the equivalent of:
Object.assign(
previousState,
{quantity: state.quantity + 1},
{quantity: state.quantity + 1},
...
)
Subsequent calls will override values from previous calls in the same cycle, so the quantity will only be incremented once. If the next state depends on the current state, we recommend using the updater function form, instead:
this.setState((state) => {
return {quantity: state.quantity + 1};
});
For more detail, see:
setState()
calls batched?
this.state
updated immediately?
forceUpdate()
component.forceUpdate(callback)
By default, when your component’s state or props change, your component will re-render. If your
render()
method depends on some other data, you can tell React that the component needs re-rendering by calling
forceUpdate()
.
Calling
forceUpdate()
will cause
render()
to be called on the component, skipping
shouldComponentUpdate()
. This will trigger the normal lifecycle methods for child components, including the
shouldComponentUpdate()
method of each child. React will still only update the DOM if the markup changes.
Normally you should try to avoid all uses of
forceUpdate()
and only read from
this.props
and
this.state
in
render()
.
defaultProps
defaultProps
can be defined as a property on the component class itself, to set the default props for the class. This is used for
undefined
props, but not for
null
props. For example:
class CustomButton extends React.Component {
// ...
}
CustomButton.defaultProps = {
color: 'blue'
};
If
props.color
is not provided, it will be set by default to
'blue'
:
render() {
return <CustomButton /> ; // props.color will be set to blue
}
If
props.color
is set to
null
, it will remain
null
:
render() {
return <CustomButton color={null} /> ; // props.color will remain null
}
displayName
The
displayName
string is used in debugging messages. Usually, you don’t need to set it explicitly because it’s inferred from the name of the function or class that defines the component. You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component, see Wrap the Display Name for Easy Debugging for details.
props
this.props
contains the props that were defined by the caller of this component. See Components and Props for an introduction to props.
In particular,
this.props.children
is a special prop, typically defined by the child tags in the JSX expression rather than in the tag itself.
state
The state contains data specific to this component that may change over time. The state is user-defined, and it should be a plain JavaScript object.
If some value isn’t used for rendering or data flow (for example, a timer ID), you don’t have to put it in the state. Such values can be defined as fields on the component instance.
See State and Lifecycle for more information about the state.
Never mutate
this.state
directly, as calling
setState()
afterwards may replace the mutation you made. Treat
this.state
as if it were immutable.
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