{"_id":"doc-en-react-8faba1735f6b2d17744137e2793573e876d08674a943e100ee050b84816a75af","title":"","text":"function getJSReport(browser){ return browser .waitForCondition(\"typeof window.jasmine != 'undefined'\", 5e3) .waitFor(wd.asserters.jsCondition(\"typeof window.jasmine != 'undefined'\"), 5e3, 50) .fail(function(error){ throw Error(\"The test page didn't load properly. \" + error); }) .waitForCondition(\"typeof window.jasmine.getJSReport != 'undefined'\", 10e3) .waitForCondition(\"window.postDataToURL.running <= 0\", 30e3) .waitFor(wd.asserters.jsCondition(\"typeof window.jasmine.getJSReport != 'undefined'\"), 60e3, 100) .waitFor(wd.asserters.jsCondition(\"window.postDataToURL.running <= 0\"), 30e3, 500) .eval(\"jasmine.getJSReport().passed\"); }"} {"_id":"doc-en-react-4734459bb16532eb5aafa8f3bbb5dd04693fbfbd22abcd7e1fb13c89b20cc667","title":"","text":"urls.unshift('../node_modules/es5-shim/es5-shim.js'); } var cacheBust = '?_=' + Date.now().toString(36); var cacheBust = '?_=' + (+new Date).toString(36); for (var urls_index = -1, urls_length = urls.length; ++urls_index < urls_length;) { document.write('');"} {"_id":"doc-en-react-3007f0673be52064524a00db56e1c9591a291cecd9b1d55e789410281772ed12","title":"","text":"* @protected */ setState: function(partialState, callback) { invariant( typeof partialState === 'object' || partialState == null, 'setState(...): takes an object of state variables to update.' ); if (__DEV__){ if (partialState == null) { console.warn( 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().' ); } } // Merge with `_pendingState` if it exists, otherwise with existing state. this.replaceState( merge(this._pendingState || this.state, partialState),"} {"_id":"doc-en-react-bf5798b90c09f75d39944d2b957e97fc266706845ce1d800e084eabfffafd0d5","title":"","text":"checkMergeArrayArgs: function(one, two) { invariant( Array.isArray(one) && Array.isArray(two), 'Critical assumptions about the merge functions have been violated. ' + 'This is the fault of the merge functions themselves, not necessarily ' + 'the callers.' 'Tried to merge arrays, instead got %s and %s.', one, two ); },"} {"_id":"doc-en-react-27ce1f5c9dc1f4b83ec14da9bdb62fb7c8e671e4406e25c42cdaee2a7bc06ea0","title":"","text":"checkMergeObjectArg: function(arg) { invariant( !isTerminal(arg) && !Array.isArray(arg), 'Critical assumptions about the merge functions have been violated. ' + 'This is the fault of the merge functions themselves, not necessarily ' + 'the callers.' 'Tried to merge an object, instead got %s.', arg ); },"} {"_id":"doc-en-react-cec87f280fa9de2093b22995f60bc68c6f34138f838f6de2034bd3beca51ce39","title":"","text":"* CSS properties which accept numbers but are not in units of \"px\". */ var isUnitlessNumber = { columnCount: true, fillOpacity: true, flex: true, flexGrow: true, flexShrink: true, fontWeight: true, lineHeight: true, opacity: true, order: true, orphans: true, pitchRange: true, richness: true, stress: true, volume: true, widows: true, zIndex: true, zoom: true };"} {"_id":"doc-en-react-50d5598a1ecf06b53398ae235a982412740b4603ea301eacccd3469d4802bd3d","title":"","text":"}); it('should not append `px` to styles that might need a number', function() { expect(CSSPropertyOperations.createMarkupForStyles({ fillOpacity: 1, fontWeight: 2, opacity: 3, orphans: 4, zIndex: 5, zoom: 6, lineHeight: 7 })).toBe( 'fill-opacity:1;font-weight:2;opacity:3;orphans:4;z-index:5;zoom:6;' + 'line-height:7;' ); var unitlessProperties = [ 'columnCount', 'fillOpacity', 'flex', 'flexGrow', 'flexShrink', 'fontWeight', 'lineHeight', 'opacity', 'order', 'orphans', 'pitchRange', 'richness', 'stress', 'volume', 'widows', 'zIndex', 'zoom' ]; unitlessProperties.forEach(function(property) { var styles = {}; styles[property] = 1; expect(CSSPropertyOperations.createMarkupForStyles(styles)) .toMatch(/:1;$/); }); }); it('should set style attribute when styles exist', function() {"} {"_id":"doc-en-react-67f9022d491ffeba0e3f72f5cd6879bf0df3b76370ab9dbcfaf7a50cc425e302","title":"","text":"\"url\": \"https://github.com/facebook/react\" }, \"dependencies\": { \"commoner\": \"~0.8.14\", \"commoner\": \"~0.9.0\", \"esprima-fb\": \"~2001.1001.0-dev-harmony-fb\", \"jstransform\": \"~2.0.2\" },"} {"_id":"doc-en-react-86fa3b086bf47779ea8ba228dbf7f456a53f187ff313c418f4b2489d7df5dac8","title":"","text":"var mocks = require('mocks'); var ExecutionEnvironment; var React; var ReactMarkupChecksum; var ReactMount; var ReactReconcileTransaction; var ReactTestUtils; var ReactServerRendering; var ReactMarkupChecksum; var ExecutionEnvironment; var ID_ATTRIBUTE_NAME;"} {"_id":"doc-en-react-8c6664b9dd18238c386e8388cca596d050fb9e678aa76b4b382edadcadedbbca","title":"","text":"beforeEach(function() { require('mock-modules').dumpCache(); React = require('React'); ReactMarkupChecksum = require('ReactMarkupChecksum'); ReactMount = require('ReactMount'); ReactTestUtils = require('ReactTestUtils'); ReactReconcileTransaction = require('ReactReconcileTransaction'); ExecutionEnvironment = require('ExecutionEnvironment'); ExecutionEnvironment.canUseDOM = false; ReactServerRendering = require('ReactServerRendering'); ReactMarkupChecksum = require('ReactMarkupChecksum'); var DOMProperty = require('DOMProperty'); ID_ATTRIBUTE_NAME = DOMProperty.ID_ATTRIBUTE_NAME;"} {"_id":"doc-en-react-e4c9f26c4e027620bdc25234dd0ae617a2ff1a3f0a3e30f84a9348766a1ebba4","title":"","text":"'a valid ReactComponent.' ); }); it('allows setState in componentWillMount without using DOM', function() { var Component = React.createClass({ componentWillMount: function() { this.setState({text: 'hello, world'}); }, render: function() { return
{this.state.text}
; } }); ReactReconcileTransaction.prototype.perform = function() { // We shouldn't ever be calling this on the server throw new Error('Browser reconcile transaction should not be used'); }; var markup = ReactServerRendering.renderComponentToString( ); expect(markup.indexOf('hello, world') >= 0).toBe(true); });
}); });"} {"_id":"doc-en-react-6c7a2ea2f7d9ce914e550371efb098fce8d41bd239c8399a12042b1d80379459","title":"","text":"// componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks. while (dirtyComponents.length) { var allUnmounted = true; for (var i = 0, l = dirtyComponents.length; i < l; i++) { if (dirtyComponents[i].isMounted()) { allUnmounted = false; break; } } if (allUnmounted) { // All the \"dirty\" components are unmounted, which probably means that // they were marked dirty due to setState calls in componentWillMount // handlers and the components are currently in the process of mounting. // `runBatchedUpdates` will be a noop. In that case, initializing the // DOM-dependent ReactReconcileTransaction is thus not what we want to // do, especially when using server rendering, so we skip it. dirtyComponents.length = 0; return; } var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction);"} {"_id":"doc-en-react-da82db36cff2f8fd8a79f4f349eaa280e9ab783ad80f56092dd2a24e1dac0c82","title":"","text":"* **Computed data:** Don't worry about precomputing values based on state — it's easier to ensure that your UI is consistent if you do all computation within `render()`. For example, if you have an array of list items in state and you want to render the count as a string, simply render `this.state.listItems.length + ' list items'` in your `render()` method rather than storing it on state. * **React components:** Build them in `render()` based on underlying props and state. * **Duplicated data from props:** Try to use props as the source of truth where possible. Because props can change over time, it's appropriate to store props in state to be able to know its previous values. * **Duplicated data from props:** Try to use props as the source of truth where possible. One valid use to store props in state is to be able to know it's previous values, because props can change over time. "} {"_id":"doc-en-react-e4f795e1235ca92806e674ac5b38f4fc9f8c66b295cbefb2ad5b77e4d6552175","title":"","text":"invariant( one[key] === undefined, 'mergeObjectsWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: %s', 'Tried to merge two objects with the same key: `%s`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.', key ); one[key] = value;"} {"_id":"doc-en-react-4134d81734458406d3b456b46dcc61bd82b5668ca375b3bf775b2c2bb168855a","title":"","text":"instance = ReactTestUtils.renderIntoDocument(instance); }).toThrow( 'Invariant Violation: mergeObjectsWithNoDuplicateKeys(): ' + 'Tried to merge two objects with the same key: x' 'Tried to merge two objects with the same key: `x`. This conflict ' + 'may be due to a mixin; in particular, this may be caused by two ' + 'getInitialState() or getDefaultProps() methods returning objects ' + 'with clashing keys.' ); });"} {"_id":"doc-en-react-d664c9c45770d6e9f28a6f5e6e8e0d6090c2c2e680103ebecfb53a558305bce9","title":"","text":" /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; require('mock-modules') .dontMock('shallowEqual'); var shallowEqual; describe('shallowEqual', function() { beforeEach(function() { shallowEqual = require('shallowEqual'); }); it('returns false if either argument is null', function() { expect(shallowEqual(null, {})).toBe(false); expect(shallowEqual({}, null)).toBe(false); }); it('returns true if both arguments are null or undefined', function() { expect(shallowEqual(null, null)).toBe(true); expect(shallowEqual(undefined, undefined)).toBe(true); }); it('returns true if arguments are shallow equal', function() { expect( shallowEqual( {a: 1, b: 2, c: 3}, {a: 1, b: 2, c: 3} ) ).toBe(true); }); it('returns false if first argument has too many keys', function() { expect( shallowEqual( {a: 1, b: 2, c: 3}, {a: 1, b: 2} ) ).toBe(false); }); it('returns false if second argument has too many keys', function() { expect( shallowEqual( {a: 1, b: 2}, {a: 1, b: 2, c: 3} ) ).toBe(false); }); it('returns false if arguments are not shallow equal', function() { expect( shallowEqual( {a: 1, b: 2, c: {}}, {a: 1, b: 2, c: {}} ) ).toBe(false); }); }); "} {"_id":"doc-en-react-8f0f6eb1846a5dbcf8f6f26b72dbb7162700a5dbaaede96d44f06a563947b22e","title":"","text":"if (objA === objB) { return true; } if (!objA || !objB) { return false; } var key; // Test for A's keys different from B. for (key in objA) {"} {"_id":"doc-en-react-89f6ad41bb608aa76e5bfa8a414adf2c3657357b5cf38c787f2ac010ca54b5d1","title":"","text":"

HTML to JSX Compiler

"} {"_id":"doc-en-react-3f4c65c191b8b02a4ff276369801d4c4ada1f6a7904f8a9548b5f851a2dfc433","title":"","text":"}, \"preferGlobal\": true, \"commonerConfig\": { \"version\": 6 \"version\": 7 }, \"scripts\": { \"test\": \"jest\","} {"_id":"doc-en-react-9cff522cafc943cbeed3a28cfd651ce73b7407f275a210ecd0e90ca2f666690d","title":"","text":"CallExpression: { exit: function(node, parent) { if (this.get('callee').isIdentifier({name: 'invariant'})) { // Truncate the arguments of invariant(condition, ...) // statements to just the condition based on NODE_ENV // (dead code removal will remove the extra bytes). return t.conditionalExpression( DEV_EXPRESSION, node, t.callExpression(node.callee, [node.arguments[0]]) // Turns this code: // // invariant(condition, argument, argument); // // into this: // // if (!condition) { // if (\"production\" !== process.env.NODE_ENV) { // invariant(false, argument, argument); // } else { // invariant(false); // } // } // // Specifically this does 2 things: // 1. Checks the condition first, preventing an extra function call. // 2. Adds an environment check so that verbose error messages aren't // shipped to production. // The generated code is longer than the original code but will dead // code removal in a minifier will strip that out. var condition = node.arguments[0]; return t.ifStatement( t.unaryExpression('!', condition), t.blockStatement([ t.ifStatement( DEV_EXPRESSION, t.blockStatement([ t.expressionStatement( t.callExpression( node.callee, [t.literal(false)].concat(node.arguments.slice(1)) ) ) ]), t.blockStatement([ t.expressionStatement( t.callExpression( node.callee, [t.literal(false)] ) ) ]) ) ]) ); } else if (this.get('callee').isIdentifier({name: 'warning'})) { // Eliminate warning(condition, ...) statements based on NODE_ENV // (dead code removal will remove the extra bytes). return t.conditionalExpression( // Turns this code: // // warning(condition, argument, argument); // // into this: // // if (\"production\" !== process.env.NODE_ENV) { // warning(condition, argument, argument); // } // // The goal is to strip out warning calls entirely in production. We // don't need the same optimizations for conditions that we use for // invariant because we don't care about an extra call in __DEV__ return t.ifStatement( DEV_EXPRESSION, node, t.literal(null) t.blockStatement([ t.expressionStatement( node ) ]) ); } }"} {"_id":"doc-en-react-69f17fa4a4ca876f149eff2e205fb59cf86381a6afa0e1fea6f3478d2fb2390f","title":"","text":"itemRef: MUST_USE_ATTRIBUTE, // property is supported for OpenGraph in meta tags. property: null, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: MUST_USE_ATTRIBUTE, // IE-only attribute that controls focus behavior unselectable: MUST_USE_ATTRIBUTE, },"} {"_id":"doc-en-react-08bc89b1e51d4ef0d40a57deb51584c975a2f17488c9822adc68361928a14afa","title":"","text":"var grunt = require('grunt'); var UglifyJS = require('uglify-js'); var uglifyify = require('uglifyify'); var _ = require('lodash'); var derequire = require('derequire'); var SIMPLE_TEMPLATE = '/**n"} {"_id":"doc-en-react-d52c72945ab19ca557aaebddc9dfab2323690da98f8da9304cc0e00fd6fd23c5","title":"","text":"debug: false, standalone: 'React', transforms: [envify({NODE_ENV: 'development'})], after: [es3ify.transform, simpleBannerify] after: [es3ify.transform, derequire, simpleBannerify] }; var min = _.merge({}, basic, { var min = { entries: [ './build/modules/React.js' ], outfile: './build/react.min.js', debug: false, standalone: 'React', transforms: [envify({NODE_ENV: 'production'}), uglifyify], after: [minify, bannerify] }); after: [es3ify.transform, derequire, minify, bannerify] }; var transformer = { entries:["} {"_id":"doc-en-react-ff0daa58a7b1906f42412d89c6f4adfd92319da60311baee5da7a22d8bcb9fe9","title":"","text":"outfile: './build/JSXTransformer.js', debug: false, standalone: 'JSXTransformer', after: [es3ify.transform, simpleBannerify] transforms: [], after: [es3ify.transform, derequire, simpleBannerify] }; var addons = {"} {"_id":"doc-en-react-fb7f6dd4afda24ec875e2e96f5030cb142ef02c10cd809825e25368a0b818104","title":"","text":"outfile: './build/react-with-addons.js', debug: false, standalone: 'React', transforms: [envify({NODE_ENV: 'development'})], packageName: 'React (with addons)', after: [es3ify.transform, simpleBannerify] transforms: [envify({NODE_ENV: 'development'})], after: [es3ify.transform, derequire, simpleBannerify] }; var addonsMin = _.merge({}, addons, { var addonsMin = { entries: [ './build/modules/ReactWithAddons.js' ], outfile: './build/react-with-addons.min.js', debug: false, standalone: 'React', packageName: 'React (with addons)', transforms: [envify({NODE_ENV: 'production'}), uglifyify], after: [minify, bannerify] }); after: [es3ify.transform, derequire, minify, bannerify] }; var withCodeCoverageLogging = { entries: ["} {"_id":"doc-en-react-97c41f5b1ea82b3a1bb345a546f5031a115d6555d867f2fde16f6c3e260fa207","title":"","text":"// grunt.config.requires('entries'); config.transforms = config.transforms || []; config.after = config.after || []; if (typeof config.after === 'function') { config.after = [config.after]; } // create the bundle we'll work with var entries = grunt.file.expand(config.entries); var bundle = browserify(entries); // Make sure the things that need to be exposed are. var requires = config.requires || {}; if (requires instanceof Array) { grunt.file.expand({ nonull: true, // Keep IDs that don't expand to anything. cwd: \"src\" }, requires).forEach(function(name) { bundle.require(\"./build/modules/\" + name, { expose: name.replace(/.js$/i, \"\") }); }); } else if (typeof requires === \"object\") { Object.keys(requires).forEach(function(name) { bundle.require(requires[name], { expose: name }); }); } // Extract other options var options = { entries: entries, debug: config.debug, // sourcemaps standalone: config.standalone // global }; // TODO: make sure this works, test with this too var bundle = browserify(options); config.transforms.forEach(function(transform) { bundle.transform({}, transform); }); // Actually bundle it up var _this = this; bundle.bundle(options, function(err, src) { bundle.bundle(function(err, buf) { if (err) { grunt.log.error(err); done(); return done(); } var src = buf.toString(); config.after.forEach(function(fn) { src = fn.call(_this, src); });"} {"_id":"doc-en-react-20a3f441105be66fd78ec211100eab02ec2aa1e31b656574c5ce7fe08a35faa8","title":"","text":"\"node\": \">=0.10.0\" }, \"dependencies\": { \"envify\": \"^2.0.0\" \"envify\": \"^3.0.0\" }, \"browserify\": { \"transform\": [\"envify\"]"} {"_id":"doc-en-react-0c5f43a655ae4fa34f170aa69c147d6cef9d7c74a69573783eadc7807b0916e6","title":"","text":"\"dependencies\": { \"commoner\": \"^0.10.0\", \"esprima-fb\": \"^6001.1.0-dev-harmony-fb\", \"jstransform\": \"^6.2.0\" \"jstransform\": \"^6.3.2\" }, \"devDependencies\": { \"benchmark\": \"~1.0.0\", \"browserify\": \"^4.1.10\", \"browserify\": \"^6.1.0\", \"coverify\": \"~1.0.4\", \"envify\": \"^2.0.0\", \"derequire\": \"^1.2.0\", \"envify\": \"^3.0.0\", \"es3ify\": \"~0.1.2\", \"es5-shim\": \"^4.0.0\", \"grunt\": \"~0.4.2\", \"grunt-cli\": \"~0.1.9\", \"grunt-compare-size\": \"~0.4.0\", \"grunt-contrib-clean\": \"~0.5.0\", \"grunt-contrib-compress\": \"^0.9.1\", \"grunt-contrib-clean\": \"^0.6.0\", \"grunt-contrib-compress\": \"^0.12.0\", \"grunt-contrib-connect\": \"~0.6.0\", \"grunt-contrib-copy\": \"~0.5.0\", \"grunt-contrib-copy\": \"^0.6.0\", \"grunt-contrib-jshint\": \"^0.10.0\", \"gzip-js\": \"~0.3.2\", \"jasmine-tapreporter\": \"~0.2.2\", \"jest-cli\": \"~0.1.5\", \"lodash\": \"~2.4.1\", \"microtime\": \"^0.6.0\", \"optimist\": \"~0.6.0\", \"phantomjs\": \"~1.9\", \"platform\": \"^1.1.0\", \"populist\": \"~0.1.6\", \"recast\": \"^0.6.10\", \"recast\": \"^0.7.2\", \"sauce-tunnel\": \"~1.1.0\", \"semver\": \"^2.3.0\", \"tmp\": \"~0.0.18\", \"uglify-js\": \"~2.4.0\", \"uglifyify\": \"^2.4.0\","} {"_id":"doc-en-react-55e128ceae5495a426e8609bd3eccbbbd5b9b75ba4fc2e168009852c6f813abd","title":"","text":"\"rootDir\": \"\", \"scriptPreprocessor\": \"jest/preprocessor.js\", \"setupEnvScriptFile\": \"jest/environment.js\", \"modulePathIgnorePatterns\": [\"/build/\", \"/node_modules/\", \"/.module-cache/\"], \"testPathIgnorePatterns\": [\"/build/\", \"/node_modules/\"], \"unmockedModulePathPatterns\": [\"\"] \"modulePathIgnorePatterns\": [ \"/build/\", \"/node_modules/\", \"/.module-cache/\" ], \"testPathIgnorePatterns\": [ \"/build/\", \"/node_modules/\" ], \"unmockedModulePathPatterns\": [ \"\" ] } }"} {"_id":"doc-en-react-d8a74583a7dd7438075fe70a8cbf57bf27e25367de6faa766691242e607a6889","title":"","text":"topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange,"} {"_id":"doc-en-react-65cf806f73c3563aa2b997922e2cd99c2aa2c62cf7f7cd1bae37aa103096bc07","title":"","text":"It is a good idea to avoid spamming the console with duplicate warnings: ````js ```js var warning = require('warning'); var didWarnAboutMath = false;"} {"_id":"doc-en-react-92ce1029ef095c2332df8f67e4184201b3cfa25e3b4639438cfd1b6120cb55ec","title":"","text":"In a traditional JavaScript application, you need to look at what data changed and imperatively make changes to the DOM to keep it up-to-date. Even AngularJS, which provides a declarative interface via directives and data binding requires a linking function to manually update DOM nodes. which provides a declarative interface via directives and data binding [requires a linking function to manually update DOM nodes](http://docs.angularjs.org/guide/directive#reasonsbehindthecompilelinkseparation). React takes a different approach."} {"_id":"doc-en-react-83b6aed5d4db4951133cc2066b1477a66e05064e720ce3a32458ecc5461c3411","title":"","text":"- Facebook has dynamic charts that render to `` instead of HTML. - Instagram is a \"single page\" web app built entirely with React and `Backbone.Router`. Designers regularly contribute React code with JSX. - We've built an internal prototype that runs React apps in a web worker. - We've built internal prototypes that run React apps in a web worker and use React to drive **native iOS views** via an Objective-C bridge. - You can run React [on the server](http://github.com/petehunt/react-server-rendering) for SEO, performance, code sharing and overall flexibility."} {"_id":"doc-en-react-6209a25f2b5d5edd56eb659a9c08eb93ec56ae507a6f982e2ecc3cb4a04b1166","title":"","text":"ReactCache = require('react-cache'); Suspense = React.Suspense; container = document.createElement('div'); document.body.appendChild(container); TextResource = ReactCache.unstable_createResource(([text, ms = 0]) => { return new Promise((resolve, reject) =>"} {"_id":"doc-en-react-53cbdf6fd6a3e255b0645fb9e776de5e726b22f94e3c89f02daddd9d6357d852","title":"","text":"}, ([text, ms]) => text); }); afterEach(() => { document.body.removeChild(container); }); function advanceTimers(ms) { // Note: This advances Jest's virtual time but not React's. Use // ReactNoop.expire for that."} {"_id":"doc-en-react-6c924b6f749e920e4f13d9d8bb7b9592aa026ea5edc52fbb617eeb241aa29f5d","title":"","text":"); }, ); // Regression test for https://github.com/facebook/react/issues/14188 it('can call findDOMNode() in a suspended component commit phase', async () => { const log = []; const Lazy = React.lazy( () => new Promise(resolve => resolve({ default() { return 'lazy'; }, }), ), ); class Child extends React.Component { componentDidMount() { log.push('cDM ' + this.props.id); ReactDOM.findDOMNode(this); } componentDidUpdate() { log.push('cDU ' + this.props.id); ReactDOM.findDOMNode(this); } render() { return 'child'; } } const buttonRef = React.createRef(); class App extends React.Component { state = { suspend: false, }; handleClick = () => { this.setState({suspend: true}); }; render() { return ( {this.state.suspend && } ); } } ReactDOM.render(, container); expect(log).toEqual(['cDM first', 'cDM second']); log.length = 0; buttonRef.current.dispatchEvent(new MouseEvent('click', {bubbles: true})); await Lazy; expect(log).toEqual(['cDU first', 'cDU second']); }); });"} {"_id":"doc-en-react-65d9a0a4c0eea8c4a5c5275a146425908501bb1d38e1c8b89289290f0be80060","title":"","text":"Scheduler.flushAll(); expect(root).toMatchRenderedOutput('hello'); }); // Regression test for https://github.com/facebook/react/issues/15732 it('resets hooks when an error is thrown in the middle of a list of hooks', async () => { const {useEffect, useState} = React; class ErrorBoundary extends React.Component { state = {hasError: false}; static getDerivedStateFromError() { return {hasError: true}; } render() { return ( {this.state.hasError ? 'Error!' : this.props.children} ); } } function Wrapper({children}) { return children; } let setShouldThrow; function Thrower() { const [shouldThrow, _setShouldThrow] = useState(false); setShouldThrow = _setShouldThrow; if (shouldThrow) { throw new Error('Throw!'); } useEffect(() => {}, []); return 'Throw!'; } const root = ReactTestRenderer.create( , ); expect(root).toMatchRenderedOutput('Throw!'); act(() => setShouldThrow(true)); expect(root).toMatchRenderedOutput('Error!'); }); });"} {"_id":"doc-en-react-a89f0b2cac4869a3b8ea690eae250ca99e33423536b308179ec7ec72f8d1dd17","title":"","text":"} case Profiler: if (enableProfilerTimer) { workInProgress.effectTag |= Update; // Profiler should only call onRender when one of its descendants actually rendered. const hasChildWork = workInProgress.childExpirationTime >= renderExpirationTime; if (hasChildWork) { workInProgress.effectTag |= Update; } } break; case SuspenseComponent: {"} {"_id":"doc-en-react-9f98db2a443bd3dcd9c8cd3f3384418c7db45be5ecd7d7fa9d8050f88401fcfa","title":"","text":"); }); it('does not report work done on a sibling', () => { const callback = jest.fn(); const DoesNotUpdate = React.memo(function DoesNotUpdateInner() { Scheduler.unstable_advanceTime(10); return null; }, () => true); let updateProfilerSibling; function ProfilerSibling() { const [count, setCount] = React.useState(0); updateProfilerSibling = () => setCount(count + 1); return null; } function App() { return ( ); } const renderer = ReactTestRenderer.create(); expect(callback).toHaveBeenCalledTimes(1); let call = callback.mock.calls[0]; expect(call).toHaveLength(enableSchedulerTracing ? 7 : 6); expect(call[0]).toBe('test'); expect(call[1]).toBe('mount'); expect(call[2]).toBe(10); // actual time expect(call[3]).toBe(10); // base time expect(call[4]).toBe(0); // start time expect(call[5]).toBe(10); // commit time expect(call[6]).toEqual(enableSchedulerTracing ? new Set() : undefined); // interaction events callback.mockReset(); Scheduler.unstable_advanceTime(20); // 10 -> 30 // Updating a parent should report a re-render, // since React technically did a little bit of work between the Profiler and the bailed out subtree. renderer.update(); expect(callback).toHaveBeenCalledTimes(1); call = callback.mock.calls[0]; expect(call).toHaveLength(enableSchedulerTracing ? 7 : 6); expect(call[0]).toBe('test'); expect(call[1]).toBe('update'); expect(call[2]).toBe(0); // actual time expect(call[3]).toBe(10); // base time expect(call[4]).toBe(30); // start time expect(call[5]).toBe(30); // commit time expect(call[6]).toEqual(enableSchedulerTracing ? new Set() : undefined); // interaction events callback.mockReset(); Scheduler.unstable_advanceTime(20); // 30 -> 50 // Updating a sibling should not report a re-render. ReactTestRenderer.act(updateProfilerSibling); expect(callback).not.toHaveBeenCalled(); }); it('logs render times for both mount and update', () => { const callback = jest.fn();"} {"_id":"doc-en-react-08c42cf431b916b22ced085cd69d07ca68aaea32605a377828ff3d6da4b26992","title":"","text":"Scheduler.unstable_advanceTime(5); // 0 -> 5 ReactTestRenderer.create( <> "} {"_id":"doc-en-react-fb781bf877d85dffa9028cff3949590ba7e26bfb1dde624fa515447fa84bd6e6","title":"","text":" , , ); expect(callback).toHaveBeenCalledTimes(2);"} {"_id":"doc-en-react-90a06ea5f9b787f43db7a85f516e5053e6acfcb570de02e762c328567228eb8d","title":"","text":"Scheduler.unstable_advanceTime(5); // 0 -> 5 ReactTestRenderer.create( <> , , ); expect(callback).toHaveBeenCalledTimes(2);"} {"_id":"doc-en-react-a6d08422a5c943eb7d86a2c23e477cbe98949f3b483adfbff0a185d68a82708a","title":"","text":"Scheduler.unstable_advanceTime(5); // 0 -> 5 ReactTestRenderer.create( <> , , ); expect(callback).toHaveBeenCalledTimes(1);"} {"_id":"doc-en-react-6de1770c683920b9491c28752822ebaa169746b3515c048c2524d9c4c815d2eb","title":"","text":"} } class Pure extends React.PureComponent { render() { return this.props.children; } } const renderer = ReactTestRenderer.create(
, ); // All profile callbacks are called for initial render expect(callback).toHaveBeenCalledTimes(3); expect(callback).toHaveBeenCalledTimes(2); callback.mockReset();"} {"_id":"doc-en-react-316689dac6224d71a18d85929d82290c223638756366f8776dbc72b23d2c5b18","title":"","text":"}); }); // Only call profile updates for paths that have re-rendered // Since \"inner\" is beneath a pure component, it isn't called expect(callback).toHaveBeenCalledTimes(2); expect(callback.mock.calls[0][0]).toBe('middle'); expect(callback.mock.calls[1][0]).toBe('outer'); // Only call onRender for paths that have re-rendered. // Since the Updater's props didn't change, // React does not re-render its children. expect(callback).toHaveBeenCalledTimes(1); expect(callback.mock.calls[0][0]).toBe('outer'); }); it('decreases actual time but not base time when sCU prevents an update', () => {"} {"_id":"doc-en-react-c1128494dcd2c03700c66170c9a19ec7485d12e17d6aedf2bd87d6e492329c4b","title":"","text":"render() { instance = this; return ( <> {this.state.count} ); } }"} {"_id":"doc-en-react-46beefd74367193c1721f7df2618323e70af81a25d5de02eee804981c86e4c90","title":"","text":"); if (__DEV__) { const inst = workInProgress.stateNode; if (inst.props !== nextProps) { if (shouldUpdate && inst.props !== nextProps) { if (!didWarnAboutReassigningProps) { console.error( 'It looks like %s is reassigning its own `this.props` while rendering. ' +"} {"_id":"doc-en-react-37e90eee3dbf38f508b0345fcf49fb7a9ef9db60c9008e258a30b780c84de5e1","title":"","text":"cloneUpdateQueue(current, workInProgress); const oldProps = workInProgress.memoizedProps; instance.props = const unresolvedOldProps = workInProgress.memoizedProps; const oldProps = workInProgress.type === workInProgress.elementType ? oldProps : resolveDefaultProps(workInProgress.type, oldProps); ? unresolvedOldProps : resolveDefaultProps(workInProgress.type, unresolvedOldProps); instance.props = oldProps; const unresolvedNewProps = workInProgress.pendingProps; const oldContext = instance.context; const contextType = ctor.contextType;"} {"_id":"doc-en-react-8967f32e433f822fea9a24e449bdef862555ebe03f655856daa2221464c232e1","title":"","text":"(typeof instance.UNSAFE_componentWillReceiveProps === 'function' || typeof instance.componentWillReceiveProps === 'function') ) { if (oldProps !== newProps || oldContext !== nextContext) { if ( unresolvedOldProps !== unresolvedNewProps || oldContext !== nextContext ) { callComponentWillReceiveProps( workInProgress, instance,"} {"_id":"doc-en-react-fbf5da77cfa162c01513ada1bdaaa5adb28d4e4f38c5f1602a75adf4b5e842c9","title":"","text":"newState = workInProgress.memoizedState; if ( oldProps === newProps && unresolvedOldProps === unresolvedNewProps && oldState === newState && !hasContextChanged() && !checkHasForceUpdateAfterProcessing()"} {"_id":"doc-en-react-f4cc3ef29747b031c45e4cd869ac7ed92a72052109d2e19cb8d9180ed5eb9bd8","title":"","text":"// effect even though we're bailing out, so that cWU/cDU are called. if (typeof instance.componentDidUpdate === 'function') { if ( oldProps !== current.memoizedProps || unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState ) { workInProgress.effectTag |= Update;"} {"_id":"doc-en-react-312d4a074bbd9efa4f979633a3d7d583128bcd68898b3067f59667bbe2e6d43a","title":"","text":"} if (typeof instance.getSnapshotBeforeUpdate === 'function') { if ( oldProps !== current.memoizedProps || unresolvedOldProps !== current.memoizedProps || oldState !== current.memoizedState ) { workInProgress.effectTag |= Snapshot;"} {"_id":"doc-en-react-a4939f9fc327e475ff468a66a8927faea55a5732a12dc3c918d597d399424257","title":"","text":"expect(root).toMatchRenderedOutput('SiblingB'); }); it('resolves defaultProps without breaking bailout due to unchanged props and state, #17151', async () => { class LazyImpl extends React.Component { static defaultProps = {value: 0}; render() { const text = `${this.props.label}: ${this.props.value}`; return ; } } const Lazy = lazy(() => fakeImport(LazyImpl)); const instance1 = React.createRef(null); const instance2 = React.createRef(null); const root = ReactTestRenderer.create( <> }> , { unstable_isConcurrent: true, }, ); expect(Scheduler).toFlushAndYield(['Not lazy: 0', 'Loading...']); expect(root).not.toMatchRenderedOutput('Not lazy: 0Lazy: 0'); await Promise.resolve(); expect(Scheduler).toFlushAndYield(['Lazy: 0']); expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0'); // Should bailout due to unchanged props and state instance1.current.setState(null); expect(Scheduler).toFlushAndYield([]); expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0'); // Should bailout due to unchanged props and state instance2.current.setState(null); expect(Scheduler).toFlushAndYield([]); expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0'); }); it('resolves defaultProps without breaking bailout in PureComponent, #17151', async () => { class LazyImpl extends React.PureComponent { static defaultProps = {value: 0}; state = {}; render() { const text = `${this.props.label}: ${this.props.value}`; return ; } } const Lazy = lazy(() => fakeImport(LazyImpl)); const instance1 = React.createRef(null); const instance2 = React.createRef(null); const root = ReactTestRenderer.create( <> }> , { unstable_isConcurrent: true, }, ); expect(Scheduler).toFlushAndYield(['Not lazy: 0', 'Loading...']); expect(root).not.toMatchRenderedOutput('Not lazy: 0Lazy: 0'); await Promise.resolve(); expect(Scheduler).toFlushAndYield(['Lazy: 0']); expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0'); // Should bailout due to shallow equal props and state instance1.current.setState({}); expect(Scheduler).toFlushAndYield([]); expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0'); // Should bailout due to shallow equal props and state instance2.current.setState({}); expect(Scheduler).toFlushAndYield([]); expect(root).toMatchRenderedOutput('Not lazy: 0Lazy: 0'); }); it('sets defaultProps for modern lifecycles', async () => { class C extends React.Component { static defaultProps = {text: 'A'};"} {"_id":"doc-en-react-5cb7765e5a8008bf69b4ce015c8eae0bfaff49867f0ec035de36017cf00d179c","title":"","text":"const nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's // version of setImmediate, bypassing fake timers if any. enqueueTaskImpl = nodeRequire('timers').setImmediate; enqueueTaskImpl = nodeRequire.call(module, 'timers').setImmediate; } catch (_err) { // we're in a browser // we can't use regular timers because they may still be faked"} {"_id":"doc-en-react-1acf6ecf78e5bfcee6058e14abecb4c6340c62dcfda74a31f238aa9dd5f8fc0f","title":"","text":"return JSON.parse(raw); } } catch (error) {} return true; return false; } export function setBreakOnConsoleErrors(value: boolean): void {"} {"_id":"doc-en-react-d881ebe0e86edb4dcf13d68a1ff2b35976f94915d867ded28b73253b220afacf","title":"","text":"} function mountFiberRecursively( fiber: Fiber, firstChild: Fiber, parentFiber: Fiber | null, traverseSiblings: boolean, traceNearestHostComponentUpdate: boolean, ) { if (__DEBUG__) { debug('mountFiberRecursively()', fiber, parentFiber); } // Iterate over siblings rather than recursing. // This reduces the chance of stack overflow for wide trees (e.g. lists with many items). let fiber: Fiber | null = firstChild; while (fiber !== null) { if (__DEBUG__) { debug('mountFiberRecursively()', fiber, parentFiber); } // If we have the tree selection from previous reload, try to match this Fiber. // Also remember whether to do the same for siblings. const mightSiblingsBeOnTrackedPath = updateTrackedPathStateBeforeMount( fiber, ); // If we have the tree selection from previous reload, try to match this Fiber. // Also remember whether to do the same for siblings. const mightSiblingsBeOnTrackedPath = updateTrackedPathStateBeforeMount( fiber, ); const shouldIncludeInTree = !shouldFilterFiber(fiber); if (shouldIncludeInTree) { recordMount(fiber, parentFiber); } const shouldIncludeInTree = !shouldFilterFiber(fiber); if (shouldIncludeInTree) { recordMount(fiber, parentFiber); } if (traceUpdatesEnabled) { if (traceNearestHostComponentUpdate) { const elementType = getElementTypeForFiber(fiber); // If an ancestor updated, we should mark the nearest host nodes for highlighting. if (elementType === ElementTypeHostComponent) { traceUpdatesForNodes.add(fiber.stateNode); traceNearestHostComponentUpdate = false; if (traceUpdatesEnabled) { if (traceNearestHostComponentUpdate) { const elementType = getElementTypeForFiber(fiber); // If an ancestor updated, we should mark the nearest host nodes for highlighting. if (elementType === ElementTypeHostComponent) { traceUpdatesForNodes.add(fiber.stateNode); traceNearestHostComponentUpdate = false; } } } // We intentionally do not re-enable the traceNearestHostComponentUpdate flag in this branch, // because we don't want to highlight every host node inside of a newly mounted subtree. } // We intentionally do not re-enable the traceNearestHostComponentUpdate flag in this branch, // because we don't want to highlight every host node inside of a newly mounted subtree. } const isSuspense = fiber.tag === ReactTypeOfWork.SuspenseComponent; if (isSuspense) { const isTimedOut = fiber.memoizedState !== null; if (isTimedOut) { // Special case: if Suspense mounts in a timed-out state, // get the fallback child from the inner fragment and mount // it as if it was our own child. Updates handle this too. const primaryChildFragment = fiber.child; const fallbackChildFragment = primaryChildFragment ? primaryChildFragment.sibling : null; const fallbackChild = fallbackChildFragment ? fallbackChildFragment.child : null; if (fallbackChild !== null) { mountFiberRecursively( fallbackChild, shouldIncludeInTree ? fiber : parentFiber, true, traceNearestHostComponentUpdate, ); const isSuspense = fiber.tag === ReactTypeOfWork.SuspenseComponent; if (isSuspense) { const isTimedOut = fiber.memoizedState !== null; if (isTimedOut) { // Special case: if Suspense mounts in a timed-out state, // get the fallback child from the inner fragment and mount // it as if it was our own child. Updates handle this too. const primaryChildFragment = fiber.child; const fallbackChildFragment = primaryChildFragment ? primaryChildFragment.sibling : null; const fallbackChild = fallbackChildFragment ? fallbackChildFragment.child : null; if (fallbackChild !== null) { mountFiberRecursively( fallbackChild, shouldIncludeInTree ? fiber : parentFiber, true, traceNearestHostComponentUpdate, ); } } else { let primaryChild: Fiber | null = null; const areSuspenseChildrenConditionallyWrapped = OffscreenComponent === -1; if (areSuspenseChildrenConditionallyWrapped) { primaryChild = fiber.child; } else if (fiber.child !== null) { primaryChild = fiber.child.child; } if (primaryChild !== null) { mountFiberRecursively( primaryChild, shouldIncludeInTree ? fiber : parentFiber, true, traceNearestHostComponentUpdate, ); } } } else { let primaryChild: Fiber | null = null; const areSuspenseChildrenConditionallyWrapped = OffscreenComponent === -1; if (areSuspenseChildrenConditionallyWrapped) { primaryChild = fiber.child; } else if (fiber.child !== null) { primaryChild = fiber.child.child; } if (primaryChild !== null) { if (fiber.child !== null) { mountFiberRecursively( primaryChild, fiber.child, shouldIncludeInTree ? fiber : parentFiber, true, traceNearestHostComponentUpdate, ); } } } else { if (fiber.child !== null) { mountFiberRecursively( fiber.child, shouldIncludeInTree ? fiber : parentFiber, true, traceNearestHostComponentUpdate, ); } } // We're exiting this Fiber now, and entering its siblings. // If we have selection to restore, we might need to re-activate tracking. updateTrackedPathStateAfterMount(mightSiblingsBeOnTrackedPath); // We're exiting this Fiber now, and entering its siblings. // If we have selection to restore, we might need to re-activate tracking. updateTrackedPathStateAfterMount(mightSiblingsBeOnTrackedPath); if (traverseSiblings && fiber.sibling !== null) { mountFiberRecursively( fiber.sibling, parentFiber, true, traceNearestHostComponentUpdate, ); fiber = traverseSiblings ? fiber.sibling : null; } }"} {"_id":"doc-en-react-b79fd4faf80d63764211b4876b9981357b248a77ab807f7d175019e974fdb1ab","title":"","text":"expect(store).toMatchSnapshot('2: add host nodes'); }); // This test is not the same cause as what's reported on GitHub, // but the resulting behavior (owner mounting after descendant) is the same. // Thec ase below is admittedly contrived and relies on side effects. // I'mnot yet sure of how to reduce the GitHub reported production case to a test though. // See https://github.com/facebook/react/issues/21445 it('should handle when a component mounts before its owner', () => { const promise = new Promise(resolve => {}); let Dynamic = null; const Owner = () => { Dynamic = ; throw promise; }; const Parent = () => { return Dynamic; }; const Child = () => null; const container = document.createElement('div'); act(() => ReactDOM.render( <> , container, ), ); expect(store).toMatchInlineSnapshot(` [root] `); }); describe('collapseNodesByDefault:false', () => { beforeEach(() => { store.collapseNodesByDefault = false;"} {"_id":"doc-en-react-2ecdf99ae0b477493332383441b1b8e37fd7275f72a0cb086c37af80dd52bf6b","title":"","text":"const elementType = getElementTypeForFiber(fiber); const {_debugOwner} = fiber; const ownerID = _debugOwner != null ? getFiberIDThrows(_debugOwner) : 0; // Ideally we should call getFiberIDThrows() for _debugOwner, // since owners are almost always higher in the tree (and so have already been processed), // but in some (rare) instances reported in open source, a descendant mounts before an owner. // Since this is a DEV only field it's probably okay to also just lazily generate and ID here if needed. // See https://github.com/facebook/react/issues/21445 const ownerID = _debugOwner != null ? getOrGenerateFiberID(_debugOwner) : 0; const parentID = parentFiber ? getFiberIDThrows(parentFiber) : 0; const displayNameStringID = getStringID(displayName);"} {"_id":"doc-en-react-6c04309ecc806d336b79c1f52650324556e50672ebaa62fa9525afe9ecf3d1e2","title":"","text":"return false; } // Column numbers are representated differently between tools/engines. // Error.prototype.stack columns are 1-based (like most IDEs) but ASTs are 0-based. // // In practice this will probably never matter, // because this code matches the 1-based Error stack location for the hook Identifier (e.g. useState) // with the larger 0-based VariableDeclarator (e.g. [foo, setFoo] = useState()) // so the ranges should always overlap. // // For more info see https://github.com/facebook/react/pull/21833#discussion_r666831276 column -= 1; if ( (line === start.line && column < start.column) || (line === end.line && column > end.column)"} {"_id":"doc-en-react-0c1cb0c26d52930b9ad004067452ec04c302d940bc79c996eaa9bbbed899b8c6","title":"","text":"line: lineNumber, // Column numbers are representated differently between tools/engines. // Error.prototype.stack columns are 1-based (like most IDEs) but ASTs are 0-based. // For more info see https://github.com/facebook/react/issues/21792#issuecomment-873171991 column: columnNumber - 1, });"} {"_id":"doc-en-react-013979c404fb59396054817073a8bbc013f54efd66978ad1f560eb75dae2d293","title":"","text":" ## 4.4.0 * No changes, this was an automated release together with React 18. ## 4.3.0 * Support ESLint 8. ([@MichaelDeBoey](https://github.com/MichaelDeBoey) in [#22248](https://github.com/facebook/react/pull/22248))"} {"_id":"doc-en-react-7ea35d2e124dc8e026573763d78655a2d98ece529ec7c474960b2b755f8cb79b","title":"","text":"The examples in the React repository are declared a bit differently than a third-party renderer would be. In particular, the `HostConfig` object mentioned above is never explicitly declared, and instead is a *module* in our code. However, its exports correspond directly to properties on a `HostConfig` object you'd need to declare in your code: * [React ART](https://github.com/facebook/react/blob/main/packages/react-art/src/ReactART.js) and its [host config](https://github.com/facebook/react/blob/main/packages/react-art/src/ReactARTHostConfig.js) * [React DOM](https://github.com/facebook/react/blob/main/packages/react-dom/src/client/ReactDOM.js) and its [host config](https://github.com/facebook/react/blob/main/packages/react-dom/src/client/ReactDOMHostConfig.js) * [React DOM](https://github.com/facebook/react/blob/main/packages/react-dom/src/client/ReactDOM.js) and its [host config](https://github.com/facebook/react/blob/main/packages/react-dom-bindings/src/client/ReactDOMHostConfig.js) * [React Native](https://github.com/facebook/react/blob/main/packages/react-native-renderer/src/ReactNativeRenderer.js) and its [host config](https://github.com/facebook/react/blob/main/packages/react-native-renderer/src/ReactNativeHostConfig.js) If these links break please file an issue and we’ll fix them. They intentionally link to the latest versions since the API is still evolving. If you have more questions please file an issue and we’ll try to help!"} {"_id":"doc-en-react-7433a0a21625d38bf89325fcc98d9742c4cc83acae3dad64cff7184d0e5ede32","title":"","text":" /** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeGlobalInteractionHandler * @flow */ 'use strict'; var InteractionManager = require('InteractionManager'); // Interaction handle is created/cleared when responder is granted or // released/terminated. var interactionHandle = null; var ReactNativeGlobalInteractionHandler = { onChange: function(numberActiveTouches: number) { if (numberActiveTouches === 0) { if (interactionHandle) { InteractionManager.clearInteractionHandle(interactionHandle); interactionHandle = null; } } else if (!interactionHandle) { interactionHandle = InteractionManager.createInteractionHandle(); } }, }; module.exports = ReactNativeGlobalInteractionHandler; "}