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:
checked
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.
className
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
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:
Since
for
is a reserved word in JavaScript, React elements use
htmlFor
instead.
onChange
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.
selected
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.
style
Note
Some examples in the documentation use
style
for convenience, but
using the
style
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:
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 };
functionComponentWithTransition(){ return<divstyle={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' <divstyle={{height:10}}> Hello World! </div>
// Result style: '10%' <divstyle={{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.
suppressContentEditableWarning
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.
suppressHydrationWarning
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.
value
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.
All Supported HTML Attributes
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:
<divtabIndex={-1}/>// Just like node.tabIndex DOM API <divclassName="Button"/>// Just like node.className DOM API <inputreadOnly={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:
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 voidpreventDefault() boolean isDefaultPrevented() voidstopPropagation() boolean isPropagationStopped() voidpersist() DOMEventTarget target number timeStamp string type
Note:
As of v17,
e.persist()
doesn’t do anything because the
SyntheticEvent
is no longer pooled.
Note:
As of v0.14, returning
false
from an event handler will no longer stop event propagation. Instead,
e.stopPropagation()
or
e.preventDefault()
should be triggered manually, as appropriate.
Supported Events
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.
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.
Focus Events
Event names:
onFocus onBlur
These focus events work on all elements in the React DOM, not just form elements.
Properties:
DOMEventTarget relatedTarget
onFocus
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.
functionExample(){ return( <input onFocus={(e)=>{ console.log('Focused on input'); }} placeholder="onFocus is triggered when you click this input." /> ) }
onBlur
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.
functionExample(){ 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." /> ) }
Detecting Focus Entering and Leaving
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.
functionExample(){ 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'); } }} > <inputid="1"/> <inputid="2"/> </div> ); }
Form Events
Event names:
onChange onInput onInvalid onReset onSubmit
For more information about the onChange event, see Forms.
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
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.
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
Wheel Events
Event names:
onWheel
Properties:
number deltaMode number deltaX number deltaY number deltaZ
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
Reference
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 an
act
export that behaves the same way.
For example, let’s say we have this
Counter
component:
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(newMouseEvent('click',{bubbles:true}));});expect(label.textContent).toBe('You clicked 1 times'); expect(document.title).toBe('You clicked 1 times'); });
Don’t forget that dispatching DOM events only works when the DOM container is added to the
document
. You can use a library like React Testing Library to reduce the boilerplate code.
The
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 using
jest.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.
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.
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.
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:
You will need to have
window
,
window.document
and
window.document.createElement
globally available
before
you import
React
. Otherwise React will think it can’t access the DOM and methods like
setState
won’t work.
Other Utilities
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.
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.
This package provides a React renderer that can be used to render React components to pure JavaScript objects, without depending on the DOM or a native mobile environment.
Essentially, this package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a React DOM or React Native component without using a browser or jsdom.
You can use Jest’s snapshot testing feature to automatically save a copy of the JSON tree to a file and check in your tests that it hasn’t changed: Learn more about it.
You can also traverse the output to find specific nodes and make assertions about them.
Create a
TestRenderer
instance with the passed React element. It doesn’t use the real DOM, but it still fully renders the component tree into memory so you can make assertions about it. Returns a TestRenderer instance.
TestRenderer.act()
TestRenderer.act(callback);
Similar to the
act()
helper from
react-dom/test-utils
,
TestRenderer.act
prepares a component for assertions. Use this version of
act()
to wrap calls to
TestRenderer.create
and
testRenderer.update
.
import{create, act}from'react-test-renderer'; import App from'./app.js';// The component being tested
// render the component let root; act(()=>{ root =create(<Appvalue={1}/>) });
// make assertions on root expect(root.toJSON()).toMatchSnapshot();
// update with some different props act(()=>{ root.update(<Appvalue={2}/>); })
// make assertions on root expect(root.toJSON()).toMatchSnapshot();
testRenderer.toJSON()
testRenderer.toJSON()
Return an object representing the rendered tree. This tree only contains the platform-specific nodes like
<div>
or
<View>
and their props, but doesn’t contain any user-written components. This is handy for snapshot testing.
testRenderer.toTree()
testRenderer.toTree()
Return an object representing the rendered tree. The representation is more detailed than the one provided by
toJSON()
, and includes the user-written components. You probably don’t need this method unless you’re writing your own assertion library on top of the test renderer.
testRenderer.update()
testRenderer.update(element)
Re-render the in-memory tree with a new root element. This simulates a React update at the root. If the new element has the same type and key as the previous element, the tree will be updated; otherwise, it will re-mount a new tree.
testRenderer.unmount()
testRenderer.unmount()
Unmount the in-memory tree, triggering the appropriate lifecycle events.
testRenderer.getInstance()
testRenderer.getInstance()
Return the instance corresponding to the root element, if available. This will not work if the root element is a function component because they don’t have instances.
testRenderer.root
testRenderer.root
Returns the root “test instance” object that is useful for making assertions about specific nodes in the tree. You can use it to find other “test instances” deeper below.
testInstance.find()
testInstance.find(test)
Find a single descendant test instance for which
test(testInstance)
returns
true
. If
test(testInstance)
does not return
true
for exactly one test instance, it will throw an error.
testInstance.findByType()
testInstance.findByType(type)
Find a single descendant test instance with the provided
type
. If there is not exactly one test instance with the provided
type
, it will throw an error.
testInstance.findByProps()
testInstance.findByProps(props)
Find a single descendant test instance with the provided
props
. If there is not exactly one test instance with the provided
props
, it will throw an error.
testInstance.findAll()
testInstance.findAll(test)
Find all descendant test instances for which
test(testInstance)
returns
true
.
testInstance.findAllByType()
testInstance.findAllByType(type)
Find all descendant test instances with the provided
type
.
testInstance.findAllByProps()
testInstance.findAllByProps(props)
Find all descendant test instances with the provided
props
.
testInstance.instance
testInstance.instance
The component instance corresponding to this test instance. It is only available for class components, as function components don’t have instances. It matches the
this
value inside the given component.
testInstance.type
testInstance.type
The component type corresponding to this test instance. For example, a
<Button />
component has a type of
Button
.
testInstance.props
testInstance.props
The props corresponding to this test instance. For example, a
<Button size="small" />
component has
{size: 'small'}
as props.
testInstance.parent
testInstance.parent
The parent test instance of this test instance.
testInstance.children
testInstance.children
The children test instances of this test instance.
Ideas
You can pass
createNodeMock
function to
TestRenderer.create
as the option, which allows for custom mock refs.
createNodeMock
accepts the current element and should return a mock ref object.
This is useful when you test a component that relies on refs.
React 18 supports all modern browsers (Edge, Firefox, Chrome, Safari, etc).
If you support older browsers and devices such as Internet Explorer which do not provide modern browser features natively or have non-compliant implementations, consider including a global polyfill in your bundled application.
Here is a list of the modern features React 18 uses:
The correct polyfill for these features depend on your environment. For many users, you can configure your Browserlist settings. For others, you may need to import polyfills like
core-js
directly.
A single-page application is an application that loads a single HTML page and all the necessary assets (such as JavaScript and CSS) required for the application to run. Any interactions with the page or subsequent pages do not require a round trip to the server which means the page is not reloaded.
Though you may build a single-page application in React, it is not a requirement. React can also be used for enhancing small parts of existing websites with additional interactivity. Code written in React can coexist peacefully with markup rendered on the server by something like PHP, or with other client-side libraries. In fact, this is exactly how React is being used at Facebook.
ES6, ES2015, ES2016, etc
These acronyms all refer to the most recent versions of the ECMAScript Language Specification standard, which the JavaScript language is an implementation of. The ES6 version (also known as ES2015) includes many additions to the previous versions such as: arrow functions, classes, template literals,
let
and
const
statements. You can learn more about specific versions here.
Compilers
A JavaScript compiler takes JavaScript code, transforms it and returns JavaScript code in a different format. The most common use case is to take ES6 syntax and transform it into syntax that older browsers are capable of interpreting. Babel is the compiler most commonly used with React.
Bundlers
Bundlers take JavaScript and CSS code written as separate modules (often hundreds of them), and combine them together into a few files better optimized for the browsers. Some bundlers commonly used in React applications include Webpack and Browserify.
Package Managers
Package managers are tools that allow you to manage dependencies in your project. npm and Yarn are two package managers commonly used in React applications. Both of them are clients for the same npm package registry.
CDN
CDN stands for Content Delivery Network. CDNs deliver cached, static content from a network of servers across the globe.
JSX
JSX is a syntax extension to JavaScript. It is similar to a template language, but it has full power of JavaScript. JSX gets compiled to
React.createElement()
calls which return plain JavaScript objects called “React elements”. To get a basic introduction to JSX see the docs here and find a more in-depth tutorial on JSX here.
React DOM uses camelCase property naming convention instead of HTML attribute names. For example,
tabindex
becomes
tabIndex
in JSX. The attribute
class
is also written as
className
since
class
is a reserved word in JavaScript:
<h1className="hello">My name is Clementine!</h1>
Elements
React elements are the building blocks of React applications. One might confuse elements with a more widely known concept of “components”. An element describes what you want to see on the screen. React elements are immutable.
const element =<h1>Hello, world</h1>;
Typically, elements are not used directly, but get returned from components.
Components
React components are small, reusable pieces of code that return a React element to be rendered to the page. The simplest version of React component is a plain JavaScript function that returns a React element:
Components can be broken down into distinct pieces of functionality and used within other components. Components can return other components, arrays, strings and numbers. A good rule of thumb is that if a part of your UI is used several times (Button, Panel, Avatar), or is complex enough on its own (App, FeedStory, Comment), it is a good candidate to be a reusable component. Component names should also always start with a capital letter (
<Wrapper/>
not
<wrapper/>
). See this documentation for more information on rendering components.
props
props
are inputs to a React component. They are data passed down from a parent component to a child component.
Remember that
props
are readonly. They should not be modified in any way:
// Wrong! props.number =42;
If you need to modify some value in response to user input or a network response, use
state
instead.
props.children
props.children
is available on every component. It contains the content between the opening and closing tags of a component. For example:
<Welcome>Hello world!</Welcome>
The string
Hello world!
is available in
props.children
in the
Welcome
component:
A component needs
state
when some data associated with it changes over time. For example, a
Checkbox
component might need
isChecked
in its state, and a
NewsFeed
component might want to keep track of
fetchedPosts
in its state.
The most important difference between
state
and
props
is that
props
are passed from a parent component, but
state
is managed by the component itself. A component cannot change its
props
, but it can change its
state
.
For each particular piece of changing data, there should be just one component that “owns” it in its state. Don’t try to synchronize states of two different components. Instead, lift it up to their closest shared ancestor, and pass it down as props to both of them.
Lifecycle Methods
Lifecycle methods are custom functionality that gets executed during the different phases of a component. There are methods available when the component gets created and inserted into the DOM (mounting), when the component updates, and when the component gets unmounted or removed from the DOM.
Controlled vs. Uncontrolled Components
React has two different approaches to dealing with form inputs.
An input form element whose value is controlled by React is called a
controlled component
. When a user enters data into a controlled component a change event handler is triggered and your code decides whether the input is valid (by re-rendering with the updated value). If you do not re-render then the form element will remain unchanged.
An
uncontrolled component
works like form elements do outside of React. When a user inputs data into a form field (an input box, dropdown, etc) the updated information is reflected without React needing to do anything. However, this also means that you can’t force the field to have a certain value.
In most cases you should use controlled components.
Keys
A “key” is a special string attribute you need to include when creating arrays of elements. Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside an array to give the elements a stable identity.
Keys only need to be unique among sibling elements in the same array. They don’t need to be unique across the whole application or even a single component.
Don’t pass something like
Math.random()
to keys. It is important that keys have a “stable identity” across re-renders so that React can determine when items are added, removed, or re-ordered. Ideally, keys should correspond to unique and stable identifiers coming from your data, such as
post.id
.
Refs
React supports a special attribute that you can attach to any component. The
ref
attribute can be an object created by
React.createRef()
function or a callback function, or a string (in legacy API). When the
ref
attribute is a callback function, the function receives the underlying DOM element or class instance (depending on the type of element) as its argument. This allows you to have direct access to the DOM element or component instance.
Use refs sparingly. If you find yourself often using refs to “make things happen” in your app, consider getting more familiar with top-down data flow.
Events
Handling events with React elements has some syntactic differences:
React event handlers are named using camelCase, rather than lowercase.
With JSX you pass a function as the event handler, rather than a string.
Reconciliation
When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one. When they are not equal, React will update the DOM. This process is called “reconciliation”.