aria-*
HTML attributes are fully supported in JSX. Whereas most DOM properties and attributes in React are camelCased, these attributes should be hyphen-cased (also known as kebab-case, lisp-case, etc) as they are in plain HTML:<input type="text" aria-label={labelText} aria-required="true" onChange={onchangeHandler}value={inputValue}name="name"/>
<div>
elements to our JSX to make our React code work, especially when working with lists (<ol>
, <ul>
and <dl>
) and the HTML <table>
. In these cases we should rather use React Fragments to group together multiple elements.function Glossary(props) { return ( <dl> {props.items.map(item => ( // Fragments should also have a
keyprop when mapping collections <Fragment key={item.id}> <dt>{item.term}</dt> <dd>{item.description}</dd> </Fragment> ))} </dl>); }
function ListItem({ item }) { return ( <> <dt>{item.term}</dt> <dd>{item.description}</dd> </> ); }
<input>
and <textarea>
, needs to be labeled accessibly. We need to provide descriptive labels that are also exposed to screen readers.for
attribute is written as htmlFor
in JSX:<label htmlFor="namedInput">Name:</label><input id="namedInput" type="text" name="name"/>
outline: 0
, if you are replacing it with another focus outline implementation.<main>
and <aside>
, to demarcate page regions as assistive technology allow the user to quickly navigate to these sections.class CustomTextInput extends React.Component { constructor(props) { super(props); // Create a ref to store the textInput DOM element this.textInput = React.createRef(); } render() { // Use the
refcallback to store a reference to the text input DOM // element in an instance field (for example, this.textInput). return ( <input type="text" ref={this.textInput} />); } }
focus() { // Explicitly focus the text input using the raw DOM API // Note: we're accessing "current" to get the DOM node this.textInput.current.focus(); }
forwardRef
function of React. If a third party HOC does not implement ref forwarding, the above pattern can still be used as a fallback.Note:While this is a very important accessibility feature, it is also a technique that should be used judiciously. Use it to repair the keyboard focus flow when it is disturbed, not to try and anticipate how users want to use applications.
click
event to the window
object that closes the popover:window
object never receives a click
event. This can lead to obscured functionality which blocks users from using your application.onBlur
and onFocus
:aria-*
props to support screen-reader users. For simplicity’s sake the keyboard events to enable arrow key
interaction of the popover options have not been implemented.<title>
to correctly describe the current page content as this ensures that the user remains aware of the current page context:Tab
and Shift+Tab
to browse.Enter
to activate elements..eslintrc
file in the root of your project with this content:aXe-core
.Note:Your bundles will end up looking a lot different than this.
import()
import()
syntax.React.lazy
Note:React.lazy and Suspense are not yet available for server-side rendering. If you want to do code-splitting in a server rendered app, we recommend Loadable Components. It has a nice guide for bundle splitting with server-side rendering.
React.lazy
function lets you render a dynamic import as a regular component.OtherComponent
when this component is first rendered.React.lazy
takes a function that must call a dynamic import()
. This must return a Promise
which resolves to a module with a default
export containing a React component.Suspense
component, which allows us to show some fallback content (such as a loading indicator) while we’re waiting for the lazy component to load.fallback
prop accepts any React elements that you want to render while waiting for the component to load. You can place the Suspense
component anywhere above the lazy component. You can even wrap multiple lazy components with a single Suspense
component.React.lazy
.React.lazy
currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that tree shaking keeps working and that you don’t pull in unused components.Page
component that passes a user
and avatarSize
prop several levels down so that deeply nested Link
and Avatar
components can read it:user
and avatarSize
props through many levels if in the end only the Avatar
component really needs it. It’s also annoying that whenever the Avatar
component needs more props from the top, you have to add them at all the intermediate levels too.Avatar
component itself so that the intermediate components don’t need to know about the user
or avatarSize
props:Link
and Avatar
components’ use of user
and avatarSize
.React.createContext
Provider
above it in the tree.defaultValue
argument is only used when a component does not have a matching Provider above it in the tree. This default value can be helpful for testing components in isolation without wrapping them. Note: passing undefined
as a Provider value does not cause consuming components to use defaultValue
.Context.Provider
value
prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.value
prop changes. The propagation from Provider to its descendant consumers (including [.contextType](<https://reactjs.org/docs/context.html#classcontexttype>)
and [useContext](<https://reactjs.org/docs/hooks-reference.html#usecontext>)
) is not subject to the shouldComponentUpdate
method, so the consumer is updated even when an ancestor component skips an update.[Object.is](<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#Description>)
.NoteThe way changes are determined can cause some issues when passing objects as value: see Caveats.
Class.contextType
contextType
property on a class can be assigned a Context object created by [React.createContext()](<https://reactjs.org/docs/context.html#reactcreatecontext>)
. Using this property lets you consume the nearest current value of that Context type using this.context
. You can reference this in any of the lifecycle methods including the render function.Note:You can only subscribe to a single context using this API. If you need to read more than one see Consuming Multiple Contexts.If you are using the experimental public class fields syntax, you can use a static class field to initialize your contextType.
Context.Consumer
value
argument passed to the function will be equal to the value
prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the value
argument will be equal to the defaultValue
that was passed to createContext()
.NoteFor more information about the ‘function as a child’ pattern, see render props.
Context.displayName
displayName
string property. React DevTools uses this string to determine what to display for the context.value
:NoteReact previously shipped with an experimental context API. The old API will be supported in all 16.x releases, but applications using it should migrate to the new version. The legacy API will be removed in a future major React version. Read the legacy context docs here.
<Columns />
would need to return multiple <td>
elements in order for the rendered HTML to be valid. If a parent div was used inside the render()
of <Columns />
, then the resulting HTML will be invalid.<Table />
output of:<Table />
output of:<></>
the same way you’d use any other element except that it doesn’t support keys or attributes.<React.Fragment>
syntax may have keys. A use case for this is mapping a collection to an array of fragments — for example, to create a description list:key
is the only attribute that can be passed to Fragment
. In the future, we may add support for additional attributes, such as event handlers.const EnhancedComponent = higherOrderComponent(WrappedComponent);
[connect](<https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#connect>)
and Relay’s [createFragmentContainer](<https://relay.dev/docs/v10.1.3/fragment-container/#createfragmentcontainer>)
.NoteWe previously recommended mixins as a way to handle cross-cutting concerns. We’ve since realized that mixins create more trouble than they are worth. Read more about why we’ve moved away from mixins and how you can transition your existing components.
CommentList
component that subscribes to an external data source to render a list of comments:CommentList
and BlogPost
aren’t identical — they call different methods on DataSource
, and they render different output. But much of their implementation is the same:DataSource
.setState
whenever the data source changes.DataSource
and calling setState
will occur over and over again. We want an abstraction that allows us to define this logic in a single place and share it across many components. This is where higher-order components excel.CommentList
and BlogPost
, that subscribe to DataSource
. The function will accept as one of its arguments a child component that receives the subscribed data as a prop. Let’s call the function withSubscription
:DataSource
and the current props.CommentListWithSubscription
and BlogPostWithSubscription
are rendered, CommentList
and BlogPost
will be passed a data
prop with the most current data retrieved from DataSource
:data
, which it uses to render its output. The HOC isn’t concerned with how or why the data is used, and the wrapped component isn’t concerned with where the data came from.withSubscription
is a normal function, you can add as many or as few arguments as you like. For example, you may want to make the name of the data
prop configurable, to further isolate the HOC from the wrapped component. Or you could accept an argument that configures shouldComponentUpdate
, or one that configures the data source. These are all possible because the HOC has full control over how the component is defined.withSubscription
and the wrapped component is entirely props-based. This makes it easy to swap one HOC for a different one, as long as they provide the same props to the wrapped component. This may be useful if you change data-fetching libraries, for example.EnhancedComponent
that also mutates componentDidUpdate
, the first HOC’s functionality will be overridden! This HOC also won’t work with function components, which do not have lifecycle methods.connect
is a higher-order function that returns a higher-order component!connect
function have the signature Component => Component
. Functions whose output type is the same as its input type are really easy to compose together.connect
and other enhancer-style HOCs to be used as decorators, an experimental JavaScript proposal.)withSubscription
, and the wrapped component’s display name is CommentList
, use the display name WithSubscription(CommentList)
:render
is identical (===
) to the component from the previous render, React recursively updates the subtree by diffing it with the new one. If they’re not equal, the previous subtree is unmounted completely.getFragment
to facilitate the composition of GraphQL fragments.ref
is not really a prop — like key
, it’s handled specially by React. If you add a ref to an element whose component is the result of a HOC, the ref refers to an instance of the outermost container component, not the wrapped component.React.forwardRef
API (introduced with React 16.3). Learn more about it in the forwarding refs section.React.createElement(component, props, ...children)
function. The JSX code:<Foo />
expression, Foo
must be in scope.React.createElement
, the React
library must also always be in scope from your JSX code.React
and CustomButton
are not directly referenced from JavaScript:<script>
tag, it is already in scope as the React
global.MyComponents.DatePicker
is a component, you can use it directly from JSX with:<div>
or <span>
and results in a string 'div'
or 'span'
passed to React.createElement
. Types that start with a capital letter like <Foo />
compile to React.createElement(Foo)
and correspond to a component defined or imported in your JavaScript file.hello
to Hello
and use <Hello />
when referring to it:{}
. For example, in this JSX:<MyComponent foo={1 + 2 + 3 + 4} />
MyComponent
, the value of props.foo
will be 10
because the expression 1 + 2 + 3 + 4
gets evaluated.if
statements and for
loops are not expressions in JavaScript, so they can’t be used in JSX directly. Instead, you can put these in the surrounding code. For example:<MyComponent message="hello world" /><MyComponent message={'hello world'} />
<MyComponent message="<3" /><MyComponent message={'<3'} />
true
. These two JSX expressions are equivalent:<MyTextBox autocomplete /><MyTextBox autocomplete={true} />
{foo}
which is short for {foo: foo}
rather than {foo: true}
. This behavior is just there so that it matches the behavior of HTML.props
as an object, and you want to pass it in JSX, you can use ...
as a “spread” operator to pass the whole props object. These two components are equivalent:kind
prop is safely consumed and is not passed on to the <button>
element in the DOM. All other props are passed via the ...other
object making this component really flexible. You can see that it passes an onClick
and children
props.props.children
. There are several different ways to pass children:props.children
will just be that string. This is useful for many of the built-in HTML elements. For example:<MyComponent>Hello world!</MyComponent>
props.children
in MyComponent
will simply be the string "Hello world!"
. HTML is unescaped, so you can generally write JSX just like you would write HTML in this way:<div>This is valid HTML & JSX at the same time.</div>
render() { // No need to wrap list items in an extra element! return [ // Don't forget the keys :) <li key="A">First item</li>, <li key="B">Second item</li>, <li key="C">Third item</li>, ]; }
{}
. For example, these expressions are equivalent:<MyComponent>foo</MyComponent><MyComponent>{'foo'}</MyComponent>
props.children
works just like any other prop in that it can pass any sort of data, not just the sorts that React knows how to render. For example, if you have a custom component, you could have it take a callback as props.children
:false
, null
, undefined
, and true
are valid children. They simply don’t render. These JSX expressions will all render to the same thing:<Header />
component only if showHeader
is true
:0
number, are still rendered by React. For example, this code will not behave as you might expect because 0
will be printed when props.messages
is an empty array:&&
is always boolean:false
, true
, null
, or undefined
to appear in the output, you have to convert it to a string first:build/
folder of your project.npm start
..production.min.js
are suitable for production.[terser-brunch](<https://github.com/brunch/terser-brunch>)
plugin:-p
flag to the build
command:-p
flag or apply this plugin in development, because it will hide useful React warnings and make the builds much slower.[envify](<https://github.com/hughsk/envify>)
transform ensures the right build environment is set. Make it global (g
).[uglifyify](<https://github.com/hughsk/uglifyify>)
transform removes development imports. Make it global too (g
).[terser](<https://github.com/terser-js/terser>)
for mangling (read why).[replace](<https://github.com/rollup/rollup-plugin-replace>)
plugin ensures the right build environment is set.[commonjs](<https://github.com/rollup/rollup-plugin-commonjs>)
plugin provides support for CommonJS in Rollup.[terser](<https://github.com/TrySound/rollup-plugin-terser>)
plugin compresses and mangles the final bundle.terser
plugin or the replace
plugin with 'production'
value in development because they will hide useful React warnings, and make the builds much slower.Note:If you’re using Create React App, please follow the instructions above.This section is only relevant if you configure webpack directly.
TerserPlugin
in development because it will hide useful React warnings, and make the builds much slower.react-dom
16.5+ and react-native
0.57+ provide enhanced profiling capabilities in DEV mode with the React DevTools Profiler. An overview of the Profiler can be found in the blog post “Introducing the React Profiler”. A video walkthrough of the profiler is also available on YouTube.NoteA production profiling bundle of react-dom is also available as react-dom/profiling. Read more about how to use this bundle at fb.me/react-profiling
NoteBefore React 17, we use the standard User Timing API to profile components with the chrome performance tab. For a more detailed walkthrough, check out this article by Ben Schwarz.
shouldComponentUpdate
, which is triggered before the re-rendering process starts. The default implementation of this function returns true
, leaving React to perform the update:false
from shouldComponentUpdate
instead, to skip the whole rendering process, including calling render()
on this component and below.shouldComponentUpdate()
by hand, you can inherit from [React.PureComponent](<https://reactjs.org/docs/react-api.html#reactpurecomponent>)
. It is equivalent to implementing shouldComponentUpdate()
with a shallow comparison of current and previous props and state.SCU
indicates what shouldComponentUpdate
returned, and vDOMEq
indicates whether the rendered React elements were equivalent. Finally, the circle’s color indicates whether the component had to be reconciled or not.shouldComponentUpdate
returned false
for the subtree rooted at C2, React did not attempt to render C2, and thus didn’t even have to invoke shouldComponentUpdate
on C4 and C5.shouldComponentUpdate
returned true
, so React had to go down to the leaves and check them. For C6 shouldComponentUpdate
returned true
, and since the rendered elements weren’t equivalent React had to update the DOM.shouldComponentUpdate
, and render
was not called.props.color
or the state.count
variable changes, you could have shouldComponentUpdate
check that:shouldComponentUpdate
is just checking if there is any change in props.color
or state.count
. If those values don’t change, the component doesn’t update. If your component got more complex, you could use a similar pattern of doing a “shallow comparison” between all the fields of props
and state
to determine if the component should update. This pattern is common enough that React provides a helper to use this logic - just inherit from React.PureComponent
. So this code is a simpler way to achieve the same thing:React.PureComponent
instead of writing your own shouldComponentUpdate
. It only does a shallow comparison, so you can’t use it if the props or state may have been mutated in a way that a shallow comparison would miss.ListOfWords
component to render a comma-separated list of words, with a parent WordAdder
component that lets you click a button to add a word to the list. This code does not work correctly:PureComponent
will do a simple comparison between the old and new values of this.props.words
. Since this code mutates the words
array in the handleClick
method of WordAdder
, the old and new values of this.props.words
will compare as equal, even though the actual words in the array have changed. The ListOfWords
will thus not update even though it has new words that should be rendered.handleClick
method above could be rewritten using concat
as:colormap
and we want to write a function that changes colormap.right
to be 'blue'
. We could write:function updateColorMap(colormap) { colormap.right = 'blue'; }
updateColorMap
now returns a new object, rather than mutating the old one. Object.assign
is in ES6 and requires a polyfill.Object.assign
and the object spread syntax are available by default.<p>
.<Mouse>
component that encapsulates the behavior we need to reuse elsewhere.<Mouse>
component encapsulates all behavior associated with listening for mousemove
events and storing the (x, y) position of the cursor, but it’s not yet truly reusable.<Cat>
component that renders the image of a cat chasing the mouse around the screen. We might use a <Cat mouse={{ x, y }}>
prop to tell the component the coordinates of the mouse so it knows where to position the image on the screen.<Cat>
inside <Mouse>
’s render
method, like this:<MouseWithCat>
) that renders something specifically for that use case.<Cat>
inside a <Mouse>
component, and effectively changing its rendered output, we can provide <Mouse>
with a function prop that it uses to dynamically determine what to render–a render prop.<Mouse>
component and hard-coding something else in its render
method to solve for a specific use case, we provide a render
prop that <Mouse>
can use to dynamically determine what it renders.<Mouse>
with a render
prop that tells it what to render with the current (x, y) of the cursor.withMouse
HOC instead of a <Mouse>
component, you could easily create one using a regular <Mouse>
with a render prop:render
render
to use this pattern. In fact, *any* prop that is a function that a component uses to know what to render is technically a “render prop”.render
, we could just as easily use the children
prop!children
prop doesn’t actually need to be named in the list of “attributes” in your JSX element. Instead, you can put it directly inside the element!children
should be a function in your propTypes
when designing an API like this.[React.PureComponent](<https://reactjs.org/docs/react-api.html#reactpurecomponent>)
if you create the function inside a render
method. This is because the shallow prop comparison will always return false
for new props, and each render
in this case will generate a new value for the render prop.<Mouse>
component from above, if Mouse
were to extend React.PureComponent
instead of React.Component
, our example would look like this:<MouseTracker>
renders, it generates a new function as the value of the <Mouse render>
prop, thus negating the effect of <Mouse>
extending React.PureComponent
in the first place!<Mouse>
should extend React.Component
instead.