{"_id":"q-en-react-0224e72f53068cfce1eb60f4e6918116817d50f053dcb5f8b5a759638f7bc467","text":"``` accept acceptCharset accessKey action allowFullScreen allowTransparency alt async autoComplete autoFocus autoPlay cellPadding cellSpacing charSet checked classID className colSpan cols content contentEditable contextMenu controls async autoComplete autoFocus autoPlay cellPadding cellSpacing charSet challenge checked classID className colSpan cols content contentEditable contextMenu controls coords crossOrigin data dateTime defer dir disabled download draggable encType form formAction formEncType formMethod formNoValidate formTarget frameBorder headers height hidden high href hrefLang htmlFor httpEquiv icon id label lang list loop low manifest marginHeight marginWidth max maxLength media mediaGroup method min multiple muted name noValidate open optimum pattern placeholder headers height hidden high href hrefLang htmlFor httpEquiv icon id keyParams keyType label lang list loop low manifest marginHeight marginWidth max maxLength media mediaGroup method min multiple muted name noValidate open optimum pattern placeholder poster preload radioGroup readOnly rel required role rowSpan rows sandbox scope scoped scrolling seamless selected shape size sizes span spellCheck src srcDoc srcSet start step style tabIndex target title type useMap value width wmode"} {"_id":"q-en-react-02695d84dd62ba8e5cc7d7d1498b6382aac82412daaaa94e7b6dce768cee0bd5","text":"expect(log).toEqual([]); }); it('should pass previous state to shouldComponentUpdate even with getDerivedStateFromProps', () => { const divRef = React.createRef(); class SimpleComponent extends React.Component { constructor(props) { super(props); this.state = { value: props.value, }; } static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.value === prevState.value) { return null; } return {value: nextProps.value}; } shouldComponentUpdate(nextProps, nextState) { return nextState.value !== this.state.value; } render() { return
value: {this.state.value}
; } } const div = document.createElement('div'); ReactDOM.render(, div); expect(divRef.current.textContent).toBe('value: initial'); ReactDOM.render(, div); expect(divRef.current.textContent).toBe('value: updated'); });
it('should call getSnapshotBeforeUpdate before mutations are committed', () => { const log = [];"} {"_id":"q-en-react-08051247c7484c21a13b92a0969c97f7789334fc06a140d56ce8f307ea75ed1f","text":"} } } this._updateStateFromStaticLifecycle(props); // Read state after cWRP in case it calls setState const state = this._newState || oldState; let state = this._newState || oldState; if (typeof type.getDerivedStateFromProps === 'function') { const partialState = type.getDerivedStateFromProps.call( null, props, state, ); if (partialState != null) { state = Object.assign({}, state, partialState); } } let shouldUpdate = true; if (this._forcedUpdate) {"} {"_id":"q-en-react-083d62956cf05470274440705503ba0a0734b57f8b4e261f16d6ac1983b31d37","text":"var React = require('React'); var ReactElement = require('ReactElement'); var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); var ReactCompositeComponent = require('ReactCompositeComponent'); var ReactInstanceHandles = require('ReactInstanceHandles'); var ReactInstanceMap = require('ReactInstanceMap'); var ReactMount = require('ReactMount'); var ReactUpdates = require('ReactUpdates'); var SyntheticEvent = require('SyntheticEvent'); var assign = require('Object.assign'); var instantiateReactComponent = require('instantiateReactComponent'); var topLevelTypes = EventConstants.topLevelTypes;"} {"_id":"q-en-react-0baebf45e9b87220c29281eb8bfbb60ebe3253a5952c16951a9c107393d9bf82","text":"// an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. this._store = { validated: false, props: props }; this._store = { props: props }; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. try { Object.defineProperty(this._store, 'validated', { configurable: false, enumerable: false, writable: true }); } catch (x) { } this._store.validated = false; // We're not allowed to set props directly on the object so we early // return and rely on the prototype membrane to forward to the backing"} {"_id":"q-en-react-0c05fc3684729bae7342c761e89db88783aa467325ed121fe6d2005c922ed2f0","text":"ReactDOMIDOperations.updateInnerHTMLByID( 'testID', {__html: ' testContent'} ' testContent' ); expect("} {"_id":"q-en-react-0fd04f68f41f021225646be2e9021a029743e7a569b88b7e56b7cc18503d5e7f","text":"const commitTrees = ((rootToCommitTreeMap.get( rootID, ): any): Array); if (commitIndex < commitTrees.length) { return commitTrees[commitIndex]; }"} {"_id":"q-en-react-1631af01635fa911272da2ddd5bc78c624e8703a28e4b5e6b70ad95790e93906","text":"return [
]; } function ComponentWithSymbolWarning() { console.warn('this is a symbol', Symbol('foo')); console.error('this is a symbol', Symbol.for('bar')); return null; } export default function ErrorsAndWarnings() { const [count, setCount] = useState(0); const handleClick = () => setCount(count + 1);"} {"_id":"q-en-react-1919755a26630a02897fbe5eba7e9a81ba7fa27a612b5acecfa17fc307ddd615","text":"expectTextNode(e.childNodes[1], 'bar'); } }); itRenders( 'a component returning text node between two text nodes', async render => { const B = () => 'b'; const e = await render(
{'a'}{'c'}
); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's a comment between them. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[2], 'b'); expectTextNode(e.childNodes[4], 'c'); } else { expect(e.childNodes.length).toBe(3); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[1], 'b'); expectTextNode(e.childNodes[2], 'c'); } }, ); itRenders('a tree with sibling host and text nodes', async render => { class X extends React.Component { render() { return [null, [], false]; } } function Y() { return [, ['c']]; } function Z() { return null; } const e = await render(
{[['a'], 'b']}
d
e
, ); if ( render === serverRender || render === clientRenderOnServerString || render === streamRender ) { // In the server render output there's comments between text nodes. expect(e.childNodes.length).toBe(5); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[2], 'b'); expect(e.childNodes[3].childNodes.length).toBe(3); expectTextNode(e.childNodes[3].childNodes[0], 'c'); expectTextNode(e.childNodes[3].childNodes[2], 'd'); expectTextNode(e.childNodes[4], 'e'); } else { expect(e.childNodes.length).toBe(4); expectTextNode(e.childNodes[0], 'a'); expectTextNode(e.childNodes[1], 'b'); expect(e.childNodes[2].childNodes.length).toBe(2); expectTextNode(e.childNodes[2].childNodes[0], 'c'); expectTextNode(e.childNodes[2].childNodes[1], 'd'); expectTextNode(e.childNodes[3], 'e'); } });
}); describe('number children', function() {"} {"_id":"q-en-react-19df38ab2400bdd8864a6b1dd3d49b54b2e7ae46894154f19f62c49f61836d06","text":"var inlineScriptCount = 0; // This method returns a nicely formated line of code pointing the // exactly location of the error `e`. // The line is limited in size so big lines of code are also shown // in a readable way. // Example: // // ... x', overflow:'scroll'}} id={} onScroll={this.scroll} class=\" ... // ^ var createSourceCodeErrorMessage = function(code, e) { var sourceLines = code.split('n'); var erroneousLine = sourceLines[e.lineNumber - 1]; // Removes any leading indenting spaces and gets the number of // chars indenting the `erroneousLine` var indentation = 0; erroneousLine = erroneousLine.replace(/^s+/, function(leadingSpaces) { indentation = leadingSpaces.length; return ''; }); // Defines the number of characters that are going to show // before and after the erroneous code var LIMIT = 30; var errorColumn = e.column - indentation; if (errorColumn > LIMIT) { erroneousLine = '... ' + erroneousLine.slice(errorColumn - LIMIT); errorColumn = 4 + LIMIT; } if (erroneousLine.length - errorColumn > LIMIT) { erroneousLine = erroneousLine.slice(0, errorColumn + LIMIT) + ' ...'; } var message = 'nn' + erroneousLine + 'n'; message += new Array(errorColumn - 1).join(' ') + '^'; return message; }; var transformCode = function(code, source) { var jsx = docblock.parseAsObject(docblock.extract(code)).jsx; if (jsx) { var transformed = transformReact(code); try { var transformed = transformReact(code); } catch(e) { e.message += 'n at '; if (source) { if ('fileName' in e) { // We set `fileName` if it's supported by this error object and // a `source` was provided. // The error will correctly point to `source` in Firefox. e.fileName = source; } e.message += source + ':' + e.lineNumber + ':' + e.column; } else { e.message += location.href; } e.message += createSourceCodeErrorMessage(code, e); throw e; } var map = transformed.sourceMap.toJSON(); if (source == null) {"} {"_id":"q-en-react-21f6b6defd388b3632be63440e7f793e2d8c828e38be0cab59df30fba9478e50","text":"} const {operations} = dataForRoot; if (operations.length <= commitIndex) { throw Error( `getCommitTree(): Invalid commit \"${commitIndex}\" for root \"${rootID}\". There are only \"${operations.length}\" commits.`, ); } // Commits are generated sequentially and cached. // If this is the very first commit, start with the cached snapshot and apply the first mutation. // Otherwise load (or generate) the previous commit and append a mutation to it. if (commitIndex === 0) { const nodes = new Map(); // Construct the initial tree. recursivelyInitializeTree(rootID, 0, nodes, dataForRoot); let commitTree: CommitTree = ((null: any): CommitTree); for (let index = commitTrees.length; index <= commitIndex; index++) { // Commits are generated sequentially and cached. // If this is the very first commit, start with the cached snapshot and apply the first mutation. // Otherwise load (or generate) the previous commit and append a mutation to it. if (index === 0) { const nodes = new Map(); // Mutate the tree if (operations != null && commitIndex < operations.length) { const commitTree = updateTree({nodes, rootID}, operations[commitIndex]); // Construct the initial tree. recursivelyInitializeTree(rootID, 0, nodes, dataForRoot); if (__DEBUG__) { __printTree(commitTree); } // Mutate the tree if (operations != null && index < operations.length) { commitTree = updateTree({nodes, rootID}, operations[index]); commitTrees.push(commitTree); return commitTree; } } else { const previousCommitTree = getCommitTree({ commitIndex: commitIndex - 1, profilerStore, rootID, }); if (__DEBUG__) { __printTree(commitTree); } if (operations != null && commitIndex < operations.length) { const commitTree = updateTree( previousCommitTree, operations[commitIndex], ); commitTrees.push(commitTree); } } else { const previousCommitTree = commitTrees[index - 1]; commitTree = updateTree(previousCommitTree, operations[index]); if (__DEBUG__) { __printTree(commitTree); } commitTrees.push(commitTree); return commitTree; } } throw Error( `getCommitTree(): Unable to reconstruct tree for root \"${rootID}\" and commit \"${commitIndex}\"`, ); return commitTree; } function recursivelyInitializeTree("} {"_id":"q-en-react-25aec233a2a1cc53dfad038d1962303504c42add268a6140261190df24110126","text":" /** * Copyright 2013-2014, 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\"; var React; var ReactTestUtils; var mocks; var warn; describe('ReactTestUtils', function() { beforeEach(function() { mocks = require('mocks'); React = require('React'); ReactTestUtils = require('ReactTestUtils'); warn = console.warn; console.warn = mocks.getMockFunction(); }); afterEach(function() { console.warn = warn; }); it('should have shallow rendering', function() { var SomeComponent = React.createClass({ render: function() { return (
); } }); var shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(); var result = shallowRenderer.getRenderOutput(); expect(result.type).toBe('div'); expect(result.props.children).toEqual([ , ]); }); it('lets you update shallowly rendered components', function() { var SomeComponent = React.createClass({ getInitialState: function() { return {clicked: false}; }, onClick: function() { this.setState({clicked: true}); }, render: function() { var className = this.state.clicked ? 'was-clicked' : ''; if (this.props.aNew === 'prop') { return ( Test link ); } else { return (
); } } }); var shallowRenderer = ReactTestUtils.createRenderer(); shallowRenderer.render(); var result = shallowRenderer.getRenderOutput(); expect(result.type).toBe('div'); expect(result.props.children).toEqual([ , ]); shallowRenderer.render(); var updatedResult = shallowRenderer.getRenderOutput(); expect(updatedResult.type).toBe('a'); var mockEvent = {}; updatedResult.props.onClick(mockEvent); var updatedResultCausedByClick = shallowRenderer.getRenderOutput(); expect(updatedResultCausedByClick.type).toBe('a'); expect(updatedResultCausedByClick.props.className).toBe('was-clicked'); }); });
"} {"_id":"q-en-react-26b41bf412909ef9599cf66b12f5ea03573f2791da00c76fdc0f5b24e918d007","text":"_updateDOMChildren: function(lastProps, transaction) { var nextProps = this.props; var lastUsedContent = var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var contentToUse = var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; var lastUsedChildren = lastUsedContent != null ? null : lastProps.children; var childrenToUse = contentToUse != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (contentToUse != null) { var childrenRemoved = lastUsedChildren != null && childrenToUse == null; if (childrenRemoved) { this.updateChildren(null, transaction); } if (lastUsedContent !== contentToUse) { this.updateTextContent('' + contentToUse); if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else { var contentRemoved = lastUsedContent != null && contentToUse == null; if (contentRemoved) { this.updateTextContent(''); } else if (nextHtml != null) { if (lastHtml !== nextHtml) { ReactComponent.DOMIDOperations.updateInnerHTMLByID( this._rootNodeID, nextHtml ); } this.updateChildren(flattenChildren(nextProps.children), transaction); } else if (nextChildren != null) { this.updateChildren(flattenChildren(nextChildren), transaction); } },"} {"_id":"q-en-react-27a36b8673e4939dd5b59116e8f4a4b80678086077765eec3130a71e4cb034fe","text":"* @internal */ unmountComponent: function() { this.unmountChildren(); ReactEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponent.Mixin.unmountComponent.call(this); this.unmountChildren(); } };"} {"_id":"q-en-react-280df49022f3b9a5b8664ab787ba9036ef77bc6b23bdf0915351b790454412dc","text":"
"} {"_id":"q-en-react-29fbe385ed23bd24eba969cbfa4134fdb3f0a5e44d2996e15b64ca57c24a593d","text":"styleUpdates[styleName] = ''; } } } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { // http://jsperf.com/emptying-speed ReactComponent.DOMIDOperations.updateTextContentByID( this._rootNodeID, '' ); } else if (registrationNames[propKey]) { deleteListener(this._rootNodeID, propKey); } else { } else if ( DOMProperty.isStandardName[propKey] || DOMProperty.isCustomAttribute(propKey)) { ReactComponent.DOMIDOperations.deletePropertyByID( this._rootNodeID, propKey"} {"_id":"q-en-react-2eeacd7fbbe10d84d6676db603ec3a4e8b8a8e27651d68200a25831975903454","text":"case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break;"} {"_id":"q-en-react-33a20264932ebe0d8a0c6b4086d548e615657866094922ff3bd259176ca4faf1","text":"); } // stub element used by act() when flushing effects let actContainerElement = document.createElement('div'); // a stub element, lazily initialized, used by act() when flushing effects let actContainerElement = null; /** * Utilities for making it easy to test React components."} {"_id":"q-en-react-348ef8bbc28f8eabef2ac31ce644cb91080b17dfb8027e3b25eb47a560e52645","text":"html: createFullPageComponent(ReactDOM.html), head: createFullPageComponent(ReactDOM.head), title: createFullPageComponent(ReactDOM.title), body: createFullPageComponent(ReactDOM.body) });"} {"_id":"q-en-react-353ff7a4364db19ff636be9f37ad8345e0c1e3c60efd30121dd4dad293dfb88b","text":"expect(stub.getDOMNode().innerHTML).toEqual(''); }); it(\"should transition from string content to innerHTML\", function() { var stub = ReactTestUtils.renderIntoDocument(
hello
); expect(stub.getDOMNode().innerHTML).toEqual('hello'); stub.receiveProps( {dangerouslySetInnerHTML: {__html: 'goodbye'}}, transaction ); expect(stub.getDOMNode().innerHTML).toEqual('goodbye'); }); it(\"should transition from innerHTML to string content\", function() { var stub = ReactTestUtils.renderIntoDocument(
); expect(stub.getDOMNode().innerHTML).toEqual('bonjour'); stub.receiveProps({children: 'adieu'}, transaction); expect(stub.getDOMNode().innerHTML).toEqual('adieu'); }); it(\"should not incur unnecessary DOM mutations\", function() { var stub = ReactTestUtils.renderIntoDocument(
);"} {"_id":"q-en-react-3960063a2216545d93697ac670de471b5fa68e2314de7dc297b474e9147e36ce","text":"SimulateNative: {}, act(callback: () => void): Thenable { if (actContainerElement === null) { // warn if we can't actually create the stub element if (__DEV__) { warningWithoutStack( typeof document !== 'undefined' && document !== null && typeof document.createElement === 'function', 'It looks like you called TestUtils.act(...) in a non-browser environment. ' + \"If you're using TestRenderer for your tests, you should call \" + 'TestRenderer.act(...) instead of TestUtils.act(...).', ); } // then make it actContainerElement = document.createElement('div'); } const result = ReactDOM.unstable_batchedUpdates(callback); // note: keep these warning messages in sync with // createReactNoop.js and ReactTestRenderer.js const result = ReactDOM.unstable_batchedUpdates(callback); if (__DEV__) { if (result !== undefined) { let addendum;"} {"_id":"q-en-react-3ad52d7c459f4a0e4a6a2c2e5a5974c6a8b9709818b342eaf6a7231e8f735047","text":"reactComponentExpect = require('reactComponentExpect'); React = require('React'); ReactComponent = require('ReactComponent'); ReactCurrentOwner = require('ReactCurrentOwner'); ReactDoNotBindDeprecated = require('ReactDoNotBindDeprecated'); ReactPropTypes = require('ReactPropTypes');"} {"_id":"q-en-react-44b109529c17da3a51894951913509ba4cf0770160044dff97cdc6a134640782","text":"cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, challenge: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, classID: MUST_USE_ATTRIBUTE, // To set className on SVG elements, it's necessary to use .setAttribute;"} {"_id":"q-en-react-468f3449a0008c818d29505a774383a2010ab4a9cedc64dba144f8d434803ea9","text":"ReactCurrentOwner.current = this; var inst = this._instance; try { renderedComponent = inst.render(); if (__DEV__) { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactContext.current = previousContext; ReactCurrentOwner.current = null;"} {"_id":"q-en-react-4734459bb16532eb5aafa8f3bbb5dd04693fbfbd22abcd7e1fb13c89b20cc667","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":"q-en-react-498560f2b171c7edbbf8619146ff8cc1b5bbdecccefa1dfbdce3ef14e872e74f","text":"static .grunt _SpecRunner.html __benchmarks__ build/ .module-cache *.gem"} {"_id":"q-en-react-49987896124250b1ee8db135cc5d7acde06a25b7c00554b3b6e4ea0fce834e84","text":"asap \"~2.0.3\" prop-types@^15.5.8: version \"15.5.8\" resolved \"https://registry.yarnpkg.com/prop-types/-/prop-types-15.5.8.tgz#6b7b2e141083be38c8595aa51fc55775c7199394\" version \"15.5.10\" resolved \"https://registry.yarnpkg.com/prop-types/-/prop-types-15.5.10.tgz#2797dfc3126182e3a95e3dfbb2e893ddd7456154\" dependencies: fbjs \"^0.8.9\" loose-envify \"^1.3.1\" prr@~0.0.0: version \"0.0.0\""} {"_id":"q-en-react-4c90c9a926583776dbf8862db3d9de83b74f66680db5e7771d33354fe9f578ab","text":"this._updater, ); this._updateStateFromStaticLifecycle(element.props); if (typeof element.type.getDerivedStateFromProps === 'function') { const partialState = element.type.getDerivedStateFromProps.call( null, element.props, this._instance.state, ); if (partialState != null) { this._instance.state = Object.assign( {}, this._instance.state, partialState, ); } } if (element.type.hasOwnProperty('contextTypes')) { currentlyValidatingElement = element;"} {"_id":"q-en-react-4e8e1565bb1cace3befc7dcda3adf7df21abaaeada18815a999f4f6f20de67b9","text":"}); var ShallowMixin = assign({}, ReactCompositeComponentMixin, { /** * Initializes the component, renders markup, and registers event listeners. * * @param {string} rootID DOM ID of the root node. * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {number} mountDepth number of components in the owner hierarchy * @return {ReactElement} Shallow rendering of the component. * @final * @internal */ mountComponent: function(rootID, transaction, mountDepth) { ReactComponent.Mixin.mountComponent.call( this, rootID, transaction, mountDepth ); var inst = this._instance; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING; // No context for shallow-mounted components. inst.props = this._processProps(this._currentElement.props); var initialState = inst.getInitialState ? inst.getInitialState() : null; if (__DEV__) { // We allow auto-mocks to proceed as if they're returning null. if (typeof initialState === 'undefined' && inst.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } invariant( typeof initialState === 'object' && !Array.isArray(initialState), '%s.getInitialState(): must return an object or null', inst.constructor.displayName || 'ReactCompositeComponent' ); inst.state = initialState; this._pendingState = null; this._pendingForceUpdate = false; if (inst.componentWillMount) { inst.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingState` without triggering a re-render. if (this._pendingState) { inst.state = this._pendingState; this._pendingState = null; } } // No recursive call to instantiateReactComponent for shallow rendering. this._renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); // Done with mounting, `setState` will now trigger UI changes. this._compositeLifeCycleState = null; // No call to this._renderedComponent.mountComponent for shallow // rendering. if (inst.componentDidMount) { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } return this._renderedComponent; }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function(transaction) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; // Use the without-owner-or-context variant of _rVC below: var nextRenderedElement = this._renderValidatedComponentWithoutOwnerOrContext(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { prevComponentInstance.receiveComponent( nextRenderedElement, transaction ); } else { // These two IDs are actually the same! But nothing should rely on that. var thisID = this._rootNodeID; var prevComponentID = prevComponentInstance._rootNodeID; // Don't unmount previous instance since it was never mounted, due to // shallow render. //prevComponentInstance.unmountComponent(); this._renderedComponent = nextRenderedElement; // ^ no instantiateReactComponent // // no recursive mountComponent return nextRenderedElement; } } }); var ReactCompositeComponent = { LifeCycle: CompositeLifeCycle, Mixin: ReactCompositeComponentMixin Mixin: ReactCompositeComponentMixin, ShallowMixin: ShallowMixin };"} {"_id":"q-en-react-4f5ca05be9bf12de509df49a1bc2369786e7cc707fb07112cdeb0b10991cc53d","text":"// For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = {'string': true, 'number': true}; var DANGEROUSLY_SET_INNER_HTML = keyOf({dangerouslySetInnerHTML: null}); var STYLE = keyOf({style: null}); /**"} {"_id":"q-en-react-515b29ee11881e92c3d735806e30784cc4819c5a1da8fd7ef2479c78b9da5066","text":"// Intentionally do not call componentDidUpdate() // because DOM refs are not available. } _updateStateFromStaticLifecycle(props: Object) { if (this._element === null) { return; } const {type} = this._element; if (typeof type.getDerivedStateFromProps === 'function') { const oldState = this._newState || this._instance.state; const partialState = type.getDerivedStateFromProps.call( null, props, oldState, ); if (partialState != null) { const newState = Object.assign({}, oldState, partialState); this._instance.state = this._newState = newState; } } } } let currentlyValidatingElement = null;"} {"_id":"q-en-react-51678c3bd3e4680baa79d1e5057e4666e6015472ebe50ed392a549853ba8b6c0","text":"String type ``` > Note: > > As of v0.12, 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"} {"_id":"q-en-react-52fa3afcc6b9090f8a5009045eaa05e3559e3078515a178b8d27f0e2f46b3951","text":"expect(console.warn.calls.length).toBe(0); }); it('should support injected wrapper components as DOM components', function() { var injectedDOMComponents = [ 'button', 'form', 'iframe', 'img', 'input', 'option', 'select', 'textarea', 'html', 'head', 'body' ]; injectedDOMComponents.forEach(function(type) { var component = ReactTestUtils.renderIntoDocument( React.createElement(type) ); expect(component.tagName).toBe(type.toUpperCase()); expect(ReactTestUtils.isDOMComponent(component)).toBe(true); }); }); });"} {"_id":"q-en-react-53564b213c623cfba3fa212dc2b93306b06ff45c6a7d28a5431b72906fd48898","text":"Next → {% endif %}
"} {"_id":"q-en-react-535c7a8b67305f35d128ac7496de2f759df79e190856d21b010c23c4af7a63fa","text":"*/ executeDispatch: function(event, listener, domID) { var returnValue = EventPluginUtils.executeDispatch(event, listener, domID); warning( typeof returnValue !== 'boolean', 'Returning `false` from an event handler is deprecated and will be ' + 'ignored in a future release. Instead, manually call ' + 'e.stopPropagation() or e.preventDefault(), as appropriate.' ); if (returnValue === false) { event.stopPropagation(); event.preventDefault();"} {"_id":"q-en-react-55ed93c95b89cfb4d7a03d9b171653c7d0376a4f11cc87f288da97bed5918c13","text":"ON_CLICK_KEY, recordID.bind(null, getID(GRANDPARENT)) ); spyOn(console, 'warn'); ReactTestUtils.Simulate.click(CHILD); expect(idCallOrder.length).toBe(1); expect(idCallOrder[0]).toBe(getID(CHILD)); expect(console.warn.calls.length).toEqual(1); expect(console.warn.calls[0].args[0]).toBe( 'Warning: Returning `false` from an event handler is deprecated and ' + 'will be ignored in a future release. Instead, manually call ' + 'e.stopPropagation() or e.preventDefault(), as appropriate.' ); }); /**"} {"_id":"q-en-react-5929f62864a44b69496913c49c6e395211bd5259cb40403cd7beea18d2f32348","text":"var MorphingComponent; var ChildUpdates; var React; var ReactComponent; var ReactCurrentOwner; var ReactPropTypes; var ReactTestUtils;"} {"_id":"q-en-react-644498b25172923430968e6f65e86cb9c4cc558d4a26844ecbd495a5405bc6db","text":"setRefreshHandler: __DEV__ ? setRefreshHandler : null, // Enables DevTools to append owner stacks to error messages in DEV mode. getCurrentFiber: __DEV__ ? getCurrentFiberForDevTools : null, // Enables DevTools to detect reconciler version rather than renderer version // which may not match for third party renderers. reconcilerVersion: ReactVersion, }); }"} {"_id":"q-en-react-668254523681a0d5e096d62901f5499efd318121a7c9a2bdb17c4ba2f67bb4be","text":"frame.debugElementStack = []; } this.stack.push(frame); this.previousWasTextNode = false; return out; } }"} {"_id":"q-en-react-6b69fb32ce93465fc57a456256dc3cc3d407ee4a4b661ed31fd88be37464c66d","text":"/** * @private */ _renderValidatedComponentWithoutOwnerOrContext: function() { var inst = this._instance; var renderedComponent = inst.render(); if (__DEV__) { // We allow auto-mocks to proceed as if they're returning null. if (typeof renderedComponent === 'undefined' && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: ReactPerf.measure( 'ReactCompositeComponent', '_renderValidatedComponent',"} {"_id":"q-en-react-6c4605bcff962e7970532bc4975441c8a35d51e870d5218ea656af6a717e96a1","text":"httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, keyParams: MUST_USE_ATTRIBUTE, keyType: MUST_USE_ATTRIBUTE, label: null, lang: null, list: MUST_USE_ATTRIBUTE,"} {"_id":"q-en-react-71d2e7ed0b936ec201330e7ff521ce815d042f1380509589f4044829f11909db","text":"findHostInstancesForRefresh, } from './ReactFiberHotReloading.old'; import {markRenderScheduled} from './SchedulingProfiler'; import ReactVersion from 'shared/ReactVersion'; export {registerMutableSourceForHydration} from './ReactMutableSource.old'; export {createPortal} from './ReactPortal'; export {"} {"_id":"q-en-react-77ec2c472351a9f19be4c0cb51ed0b077ff578f9af5252e6f1817a932c0a3fa8","text":"}; }, createRenderer: function() { return new ReactShallowRenderer(); }, Simulate: null, SimulateNative: {} }; /** * @class ReactShallowRenderer */ var ReactShallowRenderer = function() { this._instance = null; }; ReactShallowRenderer.prototype.getRenderOutput = function() { return (this._instance && this._instance._renderedComponent) || null; }; var ShallowComponentWrapper = function(inst) { this._instance = inst; } assign( ShallowComponentWrapper.prototype, ReactCompositeComponent.ShallowMixin ); ReactShallowRenderer.prototype.render = function(element) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); this._render(element, transaction); ReactUpdates.ReactReconcileTransaction.release(transaction); }; ReactShallowRenderer.prototype._render = function(element, transaction) { if (!this._instance) { var rootID = ReactInstanceHandles.createReactRootID(); var instance = new ShallowComponentWrapper(new element.type(element.props)); instance.construct(element); instance.mountComponent(rootID, transaction, 0); this._instance = instance; } else { this._instance.receiveComponent(element, transaction); } }; /** * Exports: * * - `ReactTestUtils.Simulate.click(Element/ReactDOMComponent)`"} {"_id":"q-en-react-78cffa44a5792fa2be826ade74ccdf98e8cc1e3e7b1e8f3af5e56054b949682b","text":"if (consoleSettingsRef.appendComponentStack) { const lastArg = args.length > 0 ? args[args.length - 1] : null; const alreadyHasComponentStack = lastArg !== null && isStringComponentStack(lastArg); typeof lastArg === 'string' && isStringComponentStack(lastArg); // If we are ever called with a string that already has a component stack, // e.g. a React error/warning, don't append a second stack."} {"_id":"q-en-react-847096e512c8ac6d81e2b57a2a45e9c7738a8ed03d4aefc8d3d88e9f7661da24","text":"\"scriptPreprocessor\": \"scripts/jest/preprocessor.js\", \"setupEnvScriptFile\": \"scripts/jest/environment.js\", \"setupTestFrameworkScriptFile\": \"scripts/jest/test-framework-setup.js\", \"testRunner\": \"jasmine1\", \"testFileExtensions\": [ \"coffee\", \"js\","} {"_id":"q-en-react-89f6ad41bb608aa76e5bfa8a414adf2c3657357b5cf38c787f2ac010ca54b5d1","text":"

HTML to JSX Compiler

"} {"_id":"q-en-react-8d35b33f45c3b9cd32106df5f0f8084a8dc2fa11e17086b79dfd8ed2490bdd32","text":"}); describe('act', () => { it('works', () => { it('can use .act() to batch updates and effects', () => { function App(props) { React.useEffect(() => { props.callback();"} {"_id":"q-en-react-8e56bb8e4ddc55562a6a2e64bb114543291f1eea1ae72646e5493afb9deec853","text":"
"} {"_id":"q-en-react-8eb50536e4555f7ff38b9b61c4205d2d40f9876fd74970cecf68cf2d8e423e94","text":"}); }); it('should call componentWillUnmount before unmounting', function() { var container = document.createElement('div'); var innerUnmounted = false; spyOn(ReactMount, 'purgeID').andCallThrough(); var Component = React.createClass({ render: function() { return
; } }); var Inner = React.createClass({ componentWillUnmount: function() { // It's important that ReactMount.purgeID be called after any component // lifecycle methods, because a componentWillMount implementation is // likely call this.getDOMNode(), which will repopulate the node cache // after it's been cleared, causing a memory leak. expect(ReactMount.purgeID.callCount).toBe(0); innerUnmounted = true; }, render: function() { return
; } }); React.renderComponent(, container); React.unmountComponentAtNode(container); expect(innerUnmounted).toBe(true); // , , and both
elements each call // unmountIDFromEnvironment which calls purgeID, for a total of 4. expect(ReactMount.purgeID.callCount).toBe(4); }); it('should detect valid CompositeComponent classes', function() { var Component = React.createClass({ render: function() {"} {"_id":"q-en-react-8f01b6f26551ed4f4f6589e970815783dd769e4f19434bda10e72e49b5863128","text":"jsxScripts.push(scripts.item(i)); } } console.warn(\"You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx\"); jsxScripts.forEach(function(script) {"} {"_id":"q-en-react-8faba1735f6b2d17744137e2793573e876d08674a943e100ee050b84816a75af","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":"q-en-react-90e017b910fb5f9012c2e55afdd99f1b05388ba147d8c60dda5ced79c8b8198d","text":"var elementFactory = ReactElement.createFactory(tag); var FullPageComponent = ReactClass.createClass({ tagName: tag.toUpperCase(), displayName: 'ReactFullPageComponent' + tag, componentWillUnmount: function() {"} {"_id":"q-en-react-9150e6e06b97d98a03759778bc6d8a868b3498f1682a923e9f7db4eaf18c465d","text":"expect(idCallOrder[0]).toBe(getID(CHILD)); }); it('should stopPropagation if false is returned', function() { it('should stopPropagation if false is returned, but warn', function() { ReactBrowserEventEmitter.putListener( getID(CHILD), ON_CLICK_KEY,"} {"_id":"q-en-react-9281b377d108389dd15f0c22c3d42f704551a6c5b41c0d45c2bc5f0496bdd631","text":" ); }"} {"_id":"q-en-react-94713d3eb40ccac98ab526fc50e8a87bace8011c25a74bacd030f423cf503da8","text":"if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (__DEV__) { if (styleName.indexOf('-') > -1) { warnHyphenatedStyleName(styleName); } else if (badVendoredStyleNamePattern.test(styleName)) { warnBadVendoredStyleName(styleName); } warnValidStyle(styleName, styleValue); } var styleValue = styles[styleName]; if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';';"} {"_id":"q-en-react-9622b1a6989f08c645ef8a7a8f4d0d5d53413bfa0e16afe88eae921e7c1f08a5","text":"} `, }, { code: normalizeIndent` export const notAComponent = () => { return () => { useState(); } } `, // TODO: this should error but doesn't. // errors: [functionError('use', 'notAComponent')], }, { code: normalizeIndent` export default () => { if (isVal) { useState(0); } } `, // TODO: this should error but doesn't. // errors: [genericError('useState')], }, { code: normalizeIndent` function notAComponent() { return new Promise.then(() => { useState(); }); } `, // TODO: this should error but doesn't. // errors: [genericError('useState')], }, ], invalid: [ {"} {"_id":"q-en-react-98ce93c3aa5ea92f8eeef061c1a47ffd1bb376293c423a735e4427196b313ba2","text":"findHostInstancesForRefresh, } from './ReactFiberHotReloading.new'; import {markRenderScheduled} from './SchedulingProfiler'; import ReactVersion from 'shared/ReactVersion'; export {registerMutableSourceForHydration} from './ReactMutableSource.new'; export {createPortal} from './ReactPortal'; export {"} {"_id":"q-en-react-a2a4da442c327b4a2d1ac737478dca75b402efb14145b02281e019284612f35c","text":"onMouseMove onMouseOut onMouseOver onMouseUp ``` Properties: Properties: ```javascript boolean altKey"} {"_id":"q-en-react-a91135a233216ad025b910c2d40d8b57bede862e4e31ca57bc002e0143fa4e12","text":"} var frame = this.stack[this.stack.length - 1]; if (frame.childIndex >= frame.children.length) { out += frame.footer; this.previousWasTextNode = false; var footer = frame.footer; out += footer; if (footer !== '') { this.previousWasTextNode = false; } this.stack.pop(); if (frame.tag === 'select') { this.currentSelectValue = null;"} {"_id":"q-en-react-ad400f0906a5e58f732417d8e7d1ed2abb683f00ee5391a64760c9f9bd523ef8","text":"this._instance.context = context; this._instance.props = props; this._instance.state = state; this._newState = null; if (shouldUpdate) { this._rendered = this._instance.render();"} {"_id":"q-en-react-ae0cab8fd1b480d7b6aca79ac62277833403598f1fe39ee4f06e5c46fc44eb46","text":"// 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnHyphenatedStyleName = function(name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {"} {"_id":"q-en-react-b2affc878bffb5a3b588c568275b81ceff7a3973515c301fe0cbdaa3a316b9fd","text":"through2 \"^2.0.0\" fbjs@^0.8.9: version \"0.8.12\" resolved \"https://registry.yarnpkg.com/fbjs/-/fbjs-0.8.12.tgz#10b5d92f76d45575fd63a217d4ea02bea2f8ed04\" version \"0.8.14\" resolved \"https://registry.yarnpkg.com/fbjs/-/fbjs-0.8.14.tgz#d1dbe2be254c35a91e09f31f9cd50a40b2a0ed1c\" dependencies: core-js \"^1.0.0\" isomorphic-fetch \"^2.1.1\""} {"_id":"q-en-react-b5276e3c025854c96c018a31267cb5065d2dce839b7e3fbc0576c90c1807f5ab","text":"it(\"should empty element when removing innerHTML\", function() { var stub = ReactTestUtils.renderIntoDocument(
); expect(stub.getDOMNode().innerHTML).toEqual(':)');"} {"_id":"q-en-react-b8c3b0517f468578990e7a7339ec228395707de3cd69de5b44591f3cb0cc8b94","text":"expect(result).toEqual(
value:1
); }); it('should pass previous state to shouldComponentUpdate even with getDerivedStateFromProps', () => { class SimpleComponent extends React.Component { constructor(props) { super(props); this.state = { value: props.value, }; } static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.value === prevState.value) { return null; } return {value: nextProps.value}; } shouldComponentUpdate(nextProps, nextState) { return nextState.value !== this.state.value; } render() { return
{`value:${this.state.value}`}
; } } const shallowRenderer = createRenderer(); const initialResult = shallowRenderer.render( , ); expect(initialResult).toEqual(
value:initial
); const updatedResult = shallowRenderer.render( , ); expect(updatedResult).toEqual(
value:updated
); });
it('can setState with an updater function', () => { let instance;"} {"_id":"q-en-react-bf2111957274c2323d60535fc90eaa001fbba4cd45864a1d75ac2cd55e643bc0","text":"/** * Same as the default implementation, except cancels the event when return * value is false. * value is false. This behavior will be disabled in a future release. * * @param {object} Event to be dispatched. * @param {function} Application-level callback."} {"_id":"q-en-react-c1468c6f9747d40bb4cd0f1b139cadc9b5e20ead7c597684472de488db53e228","text":"Next → {% endif %}
"} {"_id":"q-en-react-c1a4df081fe5b5160655d7ec209d93c739f0a5a0a4973997ac2d9346705aeee6","text":"name.charAt(0).toUpperCase() + name.slice(1) + '?' ); }; var warnStyleValueWithSemicolon = function(name, value) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; warning( false, 'Style property values shouldn't contain a semicolon. ' + 'Try \"%s: %s\" instead.', name, value.replace(badStyleValueWithSemicolonPattern, '') ); }; /** * @param {string} name * @param {*} value */ var warnValidStyle = function(name, value) { if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value); } }; } /**"} {"_id":"q-en-react-c5e7e616c09a8df01cb00b46b129588cc5f16a21481f36e80ae4278e188152e9","text":"expect(called).toBe(true); }); it('warns and throws if you use TestUtils.act instead of TestRenderer.act in node', () => { // we warn when you try to load 2 renderers in the same 'scope' // so as suggested, we call resetModules() to carry on with the test jest.resetModules(); const {act} = require('react-dom/test-utils'); expect(() => { expect(() => act(() => {})).toThrow('document is not defined'); }).toWarnDev( [ 'It looks like you called TestUtils.act(...) in a non-browser environment', ], {withoutStack: 1}, ); }); }); });"} {"_id":"q-en-react-c7f781806f41408397145a1d0359ee14f9c6f00fc902bf23f89c51c3d0661fd7","text":" ## 4.0.0 * **New Violations:** Consider `PascalCase.useFoo()` calls as Hooks. ([@cyan33](https://github.com/cyan33) in [#18722](https://github.com/facebook/react/pull/18722)) * **New Violations:** Check callback body when it's not written inline. ([@gaearon](https://github.com/gaearon) in [#18435](https://github.com/facebook/react/pull/18435)) * Add a way to enable the dangerous autofix. ([@gaearon](https://github.com/gaearon) in [#18437](https://github.com/facebook/react/pull/18437)) * Offer a more sensible suggestion when encountering an assignment. ([@Zzzen](https://github.com/Zzzen) in [#16784](https://github.com/facebook/react/pull/16784)) * Consider TypeScript casts of `useRef` as constant. ([@sophiebits](https://github.com/sophiebits) in [#18496](https://github.com/facebook/react/pull/18496)) * Add documentation. ([@ghmcadams](https://github.com/ghmcadams) in [#16607](https://github.com/facebook/react/pull/16607)) ## 3.0.0 * **New Violations:** Forbid calling Hooks from classes. ([@ianobermiller](https://github.com/ianobermiller) in [#18341](https://github.com/facebook/react/pull/18341)) * Add a recommended config. ([@SimenB](https://github.com/SimenB) in [#14762](https://github.com/facebook/react/pull/14762)) ## 2.5.0 * Fix a misleading error message in loops. ([@M-Izadmehr](https://github.com/M-Izadmehr) in [#16853](https://github.com/facebook/react/pull/16853)) ## 2.4.0 * **New Violations:** Run checks for functions passed to `forwardRef`. ([@dprgarner](https://github.com/dprgarner) in [#17255](https://github.com/facebook/react/pull/17255)) * **New Violations:** Check for ref usage in any Hook containing the word `Effect`. ([@gaearon](https://github.com/gaearon) in [#17663](https://github.com/facebook/react/pull/17663)) * Disable dangerous autofix and use ESLint Suggestions API instead. ([@wdoug](https://github.com/wdoug) in [#17385](https://github.com/facebook/react/pull/17385)) ## 2.0.0 * **New Violations:** Forbid calling Hooks at the top level. ([@gaearon](https://github.com/gaearon) in [#16455](https://github.com/facebook/react/pull/16455)) * Fix a crash when referencing arguments in arrow functions. ([@hristo-kanchev](https://github.com/hristo-kanchev) in [#16356](https://github.com/facebook/react/pull/16356)) ## 1.x The 1.x releases aren’t noted in this changelog, but you can find them in the [commit history](https://github.com/facebook/react/commits/master/packages/eslint-plugin-react-hooks). "} {"_id":"q-en-react-cbc0b580e3bb55cda19639a54ac1f9fd9455fbc78d872d5f1640d1fd91e16675","text":"}); }); describe('comparing jsx vs .createFactory() vs .createElement()', function() { var Child, mocks; beforeEach(function() { require('mock-modules').dumpCache(); mocks = require('mocks'); React = require('React'); ReactDOM = require('ReactDOM'); ReactTestUtils = require('ReactTestUtils'); var metaData = mocks.getMetadata(React.createClass({ render: function() { return React.createElement('div'); }, })); Child = mocks.generateFromMetadata(metaData); }); describe('when using jsx only', function() { var Parent, instance; beforeEach(function() { Parent = React.createClass({ render: function() { return (
children value
); }, }); instance = ReactTestUtils.renderIntoDocument(); }); it('should scry children but cannot', function() { var children = ReactTestUtils.scryRenderedComponentsWithType(instance, Child); expect(children.length).toBe(1); }); it('does not maintain refs', function() { expect(instance.refs.child).not.toBeUndefined(); }); it('can capture Child instantiation calls', function() { expect(Child.mock.calls[0][0]).toEqual({ foo: 'foo value', children: 'children value' }); }); }); describe('when using parent that uses .createFactory()', function() { var factory, instance; beforeEach(function() { var childFactory = React.createFactory(Child); var Parent = React.createClass({ render: function() { return React.DOM.div({}, childFactory({ ref: 'child', foo: 'foo value' }, 'children value')); }, }); factory = React.createFactory(Parent); instance = ReactTestUtils.renderIntoDocument(factory()); }); it('can properly scry children', function() { var children = ReactTestUtils.scryRenderedComponentsWithType(instance, Child); expect(children.length).toBe(1); }); it('does not maintain refs', function() { expect(instance.refs.child).not.toBeUndefined(); }); it('can capture Child instantiation calls', function() { expect(Child.mock.calls[0][0]).toEqual({ foo: 'foo value', children: 'children value' }); }); }); describe('when using parent that uses .createElement()', function() { var factory, instance; beforeEach(function() { var Parent = React.createClass({ render: function() { return React.DOM.div({}, React.createElement(Child, { ref: 'child', foo: 'foo value' }, 'children value')); }, }); factory = React.createFactory(Parent); instance = ReactTestUtils.renderIntoDocument(factory()); }); it('should scry children but cannot', function() { var children = ReactTestUtils.scryRenderedComponentsWithType(instance, Child); expect(children.length).toBe(1); }); it('does not maintain refs', function() { expect(instance.refs.child).not.toBeUndefined(); }); it('can capture Child instantiation calls', function() { expect(Child.mock.calls[0][0]).toEqual({ foo: 'foo value', children: 'children value' }); }); }); });
"} {"_id":"q-en-react-cbec4e8b3231fe0a9a4359eac227c48acd9ee2d0ba0860cf29ff6cb8b5bde2f6","text":"var invariant = require('invariant'); var keyOf = require('keyOf'); var warning = require('warning'); var topLevelTypes = EventConstants.topLevelTypes;"} {"_id":"q-en-react-cc517894686d322e0991eb59626b2491a10558af6a782f6ba66d0659ea95b699","text":"> lightweight description of what the DOM should look like. We call this process **reconciliation**. Check out [this jsFiddle](http://jsfiddle.net/fv6RD/3/) to see an example of [this jsFiddle](http://jsfiddle.net/2h6th4ju/) to see an example of reconciliation in action. Because this re-render is so fast (around 1ms for TodoMVC), the developer"} {"_id":"q-en-react-cf3d7a26c529e5920d38acc56b78ad0e4fd02429a8067ef39f9d0088e6b6371e","text":"this._defaultProps = null; ReactComponent.Mixin.unmountComponent.call(this); this._renderedComponent.unmountComponent(); this._renderedComponent = null; ReactComponent.Mixin.unmountComponent.call(this); if (this.refs) { this.refs = null; }"} {"_id":"q-en-react-da82db36cff2f8fd8a79f4f349eaa280e9ab783ad80f56092dd2a24e1dac0c82","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":"q-en-react-e01cf8de883d64797435f8e070b494a5eb994cd001b0b27d1ca17d16bf9f43e3","text":"``` onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseUp onMouseMove onMouseOut onMouseOver onMouseUp ``` Properties:"} {"_id":"q-en-react-e04b396dc266aa2a900be31e6e6fcf8bd605749fb7aea73a275fda72365f2cc7","text":"'n in Child (at **)n in Intermediate (at **)n in Parent (at **)', ); }); it('should correctly log Symbols', () => { const Component = ({children}) => { fakeConsole.warn('Symbol:', Symbol('')); return null; }; act(() => ReactDOM.render(, document.createElement('div'))); expect(mockWarn).toHaveBeenCalledTimes(1); expect(mockWarn.mock.calls[0][0]).toBe('Symbol:'); }); });"} {"_id":"q-en-react-e294f92462df05a7ac45349aff35915a9c38a9a6ef490b84db25e9e643634f54","text":"// Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { var lastHtml = lastProp && lastProp.__html; var nextHtml = nextProp && nextProp.__html; if (lastHtml !== nextHtml) { ReactComponent.DOMIDOperations.updateInnerHTMLByID( this._rootNodeID, nextProp ); } } else if (registrationNames[propKey]) { putListener(this._rootNodeID, propKey, nextProp); } else if ("} {"_id":"q-en-react-e4651c7bdd4e33adebf23c307fa8160bfda0845fef08537260b1a4065bb863d8","text":"runScripts = function() { var scripts = document.getElementsByTagName('script'); // Array.prototype.slice cannot be used on NodeList on IE8 var jsxScripts = []; for (var i = 0; i < scripts.length; i++) {"} {"_id":"q-en-react-e6c01ea97c564474be805fdad74db5685bf9ce4255d54884d8cedf7955742ada","text":"For the remainder of this tutorial, we'll be writing our JavaScript code in this script tag. > Note: > > We included jQuery here because we want to simplify the code of our future ajax calls, but it's **NOT** mandatory for React to work. ### Your first component React is all about modular, composable components. For our comment box example, we'll have the following component structure:"} {"_id":"q-en-react-ec3a6bbc822b94b72de6a74f9500a45c2ce38e59e006b982b2726572053a553e","text":"}, /** * Updates a DOM node's innerHTML set by `props.dangerouslySetInnerHTML`. * Updates a DOM node's innerHTML. * * @param {string} id ID of the node to update. * @param {object} html An HTML object with the `__html` property. * @param {string} html An HTML string. * @internal */ updateInnerHTMLByID: function(id, html) { var node = ReactMount.getNode(id); // HACK: IE8- normalize whitespace in innerHTML, removing leading spaces. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html node.innerHTML = (html && html.__html || '').replace(/^ /g, ' '); node.innerHTML = html.replace(LEADING_SPACE, ' '); }, /**"} {"_id":"q-en-react-eee248b139a4947341f76469752352207db9b338ac7aa08a28c22aeda9799eea","text":"'use strict'; var path = require(\"path\"); var grunt = require(\"grunt\"); var expand = grunt.file.expand; var spawn = grunt.util.spawn;"} {"_id":"q-en-react-f137cc7dcf1c140ebdd91e96706ca8a75c9fcce4e355193f02685611615cc659","text":"continue; } if (__DEV__) { if (styleName.indexOf('-') > -1) { warnHyphenatedStyleName(styleName); } else if (badVendoredStyleNamePattern.test(styleName)) { warnBadVendoredStyleName(styleName); } warnValidStyle(styleName, styles[styleName]); } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleName === 'float') {"} {"_id":"q-en-react-f3a060b60bc1bfaf97e0fada063de08b8ca79162b8b597f8126df0beda66ecf2","text":"topKeyUp: eventTypes.keyUp, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topScroll: eventTypes.scroll,"} {"_id":"q-en-react-f41796ab998cdae2715f27792da477ab83033cacb0a1fe67f9aeeff5b2a6a6da","text":"captured: keyOf({onMouseMoveCapture: true}) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({onMouseOut: true}), captured: keyOf({onMouseOutCapture: true}) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({onMouseOver: true}), captured: keyOf({onMouseOverCapture: true}) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({onMouseUp: true}),"} {"_id":"q-en-react-f78b432776740f2ee70b3546ccbb11f9305cb067bb74010166c736a5e647cd42","text":"*/ var textContentAccessor = getTextContentAccessor() || 'NA'; var LEADING_SPACE = /^ /; /** * Operations used to process updates to DOM nodes. This is made injectable via * `ReactComponent.DOMIDOperations`."} {"_id":"q-en-react-f9c985127280d043e8f647b6ba7e16154c5e4f1e6695c621018c33fa9d7738af","text":"args.push(\"--config\" /* from stdin */); var child = spawn({ cmd: \"bin/jsx-internal\", args: args cmd: \"node\", args: [path.join(\"bin\", \"jsx-internal\")].concat(args) }, function(error, result, code) { if (error) { grunt.log.error(error);"} {"_id":"q-en-react-feb85c0cff7d3032a750b51bbf462ee9361d579cc3e86e361449e7b4a34c427a","text":"expect(console.warn.argsForCall[1][0]).toContain('WebkitTransform'); }); it('should warn about style having a trailing semicolon', function() { spyOn(console, 'warn'); CSSPropertyOperations.createMarkupForStyles({ fontFamily: 'Helvetica, arial', backgroundImage: 'url(foo;bar)', backgroundColor: 'blue;', color: 'red; ' }); expect(console.warn.callCount).toBe(2); expect(console.warn.argsForCall[0][0]).toContain('Try \"backgroundColor: blue\" instead'); expect(console.warn.argsForCall[1][0]).toContain('Try \"color: red\" instead'); }); });"}