{"query": "I'm trying to programatically invoke the JSX transformer (using the version of in the npm registry) by running something like Which then throws this error: If I comment out the lines in that require/use the module loads fine and the transformer runs correctly.\nBah, I changed build filenames last minute and didn't properly test the module after :( Thanks for finding this! I guess we should write some tests for the node module too, not just our phantomjs tests. (Very) Short term, you should be able to change to and that will fix the problem. - I guess it's time to figure out what we want to do with npm versions vs library versions. Should we just bump them both for the time being?\nNope, that alone won't do it, we're not even packaging. I totally screwed up the node module :( Fix soon!\nYeah, doesn't look like there's even a directory there. :)", "pos": ["'use strict'; var React = require('./build/React'); var React = require('./build/react'); var visitors = require('./vendor/fbtransform/visitors').transformVisitors; var transform = require('./vendor/fbtransform/lib/transform').transform;", "\"README.md\", \"main.js\", \"bin/jsx\", \"build/React.js\", \"build/react.js\", \"vendor/fbtransform/\", \"vendor/woodchipper.js\" ],"], "neg": []} {"query": "Please make \"requireable\" npm release, already fixed and only new version on npm is needed. I've developed a source transform for JSX for browserify \u2014 which doesn't work properly because of\n1 pushed to npm:", "pos": ["} async function createBundle(bundle, bundleType) { if (shouldSkipBundle(bundle, bundleType)) { return; } const filename = getFilename(bundle, bundleType); const logKey = chalk.white.bold(filename) + chalk.dim(` (${bundleType.toLowerCase()})`);", "); } bundles = bundles.filter(([bundle, bundleType]) => { return !shouldSkipBundle(bundle, bundleType); }); if (process.env.CIRCLE_NODE_TOTAL) { // In CI, parallelize bundles across multiple tasks. const nodeTotal = parseInt(process.env.CIRCLE_NODE_TOTAL, 10);"], "neg": []} {"query": "Trying to run jsx to build into a subdir seems to just exit with no error message: (public/js does exist) However, if run in directly in public it works without a hitch:\nAre there any files in yet? Also potentially useful: what are you running, and what OS?\nThere is a file in src which builds when not using a subdir in the public dir. node version is 0.8.23 and im on OS X Mountain Lion\nInstalled 0.8.23 but no luck reproducing. Will try on a Mountain Lion machine tomorrow. Thanks for the report. Do you see this failure with an empty file? If using an empty file makes the failure go away, perhaps you can try cutting out different parts of the file to figure out the minimal contents that trigger the failure? It could be a problem with on Mountain Lion, though. That's my hunch.\nOne more idea: the module cache might have gotten into a bad state somehow. Try clearing it by deleting the directory ?\nThe same file builds fine if I use (note the lack of public/js). Deleting that directory didn't work for me.\nI know this is still broken. Still working on a fix.\n:heart:\nI had same problem on ubuntu. Yesterday \"jsx --watch\" worked just fine for me. Today when I ssh-ed again and ran \"jsx --watch reactjs/ js/\" it just silently does nothing.\n- I was having issues w/ vim file writes not being caught so I hacked together - Feel free to try it and let me know if it works (Haven't had the time to test on Ubuntu yet...) - We might use the file watcher in that repo in Commoner / JSX in the future.\n:+1: Work like a charm. Thank you very much!\nOk. I think I now know what the issue is. jsx created a file in the output directory. If that file is still there when running jsx again it will quick silently.\nAwesome!", "pos": ["}, \"dependencies\": { \"base62\": \"~0.1.1\", \"commoner\": \"~0.8.0\", \"commoner\": \"~0.8.3\", \"esprima\": \"https://github.com/facebook/esprima/tarball/a3e0ea3979eb8d54d8bfade220c272903f928b1e\", \"recast\": \"~0.4.8\", \"source-map\": \"~0.1.22\""], "neg": []} {"query": "Basically what the title says. After install react-tools, using jsx -w \"commoner\": \"~0.8.0\", \"commoner\": \"~0.8.3\", \"esprima\": \"https://github.com/facebook/esprima/tarball/a3e0ea3979eb8d54d8bfade220c272903f928b1e\", \"recast\": \"~0.4.8\", \"source-map\": \"~0.1.22\""], "neg": []} {"query": ":+1:\n+1\n+1\nI'mma jump on the :+1: bandwagon too. Great idea.\nI don't want to keep duplicated issues opened so just to sumup: said it makes sense to implement \"namespacing\" using colons as opt-in, config-defined option, where one of the possibilities would be a member expression. I don't have enough time to implement it this way, so I closed my issue. More on why&how in jeffmo's final comment and in in general\n+1\n+1\nA non JavaScript-first implementation that wouldn't require changes to :\nPR landing for JSX member expressions , can close this.", "pos": ["utils.catchup(openingElement.range[0], state, trimLeft); if (nameObject.namespace) { throw new Error( 'Namespace tags are not supported. ReactJSX is not XML.'); var isFallbackTag = false; if (nameObject.type === Syntax.XJSIdentifier) { if (nameObject.namespace) { throw new Error( 'Namespace tags are not supported. ReactJSX is not XML.'); } isFallbackTag = FALLBACK_TAGS.hasOwnProperty(nameObject.name); } var isFallbackTag = FALLBACK_TAGS.hasOwnProperty(nameObject.name); utils.append( (isFallbackTag ? jsxObjIdent + '.' : '') + (nameObject.name) + '(', state ); utils.append(isFallbackTag ? jsxObjIdent + '.' : '', state); utils.move(nameObject.range[0], state); utils.catchup(nameObject.range[1], state); utils.move(nameObject.range[1], state); utils.append('(', state); var hasAttributes = attributesObject.length;"], "neg": []} {"query": "http://www.polymer- needs nonstandard touch-action attribute to work. Btw, I don't know why React just don't render anything what user needs? Custom attributes should work OFTB. For control freaks there can be option React.doesNotAllowUnknownAttributtes = true.\nPlease allow touch-action attribute.\nReact needs a list of properties so that it knows whether to use the property accessor or setAttribute when changing the attribute (and also to convert between camel-casing and dash-cased, though that's not as critical). We'd like to make it easy to configure React with custom attributes; sorry this isn't easy right now.\nIt seems your other issue addresses this concern already and I don't see React adding this specific attribute to the global whitelist.", "pos": ["
  • API
  • Appendix

    ", "title: React API layout: docs prev: mixins.html next: jsx-is-not-html.html --- ## React", " --- id: docs-jsx-is-not-html title: JSX is not HTML description: Differences between JSX and HTML. layout: docs prev: api.html --- JSX looks like HTML but there are some important differences you may run into. ## Whitespace removal JSX doesn't follow the same whitespace elimination rules as HTML. JSX removes all the whitespaces between two curly braces expressions. If you want to have a white space, a work-around is to add `{' '}`. ```javascript
    {this.props.name} {' '} {this.props.surname}
    ``` This behavior is still being debated. Follow [Issue #65](https://github.com/facebook/react/issues/65) to be updated on the situation. ## HTML Entities You can insert HTML entities within literal text in JSX: ```javascript
    First · Second
    ``` If you want to display an HTML entity within a dynamic content, you will run into double escaping issues as React escapes all the strings you are displaying in order to prevent a wide range of XSS attacks by default. ```javascript // Bad: It displays \"First · Second\"
    {'First · Second'}
    ``` There are various ways to work-around this issue. The easiest one is to write unicode character directly in Javascript. You've got to make sure that the file is saved as UTF-8 and that the propers UTF-8 directives are set so the browser will display it correctly. ```javascript
    {'First \u00b7 Second'}
    ``` A safer alternative is to find the unicode number corresponding to the entity and use it inside of a Javascript string. ```javascript
    {'First u00b7 Second'}
    {'First ' + String.fromCharCode(183) + ' Second'}
    ``` You can use mixed arrays with strings and JSX elements. ```javascript
    {['First ', ·, ' Second']}
    ``` In last resort, you always have the ability to insert raw HTML inside of the div. ```javascript
    ``` ## Comments JSX supports both single-line and multi-lines Javascript comments within a tag declaration: ```javascript
    ``` As of React 0.3, there is no good way to insert comments within the children section. [Issue #82](https://github.com/facebook/react/issues/82) is tracking progress to enable the following way to write comments: ```javascript // Note: The following is not implemented yet!
    {/* This is a comment */}
    ``` ## Custom HTML attributes If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with `data-`. ```javascript
    ``` [Web Accessibility](http://www.w3.org/WAI/intro/aria) attributes starting with `aria-` will be rendered properly. ```javascript
    ``` "], "neg": []} {"query": "Someone had the trouble in IRC about it. Edit: changed the subject from \"document it\" to \"support it\", because the documentation issue is already at .\nBetter yet, support it!\nYeah, is there a particular reason it's not supported?\nCurious if you've seen the . It's automatically injected into React by default, so you can use it today. IMHO it's (much) better than . (I suppose we could support just for the sake of completeness, but I thought I'd just make sure you guys were aware of .)\nWe discussed this for a bit on IRC -- was just confused that silently didn't work whereas other events did -- perhaps adding more documentation () will fix the problem too but it seems like we might as well add for completeness. (I agree that enter/leave are much more useful and suggested that over/out are likely missing simply because no one has needed them!)\nAgree - I believe there are a few extra allocations (not-pooled) occuring in the event system already today. I'd love to track those down before adding more mouse-move event allocations. If you open the memory profiler in Chrome and move the mouse around, you'll see memory being allocated (and then properly freed of course) but if we use es everywhere, we should be flat. That would make me much more comfortable with adding to . Edit: Just checked out - we already have which fires way more frequently than would so it's probably not such a big deal to add - though we really should get rid of all additional allocations in the event path.\nJust started to look a little bit into the allocations here. Redefining trapBubbledEvent in ReactEventEmitter with: still shows allocations in the Chrome memory timeline view, so I'm not convinced that there's anything we can do here? (Replacing trapBubbledEvent itself with a noop makes the allocations go away. simply calls addEventListener.)\nI am pretty sure we have done all we can here -- at least I think we've tracked down every callsite where PooledClass would have helped us. I updated our recast transforms to log every syntax construct that would cause an obvious allocation and couldn't find anything. I was thinking maybe there was an array slice or a bind() in there, but experiment shows that this is not the case.\n(I didn't verify that we don't have more allocations than the empty-function case; I don't know of a good way to do so.)\nI might be misinformed, but isn't there quite a difference in use cases between mouseenter and mouseover events? Here's a theoretical (non-react) example working with some hover states for nested elements: I tried to apply the above concept in react (with nested components) using onMouseEnter instead, but it obviously fails because it's only triggered once on the top-most element. Moving into a child element and back has no effect. Maybe there's a better approach for this in react altogether?\nIf you render the child hierarchy with React, you can listen to on each child element you are interested in instead of using event bubbling. It is cheap.", "pos": ["``` onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseUp onMouseMove onMouseOut onMouseOver onMouseUp ``` Properties:", "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}),", "topKeyUp: eventTypes.keyUp, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topScroll: eventTypes.scroll,", "case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break;"], "neg": []} {"query": "reported the following issue on IRC: (Both on master and 4.0) The repro case is: 1) Render 2) Render 3) Render the same as 1) The div has its innerHTML empty instead of . I don't really know what's going on. can you guys look at it?\nOne other tidbit: this only seems to happen when the value is exactly the same in step 3 as it was in step 1. If it's different (i.e. ), things work as expected.\nWhat happens if you change step 2 to a instead of a ? It works, right?\nI just reduced the test case to 19 lines.\nyeah changing 2) to use a span works as expected\nIf anyone wants to look into this, the bug is probably here\nI cannot reproduce what you are seeing: It also bugs if I use a different string\nI'm not able to reproduce that particular behavior given this small repro case. The original code had several more layers... will keep trying.\nI know this is a very old issue but I had a similar problem and came across this. I found that this problem occurs when you do not add a property to the React component containing the property. So, does not seem to work reproducibly, whereas seems to. I think this could be related to React's diffing algorithm that might not properly treat a component with a statement if that component gets rerendered multiple times with different inner content. Just posting this here in case other people have the same issue and stumble upon this.\nthx you saved my day :-)\nSeems like the issue is back again. Thanks, solves the problem for me too.\nIf any of you can post a simple repro case showing the broken behavior here, I'd be happy to take a look at fixing it.\nTook me a while to repro, but here you go: (ugly, but demonstrates the issue well)\nThanks. This is the same issue as . No fix currently, but using the key as a workaround is fine and I'll see if we can fix this sometime.\nThanks that was giving me fits!\nIf anyone is still seeing issues on 0.14, please make a new issue with a simple repro case.\nI have this issue, but can't reproduce in a simple example - my original code is layered and I think that's the reason the real DOM doesn't reconcile. In the react debugger is looks as dangerouslySetInnerHTML has proper __html value, but it doesn't equeal to the innerHTML of the actual element. I used an extremely simple (and equally nasty) workaround. Writing it here just in case it will help someone:\nReading out will rarely give you what you put in because the browser does various kinds of normalization on it. If you can repro with a standalone example though I'm happy to take a look.\nwell, that's more like a control shot :-)\nLooks like the issue still exist in 16.4.1 when using on a tag, you cannot nest other or . issue is fixed by replacing the container with a\nIf you experience something similar three years later, and the original issue is closed, you can be sure it's a different unrelated issue. :-) Please file a new one. We don't keep track of closed issues so your feedback is unfortunately going into the void. When filing a new issue, please provide a reproducing example. when using dangerouslySetInnerHTML on a tag, you cannot nest other or This sounds like browsers work. You can't nest into . This is why React warns when you do it (except in which case React can't validate it).", "pos": ["*/ var textContentAccessor = getTextContentAccessor() || 'NA'; var LEADING_SPACE = /^ /; /** * Operations used to process updates to DOM nodes. This is made injectable via * `ReactComponent.DOMIDOperations`.", "}, /** * 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, ' '); }, /**", "// 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}); /**", "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", "// 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 (", "_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); } },", "ReactDOMIDOperations.updateInnerHTMLByID( 'testID', {__html: ' testContent'} ' testContent' ); expect(", "it(\"should empty element when removing innerHTML\", function() { var stub = ReactTestUtils.renderIntoDocument(
    ); expect(stub.getDOMNode().innerHTML).toEqual(':)');", "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(
    );"], "neg": []} {"query": "This makes it basically unusable in any nontrivial project. While people shouldn't be using this in production, we should still fix this bug for newbies and people using it for hackathons.\nThis should be relatively easy. What should we do with inline tags?", "pos": ["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) {", "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++) {", "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) {"], "neg": []} {"query": "See Return a string from and call . You get this amazing error message:\nWe should probably add an that whatever is returned from is in fact an object.\nInvariant all the things :)\nThis also seems to apply when using an array, not the string only. Which makes it a pretty real-world bug IMHO (compared to the weird string scenario). Or is there a reason you don't want states to be arrays?\nThis will happen whenever state is anything but an Object (I think there is a check in there for arrays). Since we use merge it needs to be an object, arrays are no good either.", "pos": ["} this.state = this.getInitialState ? this.getInitialState() : null; invariant( typeof this.state === 'object' && !Array.isArray(this.state), '%s.getInitialState(): must return an object or null', this.constructor.displayName || 'ReactCompositeComponent' ); this._pendingState = null; this._pendingForceUpdate = false;", "); }); it('should work with a null getInitialState() return value', function() { var Component = React.createClass({ getInitialState: function() { return null; }, render: function() { return ; } }); expect(() => ).not.toThrow(); }); it('should work with object getInitialState() return values', function() { var Component = React.createClass({ getInitialState: function() { return { occupation: 'clown' }; }, render: function() { return ; } }); var instance = ; ReactTestUtils.renderIntoDocument(instance); expect(instance.state.occupation).toEqual('clown'); }); it('should throw with non-object getInitialState() return values', function() { [['an array'], 'a string', 1234].forEach(function(state) { var Component = React.createClass({ getInitialState: function() { return state; }, render: function() { return ; } }); var instance = ; expect(function() { ReactTestUtils.renderIntoDocument(instance); }).toThrow( 'Invariant Violation: Component.getInitialState(): ' + 'must return an object or null' ); }); }); it('should detect valid CompositeComponent classes', function() { var Component = React.createClass({ render: function() {"], "neg": []} {"query": "Should be as simple as making sure we include the polyfills we document\nSomehow I assumed it was intentional that the polyfills weren't included, now I feel silly.\nEh, not really intentional, just never bothered to do it. Looking back it's a bit silly for us to say that we work in IE8 but not prove it.\nIt's ok guys, don't blame yourself for that IE8 story :) (this post is related to : !topic/reactjs/Z2jNf7za7cM) Meanwhile, I've just replied to Paul. Maybe you can help there because I'm stuck :+1: Thanks for your support and the work you've accomplished.\nHmm, it would appear this won't be possible so long as we use JSXTransform on the site. We could fix the NodeList -array issue, but we won't (and shouldn't try to) make changes to esprima to make it work (I think it's mostly using \"reserved\" words as keys. I guess we can turn this bug into \"include polyfills, make sure things works as well as possible, provide some warnings if using IE8 about the problem\"\nSo basically (tell me if I'm wrong) JSXTransform is not compatible with IE8.0 ? But ReactJS should be compatible, right ?\nCorrect. I just tested this myself with the zip I emailed to you - it's online for now at\nThanks zpao (you can remove it from your server if you wish I downloaded the srcs). I would recommend to add the non JSXTransformed example to git or the tutorial maybe ? Again thanks Paul and Spicyj for you help.\nThis should be easy now that has landed.\n8 is out with , so this should be even easier to jump into.", "pos": [" // Copyright 2009-2012 by contributors, MIT License // vim: ts=4 sts=4 sw=4 expandtab //Add semicolon to prevent IIFE from being passed as argument to concated code. ; // Module systems magic dance (function (definition) { // RequireJS if (typeof define == \"function\") { define(definition); // YUI3 } else if (typeof YUI == \"function\") { YUI.add(\"es5-sham\", definition); // CommonJS and "], "neg": []} {"query": "When using ReactLink with checkboxes or dropdowns, the state should not be bound to 'value', but to 'checked' and 'selected' instead.\nI guess it's not obvious what the API should be here. I suppose the most obvious way is to do but keep as-is (and should still not work). Any opinions?\nEither or change to do the same thing as ?", "pos": ["'radio': true }; function _assertLink(input) { function _assertSingleLink(input) { invariant( input.props.checkedLink == null || input.props.valueLink == null, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don't want to use valueLink and vice versa.' ); } function _assertValueLink(input) { _assertSingleLink(input); invariant( input.props.value == null && input.props.onChange == null, 'Cannot provide a valueLink and a value or onChange event. If you want ' +", "); } function _assertCheckedLink(input) { _assertSingleLink(input); invariant( input.props.checked == null && input.props.onChange == null, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don't want to ' + 'use checkedLink' ); } /** * @param {SyntheticEvent} e change event to handle */", "} /** * @param {SyntheticEvent} e change event to handle */ function _handleLinkedCheckChange(e) { /*jshint validthis:true */ this.props.checkedLink.requestChange(e.target.checked); } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */", "); } } }, checked: function(props, propName, componentName) { if (__DEV__) { if (props[propName] && !props.onChange && !props.readOnly && !props.disabled) { console.warn( 'You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.' ); } } } } },", "*/ getValue: function(input) { if (input.props.valueLink) { _assertLink(input); _assertValueLink(input); return input.props.valueLink.value; } return input.props.value;", "/** * @param {ReactComponent} input Form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function(input) { if (input.props.checkedLink) { _assertCheckedLink(input); return input.props.checkedLink.value; } return input.props.checked; }, /** * @param {ReactComponent} input Form component * @return {function} change callback either from onChange prop or link. */ getOnChange: function(input) { if (input.props.valueLink) { _assertLink(input); _assertValueLink(input); return _handleLinkedValueChange; } else if (input.props.checkedLink) { _assertCheckedLink(input); return _handleLinkedCheckChange; } return input.props.onChange; }", "props.defaultChecked = null; props.defaultValue = null; props.checked = this.props.checked != null ? this.props.checked : this.state.checked; var value = LinkedValueUtils.getValue(this); props.value = value != null ? value : this.state.value; var checked = LinkedValueUtils.getChecked(this); props.checked = checked != null ? checked : this.state.checked; props.onChange = this._handleChange; return input(props, this.props.children);", "expect(React.renderComponent.bind(React, instance, node)).toThrow(); }); it('should support checkedLink', function() { var container = document.createElement('div'); var link = new ReactLink(true, mocks.getMockFunction()); var instance = ; React.renderComponent(instance, container); expect(instance.getDOMNode().checked).toBe(true); expect(link.value).toBe(true); expect(link.requestChange.mock.calls.length).toBe(0); instance.getDOMNode().checked = false; ReactTestUtils.Simulate.click(instance.getDOMNode()); expect(link.requestChange.mock.calls.length).toBe(1); expect(link.requestChange.mock.calls[0][0]).toEqual(false); }); it('should warn with checked and no onChange handler', function() { var oldWarn = console.warn; try { console.warn = mocks.getMockFunction(); var node = document.createElement('div'); var link = new ReactLink(true, mocks.getMockFunction()); React.renderComponent(, node); expect(console.warn.mock.calls.length).toBe(0); React.renderComponent( , node ); expect(console.warn.mock.calls.length).toBe(0); React.renderComponent( , node ); expect(console.warn.mock.calls.length).toBe(0); React.renderComponent(, node); expect(console.warn.mock.calls.length).toBe(1); React.renderComponent( , node ); expect(console.warn.mock.calls.length).toBe(2); } finally { console.warn = oldWarn; } }); it('should throw if both checked and checkedLink are provided', function() { // Silences console.error messages // ReactErrorUtils.guard is applied to all methods of a React component // and calls console.error in __DEV__ (true for test environment) spyOn(console, 'error'); var node = document.createElement('div'); var link = new ReactLink(true, mocks.getMockFunction()); var instance = ; expect(React.renderComponent.bind(React, instance, node)).not.toThrow(); instance = ; expect(React.renderComponent.bind(React, instance, node)).toThrow(); instance = ; expect(React.renderComponent.bind(React, instance, node)).toThrow(); }); it('should throw if both checkedLink and valueLink are provided', function() { // Silences console.error messages // ReactErrorUtils.guard is applied to all methods of a React component // and calls console.error in __DEV__ (true for test environment) spyOn(console, 'error'); var node = document.createElement('div'); var link = new ReactLink(true, mocks.getMockFunction()); var instance = ; expect(React.renderComponent.bind(React, instance, node)).not.toThrow(); instance = ; expect(React.renderComponent.bind(React, instance, node)).not.toThrow(); instance = ; expect(React.renderComponent.bind(React, instance, node)).toThrow(); }); });"], "neg": []} {"query": "Consider this example: If is false or undefined, will be and will throw\nWant to take a go at fixing this? I think it would be a good opportunity to learn a bit more about a constrained subset of internals.\nyea - i'll give it a shot :)", "pos": ["var children = {}; var childMapping = ReactTransitionKeySet.getChildMapping(sourceChildren); var transitionConfig = this.getTransitionConfig(); var currentKeys = ReactTransitionKeySet.mergeKeySets( this._transitionGroupCurrentKeys,", "* in `next` in a reasonable order. */ mergeKeySets: function(prev, next) { prev = prev || {}; next = next || {}; var keySet = {}; var prevKeys = Object.keys(prev).concat([MERGE_KEY_SETS_TAIL_SENTINEL]); var nextKeys = Object.keys(next).concat([MERGE_KEY_SETS_TAIL_SENTINEL]);", "// Most of the real functionality is covered in other unit tests, this just // makes sure we're wired up correctly. describe('ReactTransitionGroup', function() { var container; beforeEach(function() { React = require('React'); ReactTransitionGroup = require('ReactTransitionGroup'); mocks = require('mocks'); container = document.createElement('div'); }); it('should warn after time with no transitionend', function() { var container; var a; container = document.createElement('div'); a = React.renderComponent( var a = React.renderComponent( ,", "}); it('should keep both sets of DOM nodes around', function() { var container = document.createElement('div'); var a = React.renderComponent( ", "expect(a.getDOMNode().childNodes[0].id).toBe('two'); expect(a.getDOMNode().childNodes[1].id).toBe('one'); }); describe('with an undefined child', function () { it('should fail silently', function () { var a = React.renderComponent( , container ); }); }); });", "five: true }); }); it('should support mergeKeySets with undefined input', function () { var prev = { one: true, two: true }; var next = undefined; expect(ReactTransitionKeySet.mergeKeySets(prev, next)).toEqual({ one: true, two: true }); prev = undefined; next = { three: true, four: true }; expect(ReactTransitionKeySet.mergeKeySets(prev, next)).toEqual({ three: true, four: true }); }); });"], "neg": []} {"query": "I'd rather do it , if you don't mind.\nI think we should do both. I think a forced clean should force clean all of the build artifacts (of which .module-cache is a part of).\ncan we distinguish between and ?\nIn what situation would you want to clean but not remove ?\nI'm actually not aware of any other use cases for so maybe this is fine. But it still means we need to tell people to do if they encounter problems that might be fixed by doing so, whereas gives us a way to get the same effect with no verbal communication.\nI'm going to do it. I think we should probably also do .\nClosed by .", "pos": ["var getDebugConfig = function() { return { \"debug\": true, \"commonerConfig\": grunt.config.data.pkg.commonerConfig, \"constants\": { \"__VERSION__\": grunt.config.data.pkg.version, \"__DEV__\": true", "return { \"debug\": true, \"mocking\": true, \"commonerConfig\": grunt.config.data.pkg.commonerConfig, \"constants\": { \"__VERSION__\": grunt.config.data.pkg.version, \"__DEV__\": true", "getConfig: function() { return { \"debug\": false, \"commonerConfig\": grunt.config.data.pkg.commonerConfig, \"constants\": { \"__VERSION__\": grunt.config.data.pkg.version, \"__DEV__\": false", "\"engines\": { \"node\": \">=0.10.0\" }, \"preferGlobal\": true \"preferGlobal\": true, \"commonerConfig\": { \"version\": 1 } }"], "neg": []} {"query": "This may be controversial, but after browsing StackOverflow I believe there's way too many people that load jQuery when they really don't need it. Let's not add to that. I don't think we should be loading jQuery in the tutorial just to do an AJAX request. Let's instead have a dummy object that just returns a static list. Which could simply be replaced to implement AJAX loading. Old post (before I thought of just using static data): Let's replace it with standard XMLHttpRequest code and say something like \"Here's some simple code for doing an AJAX request, alternatively you could use your favourite framework like jQuery, MooTools, YUI, ... instead\". Having jQuery loaded in the tutorial may make people think that jQuery is necessary to use React.\nI was thinking about this more and using a static list would probably be better than AJAX (given the tutorial just AJAX loads a static file). Updated the description to reflect this.\nI think that would be fine. I would still put the equivalent jQuery call because that will be the inevitable question.\nAfter reading pretty much everything related to this issue, I think it would be a good idea to add (for now) a little note in the tutorial, just under the code snippet having the jQuery inclusion. I think it's the only place it really needs to be. What do you think ? (So we can finally close this issue)\nAgreed. A beginner tutorial isn't the place to debate jquery vs no jquery. The point is familiarity.\nFor what it's worth, I removed the use of jQuery in the ReactJS.NET version of the tutorial:\n^ The note about jQuery not being mandatory got merged. I think this is good for now for newcomers. The react users probably already realized they don't actually need jQuery. Closing for now! =)\nIt dose not look very good when you are introducing new people to React and the first ting in the tutorial is: \"We need to do some Ajax calls, let's just add jQuery\".", "pos": ["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:"], "neg": []} {"query": "Here's an example: (no jsfiddle because that's broken in IE8)\nI tried to fix this bug yesterday but had a bad time trying to find a fix for a similar cases. I looked at current well maintained libraries and didn't find a way to make scroll bubble or capture it on IE8. Seems like trying to fix it would be a waste of time and would make code much complex, for a browser that is slowly dying. My suggestion is to point that out on the documentation.\nSeems like this isn't so easy. Let's do what says and document it.\ndo you think that we should do a everytime someone uses onScroll on any browser or would that be annoying? I would say it would be annoying but it would also be very frustrating to figure that it's a React limitation after some hours of debugging on IE8 (ugh!)\n+1 on the warning -- would be super helpful.\nreopening so we can add a warning\nWarning was in\nNow that events are listened on demand, maybe the warning should be moved to method, where support is already checked?\nIt also prints the warning if you render on the server, its annoying :/\nThat's odd, I wouldn't expect that code to run at all when using server rendering.\nI see this warning when I'm doing with . Any chance to disable it?\nI also see this error when using ssr\nThis is happening to me with JSDOM as well and in my case our team project standards aren't going to accommodate leaving these errors in the console when tests are run. How can I suppress or stub this out. It's not just obnoxious it is preventing me from getting my work merged in our project.\n/ - I am now seeing this error after upgrading my version of Enzyme to . Did you find a way to suppress these warnings for JSDOM?\nIf you're having problems please file a new issue. Nobody actively reads old issues, and requests for help here will get lost.", "pos": ["* `Object.create` \u2013 Provided by `es5-sham.js` from [kriskowal's es5-shim](https://github.com/kriskowal/es5-shim). * `console.*` \u2013 Only needed when using the unminified build. If you need to polyfill this, try [paulmillr's console-polyfill](https://github.com/paulmillr/console-polyfill). ### Cross-browser Issues Although React is pretty good at abstracting browser differences, some browsers are limited or present quirky behaviors that we couldn't find a workaround. #### onScroll event on IE8 On IE8 the `onScroll` event doesn't bubbles and IE8 doesn't have an API to define handlers to the capturing phase of an event, meaning there is no way for React to listen to these events. Currently a handler to this event is ignored on IE8. See the [onScroll doesn't work in IE8](https://github.com/facebook/react/issues/631) GitHub issue for more information. "], "neg": []} {"query": "Please see: and do the following: 'Toggle' to make the list-item fade into view. -click/Spam-click the 'Toggle' button again to make the item fade-out of view. 'Toggle' again to try to make the component come back into view. You'll see that the item doesn't come back! If you check the HTML, you can see that the list-item is still there, with the class name \"example-leave example-leave-active\". I suspect that React should reverse the animation elegantly in the case of the same component being re- in the render function during a leave transition.\nThanks, I was going to point you to but I see that you're the author of it!\nHehe, I thought perhaps it'd be best if I made a proper Issue (with JSFiddle example!) rather than just rudely posting Pull Requests! :)", "pos": ["componentWillReceiveProps: function(nextProps) { if (!nextProps.children && this.props.children) { this.savedChildren = this.props.children; } else if (nextProps.children && !this.props.children) { // We're being told to re-add the child. Let's stop leaving! if (this.isMounted()) { var node = this.getDOMNode(); var className = this.props.name; CSSCore.removeClass(node, className + '-leave'); CSSCore.removeClass(node, className + '-leave-active'); if (this.props.enter) { CSSCore.addClass(node, className + '-enter'); CSSCore.addClass(node, className + '-enter-active'); } } } },"], "neg": []} {"query": "When unmounting components like this: a memory leak happens because ReactMount.getID(node) puts DOM nodes back to nodeCache if they are not there.. just right after they were purged from cache. Here is what's happing when unmounting that example component: label component gets purged from nodeCache when ReactDOMInput component is going to unmount it calls this method: which contains this.getDOMNode() which iterates through the children of the Form element calling getID() on each of them.. which puts these elements back into the cache. So first they were purged and here they are all put back in cache causing a memory leak :( I'm playing with React just 3rd day so not sure of a way to correctly fix this issue\n(I took the liberty to edit your comment to add syntax highlighting)\nI can't reproduce this. With this diff applied, I loaded http://127.0.0.1:8000/examples/ballmer-peak/ in the console and checked -- it was empty. Am I misunderstanding?\nYes. You've missed one more user defined component in there.. Here you go:\nThanks, fixed in .\nThank you for fast fix :)\nThanks for the find/fix!", "pos": ["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; }", "* @internal */ unmountComponent: function() { this.unmountChildren(); ReactEventEmitter.deleteAllListeners(this._rootNodeID); ReactComponent.Mixin.unmountComponent.call(this); this.unmountChildren(); } };", "var MorphingComponent; var ChildUpdates; var React; var ReactComponent; var ReactCurrentOwner; var ReactPropTypes; var ReactTestUtils;", "reactComponentExpect = require('reactComponentExpect'); React = require('React'); ReactComponent = require('ReactComponent'); ReactCurrentOwner = require('ReactCurrentOwner'); ReactDoNotBindDeprecated = require('ReactDoNotBindDeprecated'); ReactPropTypes = require('ReactPropTypes');", "}); }); 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() {"], "neg": []} {"query": "I don't know where the right place to link to them is. Maybe \"Getting started\", \"Tutorial\" and \"Tooling integration\"?", "pos": ["that support `*.tmLanguage`. * Linting provides accurate line numbers after compiling without sourcemaps. * Elements use standard scoping so linters can find usage of out-of-scope components. ### Debugging [React Developer Tools](https://github.com/facebook/react-devtools) is a [Chrome extension](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en) that allows you to inspect the React component hierarchy in the Chrome Developer Tools. "], "neg": []} {"query": "I couldn't find a reference to the fact that jsx transform attaches to the component spec, this would be nice to document somewhere (more importantly, that not using jsx means debugging messages will be littered with ). I found this while using .\nThat would be very nice indeed. If you want to take a stab at it, the docs are in the repo in the markdown format. Would love to have you on the contributor list :)", "pos": ["var app = ; ``` JSX will infer the component's name from the variable assignment and specify the class's [displayName](/react/docs/component-specs.html#displayName) accordingly. See [Multiple Components](/react/docs/multiple-components.html) to learn more about using composite components. > Note:", " ### displayName ```javascript string displayName ``` The `displayName` string is used in debugging messages. JSX sets this value automatically, see [JSX in Depth](react/docs/jsx-in-depth.html#react-composite-components). ## Lifecycle Methods Various methods are executed at specific points in a component's lifecycle."], "neg": []} {"query": "I ran a few benchmarks on the server (modifying to not use jsdom). The results were surprising, as the browserified was about 30% faster than the npm version, even with . The performance ranking (test run time) was < < < . I suspect is not a regular js object but perhaps a getter and thus carries a penalty when you test for everywhere. Also the minified version might still perform best of all, as at least some time ago V8 used function source length (including comments) as a heuristic for function complexity / compilation time and thus affecting chances for optimization in some cases, but the effect might be negligible.\nis indeed not a regular object, but defined from the native side, so that may be the culprit for server rendering regression: and So this introduced a getter in quite time-sensitive places (around invariants etc) in your otherwise clean codebase. Can you reproduce the issue? /cc\nLately I have been simply using a wrapped module Works great. You could consider switching npm package to some such scheme if there are no downsides.\nMy first attempt was to just add to the top of every file, but unfortunately uglify isn't smart enough to do dead code removal then. I wonder if we should have essentially make two copies of the code -- one for dev, one for prod, so transforms into so we only pay the getter cost once (per module) at require time. Is doing this easy with recast? It's not obvious to me if interacts well with cloning the AST.\nI would love to see this get some attention. 30% improvement out of the box would be awesome. Is there a lot of work to do here?\nI think eventually we will want people to do a build step for server rendering, i.e. webpack's mode. Especially if people start expressing static asset dependencies as statements.\nI'm using webpack and was enough to solve it for me. Is there no such thing in browserify?\nFor browserify there's transform which automatically activates for package. You just need to set before bundling: Thus browserify also can be used for bundling for server rendering.\nCall me all crazy, just had a left field idea. Could the transformer that builds the npm module create 2 complete copies of react? one for dev and one for production? In the the normal version of react could you there look at the and swap which module is returned? This way on server you only get the performance hit once;\nThat's not too crazy. It's a bit annoying from a build process though. I'd love to know what's happening at a larger scale in the node community. It seems like we shouldn't be the first people to encounter this in a larger scale. A couple other ideas\u2026 What if we set in our main module and leave in our code everywhere else. There's some obvious bad behavior there (setting globals). So we could do variants. Only set it when it's not already set. Change to something more unique at build time () and then set that. If we switch to webpack for building the browser bundles, then the solution is super easy, and I'm sure there's a way to do this in browserify too. Another idea: Have a modules which memoizes . This is sounding like something node should do itself, but the code linked to uses ObjectTemplate (which if I'm understand a bit of V8 right doesn't do any caching because values can change). There would still be a lookup cost, but it would just be a property access, not a getter and not a call out to get current environment variables (). This one is trickier because it would mean more code and we won't do this internally. I'd prefer a different solution, even if it's more hacky. If all you're using is React and nothing from , then you could do something like mentioned above. We started shipping the browerified bundles in the npm package, so and will end up giving you the bundles which don't access .\nI don't think we're going to do anything specifically for server rendering other than bundling the builds in like mentioned, but we might change the npm package eventually to be prebuilt using closure or similar.\njust curious why and not ?\nIt was just an example. If that was the actual code I'd do the direct assignment like you suggested.\nah, ok - thanks :)\nany movement on this?\nNo movement, though you can already require the builds from react/dist as mentioned above.\nsince you mentioned Webpack, do you use Webpack for server side code?\nIf you're already using babel on your server-side code (say, via or ), you can add the to get around this problem.\nI wonder why react just can't export from for production env when react package ships with .\nBecause then results in a different copy of code, which will have issues. As long as that is remotely supported (and it's currently how and our addons packages work), we can't do that. we might do something like that in the future though.\ntrue that it's not recommended to run babel on libraries? I've seen a few warnings about this. Have you tried the babel transform-inline-environment-variables plugin in production? Did it work?\nTechnically, you have to (which is slow) to get this to work. How do you feel about compiling not into in non-dist builds, but rather require() some module that caches the env? This is just a guess, but I believe will optimize well (function call vs. getter (which doesn't optimize in v8) + call to ). I found the babel plugin in I'll give it a try & profile.\nthanks! However, I've seen a warning that is . I've only used on files in my app. I'm curious if people use it on node modules commonly in production.\nThe catch here is that people use envify to do dead-code elimination to remove non- blocks so changing our pattern here will force downstream changes.\nUnderstood. I suppose it becomes a question of priorities unless we can think of something more creative. Unfortunately with the introduction of react-dom, it's not possible to use react minified builds on the server anymore unless you use a packager or the without duplicating , due to the new halfway-shimmed packages that directly.\nshould work, no?\nAh you're correct, since the deprecation notice will get taken out due to the production check.\nOh wait, you're right that react-dom does require react directly\u2026\nHah got confused myself. You'd have to just require and pretend it was ReactDOM, knowing that the deprecation warnings would be removed. Doesn't seem portable to 0.15.\nInitial bench results show a wider performance gap (last two runs) than the OP. In bench 4, I replace with , eliminating the getter.\nI wonder if performance can just be improved in node core (by caching).\nI've asked about that, but they're not interested because programs may be relying on catching ENV changes as it is possible to change the ENV of a running process. I've been able to manage a great improvement in server-side rendering (about 100%) by hosting to the top of the file as a , so it is only evaluated once. The best part is, when uglifyJS sees a const, it replaces the member in a condition, leaving which is then removed entirely. So we maintain the same code size, no backcompat hacks, and better perf. Only issue is that we may need to then post-process replace the for a in case of use with Browserify with old browsers.\nCan I ask why this was closed? This is by far the number one bottleneck for us on the server-side. Having to change all code to , for example, is a leaky abstraction and very un-Node-like.\nTechnically you can fix the problem in your own code by doing , converting it from a live object that calls down a plain JS object. You'll get the same performance benefits, with the only downside that any code that was relying on live edits to the env (does anyone really do that?) will fail.\ncool, good to know \u2013 neat idea! Still, massively leaky abstraction right? Like, suddenly React pollutes your entire app\nYeah. I've been working on , but it requires a change in UglifyJS to allow marking statements with an annotation (e.g. ) so it knows that it won't change and safe to eliminate dead code.\nkiller little hack btw \u2013 immediately increased our server throughput by 50% I'd still love for this issue to be reopened, or tracked elsewhere (will improve things for all React code?) should work on speeding it up as well (I believe they've made ), but having littered throughout hot code is just not ideal practice IMO \u2013 if not being able to hoist that up, cache it, memoize it, whatever, is prevented by build tools, then let's fix the build tools.\nThey're . is meant to be live.\noh for sure it is \u2013 I completely agree with that \u2013 I don't think it should be cached by Node either, just the current implementation has (or had) room for improvement.\nAs I mention in that ticket, this is the main problem: A annotation in UglifyJS will fix this.\nThat seems like a decent solution to me. I'm personally not a fan of the use of a global everywhere in the React code \u2013 again, it feels really build-tool specific. I'd prefer it be imported from a config file or declared in each module or something similar. Principle of least surprise and all that.\nI would be happy to do that, but it is important that we have a way to eliminate dev-only code in prod builds and that users of React from npm have a way to do the same. Obviously we can use whatever tools we want for our stack easily but for npm currently we suggest envify/webpack.DefinePlugin. Not inherently opposed to changing that but we'd need a good proposal and reason.\nyeah, I hear ya \u2013 there's a lot of code now in React that depends on that behaviour. Not sure I fully understand your comment \"for npm currently we suggest envify/webpack.DefinePlugin\" \u2013 what do you mean \"for npm\"? React code is compiled before it's published to npm, right? My general feeling is that it would be great if there were no FB/React-specific idioms in the code \u2013 so that it's treated as though, if v8 (or other engines) had all the ES2015/2016 features needed, then you could run the code on without even needing a compiler. Currently that's not really the case. (I'm sure you could do some sort of trick or something before requiring any React modules, but still, that would be a polluting hack) If there were a way such that was required, or declared, per module \u2013 and code elimination still worked as it does now for the builds \u2013 would you be amenable to a PR along those lines?\nI mean: if you use webpack or browserify in conjunction with react from npm, you should be able to eliminate React dev-only code from your prod builds. envify lets us do that easily in browserify as it copies the NODEENV from when you make your build, and webpack.DefinePlugin lets you configure your build to replace with a constant which then can get constant-folded and minified out. This use case is important. Yes, if it works for the case of React devs using browserify/webpack too, not just our premade builds.\nas an aside, just looking through the code now, and aside from the global , I haven't seen anything that's not supported out of the box in right now \u2013 is there a reason, aside from , that the non- code is even compiled and transformed into a different structure before publishing to npm?\nWell, it does set up the team to move to ES6 for , which will be important in the near future. I've submitted a PR to UglifyJS2 as you can see above. If it's accepted this will solve the problem.\nWe'd still need everyone using React to upgrade to that version of UglifyJS so I can't promise that we'll take it\u2026\nJust everyone using React in combination with webpack or browserify and not using the build. Alternatively they could use the DefinePlugin to set to false to get the dead code elimination.\njust to clarify, do you mean \"everyone using React who also currently uses UglifyJS with it\"?\nJust so I'm clear, there are a few users here that I can think of. Those, on the browser: everywhere already, or as a global browserify/webpack + envify/DefinePlugin browserify/webpack + envify/DefinePlugin + UglifyJS browserify/webpack + plugin to transform to or So 1 and 4 are taken care of by the compilation in . What's the main reason for even supporting 2 and 3? Is it because of things like ?\n2 and 3 are the most natural for many people. If you are using browserify then envify gets used automatically because of our config in Almost everyone minifies their code in prod. It is true that we could recommend instead for many cases, but it does fall apart in the case of requiring submodules. We don't support this for external users because we consider the modules private but the addons packages use this pattern. Various third-party projects (unsupported by us) also make use of this.\nI think the only reason 2 and 3 are \"most natural\" is just because is used everywhere so you have to use something just to get it to even work out of the box. It would be equally easy to setup the config in to use or or whatever. I use 4 whenever I can and it's no more complicated than 2 or 3 for normal usage \u2013 I guess it's just a pity that users are encouraged to \"reach in\" to for various addons. Thanks for the clarification. So it's those doing 3 who are expecting their current UglifyJS setup to eliminate any code using that you're concerned about?\nTo clarify: we recommend users require or similar, which (currently) reaches into react but that's an implementation detail. Yes.\nAh cool, good to know.\nWe have been bitten by this one too. Would be great if some note about this behavior was present on , it's a large performance impact, and is hard to find this issue unless you have already done all the investigation work.\nI would like to add that this issue also affects applications. Now the work arounds seem to be: Include the minified version of React globally via tag, it would only work in Electron and it isn't the node way, where one should be able to track every used object just seeing the . It also makes it difficult to switch between dev/prod. Use the to replace with a regular object. Not good, as we are forced to overwrite node api just because we want to use React. If using babel: ... by default babel doesn't transpile nodemodules, this can be configured but doesn't look like a work around. Note that replace every to isn't a solution because automatically requires from root, not from . Why is this issue closed? It seems to me that React should be able to initialize its configuration using , then rely on its own objects, and optionally offer a function to change the value later. Is there any reason why this wouldn't work?\nTechnically this could be fixed now as UglifyJS supports annotations, and it may be easier still as the team moves the build to Rollup in . In combination with Rollup, it would be simple to export a var from a constants file and have it effectively tagged by Uglify for dead code elimination in production mode.\nAdding my two cents here, I was able to work around this by adding the following to the top of my I had previously wrapped React using local modules as was suggested above, but this caused a lot of issues with . This seems to get the job done without too much overhead or complexity.\nFor future reference, the above snippet is broken per:\nReferencing which will fix this now that UglifyJS can properly eliminate dev code (even if it references a that never changes) with its new option, which is a default. See for more context.", "pos": ["componentWillMount() ``` Invoked immediately before rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change. Invoked once, immediately before the initial rendering occurs. If you call `setState` within this method, `render()` will see the updated state and will be executed only once despite the state change. ### Mounting: componentDidMount"], "neg": []} {"query": "Replace with and no parse error happens. What\u2019s going on?\nI had the same issue with this: We actually have an internal task tracking this at Facebook but I don't think it's been looked in to yet. Here's a comment explaining why it happens:\nFixed in esprima-fb () when for esprima-fb, jstransform and react are sorted out.\nI'm actually going to leave this open for now so we remember to do the version update.\nNow fixed in", "pos": ["
    © 2013 Facebook Inc.
    "], "neg": []} {"query": "The link to \"JSX in depth\" in the \"displayName\" section on the \"Component Specs and Lifecycle\" page points to This url is not correct, the correct url is:\nThanks! Fixed in . You can close this.", "pos": ["string displayName ``` The `displayName` string is used in debugging messages. JSX sets this value automatically, see [JSX in Depth](react/docs/jsx-in-depth.html#react-composite-components). The `displayName` string is used in debugging messages. JSX sets this value automatically, see [JSX in Depth](/react/docs/jsx-in-depth.html#react-composite-components). ## Lifecycle Methods"], "neg": []} {"query": "We're currently not cleaning up strings from _mountImage after a component gets mounted. That memory could be freed. But the act of freeing the memory could be more expensive than it's worth. Needs proper benchmarks and a workaround.\nI noticed this a little while ago. I'm not sure why we need to store it on the child instance in the first place -- PR incoming.", "pos": ["transaction, this._mountDepth + 1 ); child._mountImage = mountImage; child._mountIndex = index; mountImages.push(mountImage); index++;", "* Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function(child) { enqueueMarkup(this._rootNodeID, child._mountImage, child._mountIndex); createChild: function(child, mountImage) { enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex); }, /**", "transaction, this._mountDepth + 1 ); child._mountImage = mountImage; child._mountIndex = index; this.createChild(child); this.createChild(child, mountImage); this._renderedChildren = this._renderedChildren || {}; this._renderedChildren[name] = child; },", "// TODO: When is this not true? if (ReactComponent.isValidComponent(child)) { this.removeChild(child); child._mountImage = null; child._mountIndex = null; child.unmountComponent(); delete this._renderedChildren[name];"], "neg": []} {"query": "Should those comment sections exist? I'd rather people come to IRC. Their questions are often neglected at the bottom of a doc page.\n:+1: for shutting down comments\n+1\n:+1:", "pos": ["Next → {% endif %}
    ", "
    ", "Next → {% endif %}
    "], "neg": []} {"query": "We happen to \"support\" hyphenated keys to the style object on initial render (because we attempt to hyphenate camelcased keys) but those styles will never be updated on subsequent renders because we never attempt to unhyphenate. So we should warn when we see a hyphenated style.\nSome browsers support assigning with hyphenated keys, but probably not all do.\nAFAIK only Webkit does. (And I guess by association, Blink)\nPerhaps another one for you!\nOK\nSorry for the long delay, been busy. I'll try to do this today.\nNo problem, whenever you have time.\nCurious: why do we not want to hyphenate names on subsequent updates, and instead show a warning? Because there should be \u201cone way to do that\u201d?\nYes, this matches our existing practice of requiring camel-cased attributes in general, which makes it easier to make warpper components that modify props in some way because you only need to look in one place to find the original value. In addition, you don't need to worry about what happens if someone were to specify both and in the same style block. (One last advantage: if the warnings happen only in the dev version, then there's no runtime cost in the production build.)\nDo you think it's worth adding for the sake of providing a suggestive warning? (e.g. )\nThere you go! I also updated the docs about prefix, since it's not clear right now.\nA warning would be very helpful, this just sucked up a lot of my time. If anyone is interested, chrome seems to handle hyphenated CSS props OK but FF doesn't", "pos": ["var divStyle = { color: 'white', backgroundImage: 'url(' + imgUrl + ')', WebkitTransition: 'all' // note the capital 'W' here WebkitTransition: 'all', // note the capital 'W' here msTransition: 'all' // 'ms' is the only lowercase vendor prefix }; React.renderComponent(
    Hello World!
    , mountNode); ``` Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. `node.style.backgroundImage`). Vendor prefixes should begin with a capital letter. This is why `WebkitTransition` has an uppercase \"W\". Style keys are camelCased in order to be consistent with accessing the properties on DOM nodes from JS (e.g. `node.style.backgroundImage`). Vendor prefixes [other than `ms`](http://www.andismith.com/blog/2012/02/modernizr-prefixed/) should begin with a capital letter. This is why `WebkitTransition` has an uppercase \"W\". ", "var CSSProperty = require('CSSProperty'); var camelizeStyleName = require('camelizeStyleName'); var dangerousStyleValue = require('dangerousStyleValue'); var hyphenateStyleName = require('hyphenateStyleName'); var memoizeStringOnly = require('memoizeStringOnly'); var warning = require('warning'); var processStyleName = memoizeStringOnly(function(styleName) { return hyphenateStyleName(styleName); }); if (__DEV__) { var warnedStyleNames = {}; var warnHyphenatedStyleName = function(name) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; warning( false, 'Unsupported style property ' + name + '. Did you mean ' + camelizeStyleName(name) + '?' ); }; } /** * Operations for dealing with CSS properties. */", "if (!styles.hasOwnProperty(styleName)) { continue; } if (__DEV__) { if (styleName.indexOf('-') > -1) { warnHyphenatedStyleName(styleName); } } var styleValue = styles[styleName]; if (styleValue != null) { serialized += processStyleName(styleName) + ':';", "if (!styles.hasOwnProperty(styleName)) { continue; } if (__DEV__) { if (styleName.indexOf('-') > -1) { warnHyphenatedStyleName(styleName); } } var styleValue = dangerousStyleValue(styleName, styles[styleName]); if (styleValue) { style[styleName] = styleValue;", "expect(/style=\".*\"/.test(root.innerHTML)).toBe(false); }); it('should warn when using hyphenated style names', function() { spyOn(console, 'warn'); expect(CSSPropertyOperations.createMarkupForStyles({ 'background-color': 'crimson' })).toBe('background-color:crimson;'); expect(console.warn.argsForCall.length).toBe(1); expect(console.warn.argsForCall[0][0]).toContain('backgroundColor'); }); it('should warn when updating hyphenated style names', function() { spyOn(console, 'warn'); var root = document.createElement('div'); var styles = { '-ms-transform': 'translate3d(0, 0, 0)', '-webkit-transform': 'translate3d(0, 0, 0)' }; React.renderComponent(
    , root); React.renderComponent(
    , root); expect(console.warn.argsForCall.length).toBe(2); expect(console.warn.argsForCall[0][0]).toContain('msTransform'); expect(console.warn.argsForCall[1][0]).toContain('WebkitTransform'); }); });", " /** * Copyright 2014 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the \"License\"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an \"AS IS\" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule camelizeStyleName * @typechecks */ \"use strict\"; var camelize = require('camelize'); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < \"backgroundColor\" * > camelizeStyleName('-moz-transition') * < \"MozTransition\" * > camelizeStyleName('-ms-transition') * < \"msTransition\" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; ", "/** * Hyphenates a camelcased CSS property name, for example: * * > hyphenate('backgroundColor') * > hyphenateStyleName('backgroundColor') * < \"background-color\" * > hyphenate('MozTransition') * > hyphenateStyleName('MozTransition') * < \"-moz-transition\" * > hyphenate('msTransition') * > hyphenateStyleName('msTransition') * < \"-ms-transition\" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix"], "neg": []} {"query": "This is a tricky issue, so I'll do my best to explain: I've been using the to build my React app using AMD. I've been using a of React (with ), which is based off of master. Until recently, everything was working fine. But since , I've been unable to create optimized builds using the plugin. At first, I assumed it was an issue with the plugin, but it seems that the offending line is the changed function: Until this change, wasn't forced on, and things worked just fine. With this change, it's no longer possible to build in an AMD environment, as errors out with: My best guess is that the isn't being correctly loaded (although it is included ), but I don't know enough about Browserify to debug this. Hoping someone else can take a look and find out what's going on. (in the meantime, I suppose I'll update my branch to undo the change that set )\nis this still happening for you?\njust updated to v0.9.0, and yep: Unfortunately still having to maintain my own branch :(\nI have the same issue.\nthanks for tracking this issue down. I was trying to update React in and was puzzled by this. I will disable it manually in the modified provides.", "pos": ["*/ function transformReact(source, options) { // TODO: just use react-tools options = options || {}; var visitorList; if (options && options.harmony) { if (options.harmony) { visitorList = visitors.getAllVisitors(); } else { visitorList = visitors.transformVisitors.react; } return transform(visitorList, source, { sourceMap: supportsAccessors sourceMap: supportsAccessors && options.sourceMap }); }", "} scripts.forEach(function(script, i) { var options; var options = { sourceMap: true }; if (/;harmony=true(;|$)/.test(script.type)) { options = { harmony: true }; options.harmony = true } // script.async is always true for non-javascript script tags"], "neg": []} {"query": "On re-render, we innerText. This causes inconsistencies in rendering whitespace. See demo: We should make sure this doesn't happen.\nWe switched to use but it broke some contentEditable stuff internal to FB. knows more.\nI'm switching it back (D1174395), but regardless, this is an innerText issue. Browsers that don't have textcontent (ie8) suffer\nlooks like this was brought up in\nRight, we should also do the right thing in IE8.\njQuery empties then adds a text node. Relevant commits: ()\nokay interesting. I'll do this for ie8\nI have a patch almost ready.\nI'm curious if is a simpler solution to the newline problem (for IE8), or if that only works for innerHTML.\nhmm interesting. We definitely want to preserve whitespace though. (because of and and )", "pos": ["var ReactMount = require('ReactMount'); var ReactPerf = require('ReactPerf'); var getTextContentAccessor = require('getTextContentAccessor'); var invariant = require('invariant'); /**", "style: '`style` must be set using `updateStylesByID()`.' }; /** * The DOM property to use when setting text content. * * @type {string} * @private */ var textContentAccessor = getTextContentAccessor(); var useWhitespaceWorkaround; /**", "'updateTextContentByID', function(id, content) { var node = ReactMount.getNode(id); node[textContentAccessor] = content; DOMChildrenOperations.updateTextContent(node, content); } ),", "} /** * Sets the text content of `node` to `text`. * * @param {DOMElement} node Node to change * @param {string} text New text content */ var updateTextContent; if (textContentAccessor === 'textContent') { updateTextContent = function(node, text) { node.textContent = text; }; } else { updateTextContent = function(node, text) { // In order to preserve newlines correctly, we can't use .innerText to set // the contents (see #1080), so we empty the element then append a text node while (node.firstChild) { node.removeChild(node.firstChild); } if (text) { var doc = node.ownerDocument || document; node.appendChild(doc.createTextNode(text)); } }; } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, updateTextContent: updateTextContent, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property.", "); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: update.parentNode[textContentAccessor] = update.textContent; updateTextContent( update.parentNode, update.textContent ); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: // Already removed by the for-loop above."], "neg": []} {"query": "React 0.8 React 0.9 I think this is because of switched to in 1.0.0. I submitted a to envify which uses instead of recast. This brings us back to 1.5s and delivers the same advantages as recast version (preserves code formatting): I think this is blocker for 0.9.0.\nWhat command are you running, and in what directory? I'm having trouble reproducing the slow-down with just .", "pos": ["\"node\": \">=0.10.0\" }, \"peerDependencies\": { \"envify\": \"~1.0.1\" \"envify\": \"~1.2.0\" }, \"browserify\": { \"transform\": [\"envify\"]", "\"benchmark\": \"~1.0.0\", \"browserify\": \"~3.20.0\", \"coverify\": \"~1.0.4\", \"envify\": \"~1.0.1\", \"envify\": \"~1.2.0\", \"es3ify\": \"~0.1.2\", \"es5-shim\": \"~2.3.0\", \"grunt\": \"~0.4.2\","], "neg": []} {"query": "This throws . Maybe this can be simplified some more but this was the simplest repro I could make. Thanks for sending a repro case over.\nWow, it really was a bug. Narrowed it down a little, but it's still rediculously \"complex\". Big props to for repro! Anyway, just glancing at the code and from experience, I can safely assume that the issue is that receives multiple updates to the same node from . Which intuitively didn't make any sense at all to me, since always calls when it's done and is basically just recursive. However, when taking another peek at the code, I'm pretty sure that the issue is that (in this case) makes the invalid assumption that all updates belongs to the same root. When that is not the case, an to a component which itself updates another root will only once everything is done. The updates to the other root will NOT after each on that root because will always greater than 0. In practice this means that whenever updates another root, all DOM updates on that root will be batched one after the other (as opposed to batching component updates) which is a violation of assumptions in . It's also very inefficient. Intuitively it seems that what should happen is that all component updates within a call should be (but that is not for sure), exactly how this should be solved in practice I'm not 100% sure right now. But I'm 95% sure that this is what's happening, and the repro does have all the ingredients.\nSpeaking a bit to in chat, I feel like the issue is that and when called from within become asynchronous as opposed to synchronous as they usually are. Which leads to this issue, but also possibly a lot of other subtle issues.\nApparently is not at all to blame...\nNarrowed it down even further, apparently it breaks immediately on the first , the error just didn't show up until later unless prodded. I still don't feel any more enlightened on the issue though...\nYour latest two jsbins (4 & 6) throw different error for me (from in X ): And, if one removes Z from A , the same X throws , because then A render won't have any refs on that render so will be undefined... React docs warn that \"Never access refs inside of any component's render method - or while any component's render method is even running anywhere in the call stack.\", don't know if it's relevant here.\nYeah different error, but I'm sure the cause is the same. The issue is the span not actually ever being rendered, just that in the old repro it doesn't actually turn into an error until later.\nOk, so perhaps here's a reduced test case, see console: is being called twice in a row, and the first time the span is not there in DOM even though it has been rendered already. One culprit for this behavior may be that you are effectively calling setState on sibling component where setState would not be allowed on component itself (triggered via componentWillUpdate).\nHuh? It does end up being rendered in your test case, and there's no error?\nno I didn't want to throw the error so that you can see that the componentDidUpdate will be called double. The point is that first the span is not there and if one would try to access it (as in your ref.getDOMNode()) it would throw. See console for flow.\nis defined so it's an error regardless, and more than that, React expects the node to be there, but it isn't and throws an error. Even after it still isn't physically there in the DOM. So something is wrong. Unless I'm missing something.\nYes, there is definitely a problem there as you said, sorry for not being clear. I just wanted to reduce it so that there are no refs or forceUpdates which may bring other problems. One could throw the error in componentDidUpdate for clarity, as the innerHTML is definitely empty where it should not be. But it is interesting that it will be called right away again, and then the span will be there.", "pos": ["* Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function(callback, param) { callback(param); batchedUpdates: function(callback, a, b) { callback(a, b); } };", "* Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function(callback, param) { batchedUpdates: function(callback, a, b) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(param); callback(a, b); } else { transaction.perform(callback, null, param); transaction.perform(callback, null, a, b); } } };", "\"use strict\"; var CallbackQueue = require('CallbackQueue'); var PooledClass = require('PooledClass'); var ReactCurrentOwner = require('ReactCurrentOwner'); var ReactPerf = require('ReactPerf'); var Transaction = require('Transaction'); var invariant = require('invariant'); var mixInto = require('mixInto'); var warning = require('warning'); var dirtyComponents = [];", "); } function batchedUpdates(callback, param) { var NESTED_UPDATES = { initialize: function() { this.dirtyComponentsLength = dirtyComponents.length; }, close: function() { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function() { this.callbackQueue.reset(); }, close: function() { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(null); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(); } mixInto(ReactUpdatesFlushTransaction, Transaction.Mixin); mixInto(ReactUpdatesFlushTransaction, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, destructor: function() { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function(method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call( this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a ); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b) { ensureInjected(); batchingStrategy.batchedUpdates(callback, param); batchingStrategy.batchedUpdates(callback, a, b); } /**", "} function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; invariant( len === dirtyComponents.length, 'Expected flush transaction's stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length ); // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountDepthComparator); for (var i = 0; i < dirtyComponents.length; i++) { for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, ignore them // TODO: Queue unmounts in the same list to avoid this happening at all var component = dirtyComponents[i];", "// stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; component.performUpdateIfNecessary(transaction); component.performUpdateIfNecessary(transaction.reconcileTransaction); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.getReactMountReady().enqueue( transaction.callbackQueue.enqueue( callbacks[j], component );", "} } function clearDirtyComponents() { dirtyComponents.length = 0; } function flushBatchedUpdatesOnce(transaction) { // Run these in separate functions so the JIT can optimize try { runBatchedUpdates(transaction); } finally { clearDirtyComponents(); } } var flushBatchedUpdates = ReactPerf.measure( 'ReactUpdates', 'flushBatchedUpdates', function() { // flushBatchedUpdatesOnce will clear the dirtyComponents array, but // mount-ready handlers (i.e., componentDidMount/Update) may enqueue more // state updates which we should apply immediately // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks. while (dirtyComponents.length) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform(flushBatchedUpdatesOnce, null, transaction); ReactUpdates.ReactReconcileTransaction.release(transaction); var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } } );", "); if (!batchingStrategy.isBatchingUpdates) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform( component.performUpdateIfNecessary, component, transaction ); ReactUpdates.ReactReconcileTransaction.release(transaction); callback && callback.call(component); batchingStrategy.batchedUpdates(enqueueUpdate, component, callback); return; }", "expect(aUpdated).toBe(true); }); it('should flush updates in the correct order', function() { var updates = []; var Outer = React.createClass({ getInitialState: function() { return {x: 0}; }, render: function() { updates.push('Outer-render-' + this.state.x); return
    ; }, componentDidUpdate: function() { var x = this.state.x; updates.push('Outer-didUpdate-' + x); updates.push('Inner-setState-' + x); this.refs.inner.setState({x: x}, function() { updates.push('Inner-callback-' + x); }); } }); var Inner = React.createClass({ getInitialState: function() { return {x: 0}; }, render: function() { updates.push('Inner-render-' + this.props.x + '-' + this.state.x); return
    ; }, componentDidUpdate: function() { updates.push('Inner-didUpdate-' + this.props.x + '-' + this.state.x); } }); var instance = ReactTestUtils.renderIntoDocument(); updates.push('Outer-setState-1'); instance.setState({x: 1}, function() { updates.push('Outer-callback-1'); updates.push('Outer-setState-2'); instance.setState({x: 2}, function() { updates.push('Outer-callback-2'); }); }); expect(updates).toEqual([ 'Outer-render-0', 'Inner-render-0-0', 'Outer-setState-1', 'Outer-render-1', 'Inner-render-1-0', 'Inner-didUpdate-1-0', 'Outer-didUpdate-1', 'Inner-setState-1', 'Inner-render-1-1', 'Inner-didUpdate-1-1', 'Inner-callback-1', 'Outer-callback-1', 'Outer-setState-2', 'Outer-render-2', 'Inner-render-2-1', 'Inner-didUpdate-2-1', 'Outer-didUpdate-2', 'Inner-setState-2', 'Inner-render-2-2', 'Inner-didUpdate-2-2', 'Inner-callback-2', 'Outer-callback-2' ]); }); it('should queue nested updates', function() { // See https://github.com/facebook/react/issues/1147 var X = React.createClass({ getInitialState: function() { return {s: 0}; }, render: function() { if (this.state.s === 0) { return
    0
    ; } else { return
    1
    ; } }, go: function() { this.setState({s: 1}); this.setState({s: 0}); this.setState({s: 1}); } }); var Y = React.createClass({ render: function() { return
    ; } }); var Z = React.createClass({ render: function() { return
    ; }, componentWillUpdate: function() { x.go(); } }); var x; var y; x = ReactTestUtils.renderIntoDocument(); y = ReactTestUtils.renderIntoDocument(); expect(x.getDOMNode().textContent).toBe('0'); y.forceUpdate(); expect(x.getDOMNode().textContent).toBe('1'); }); it('should queue updates from during mount', function() { // See https://github.com/facebook/react/issues/1353 var a; var A = React.createClass({ getInitialState: function() { return {x: 0}; }, componentWillMount: function() { a = this; }, render: function() { return
    A{this.state.x}
    ; } }); var B = React.createClass({ componentWillMount: function() { a.setState({x: 1}); }, render: function() { return
    ; } }); ReactUpdates.batchedUpdates(function() { ReactTestUtils.renderIntoDocument( ); }); expect(a.state.x).toBe(1); expect(a.getDOMNode().textContent).toBe('A1'); }); it('calls componentWillReceiveProps setState callback properly', function() { var callbackCount = 0; var A = React.createClass({ getInitialState: function() { return {x: this.props.x}; }, componentWillReceiveProps: function(nextProps) { var newX = nextProps.x; this.setState({x: newX}, function() { // State should have updated by the time this callback gets called expect(this.state.x).toBe(newX); callbackCount++; }); }, render: function() { return
    {this.state.x}
    ; } }); var container = document.createElement('div'); React.renderComponent(
    , container); React.renderComponent(, container); expect(callbackCount).toBe(1); }); });"], "neg": []} {"query": "Is transformed to: Note the trailing - this results in a syntax error. The problem seems to be with comma insertion in and related functions (e.g, ). See IRC discussion below for my findings. Relevant parts of an IRC discussion:\nThe root of the issue is that is a special-case in JSX, but it apparently does not take into account . Should be an easy fix. We should also look into adding I feel, just to be able to easily comment out code. EDIT: I was wrong, the special-case is handled correctly, I'll have a PR up shortly.", "pos": ["var childrenToRender = object.children.filter(function(child) { return !(child.type === Syntax.Literal && typeof child.value === 'string' && child.value.match(/^[ t]*[rn][ trn]*$/)); && child.value.match(/^[ t]*[rn][ trn]*$/) || child.type === Syntax.XJSExpressionContainer && child.expression.type === Syntax.XJSEmptyExpression); }); if (childrenToRender.length > 0) { utils.append(', ', state);"], "neg": []} {"query": "But it throws:\nWas this fixed?\nWas clearing up old some old issues and it seemed like this was fixed, but apparently not.\nI've found this same problem. Here's a minimal failing example for React 0.12.2: ,output However, it appears that this is fixed in 0.13RC: ,output. Any ideas which commit fixed this? If there aren't tests which exercise this it might creep back in.\nSame here. Was perhaps related? I created a simple test case based on jsbin, which currently passes. Unfortunately I'm unable to run tests in anything besides master so can't really validate.\nAFAIK no longer exists as of React 0.13, so this issue should be irrelevant now.", "pos": ["* Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function(callback, param) { callback(param); batchedUpdates: function(callback, a, b) { callback(a, b); } };", "* Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function(callback, param) { batchedUpdates: function(callback, a, b) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(param); callback(a, b); } else { transaction.perform(callback, null, param); transaction.perform(callback, null, a, b); } } };", "\"use strict\"; var CallbackQueue = require('CallbackQueue'); var PooledClass = require('PooledClass'); var ReactCurrentOwner = require('ReactCurrentOwner'); var ReactPerf = require('ReactPerf'); var Transaction = require('Transaction'); var invariant = require('invariant'); var mixInto = require('mixInto'); var warning = require('warning'); var dirtyComponents = [];", "); } function batchedUpdates(callback, param) { var NESTED_UPDATES = { initialize: function() { this.dirtyComponentsLength = dirtyComponents.length; }, close: function() { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function() { this.callbackQueue.reset(); }, close: function() { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(null); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled(); } mixInto(ReactUpdatesFlushTransaction, Transaction.Mixin); mixInto(ReactUpdatesFlushTransaction, { getTransactionWrappers: function() { return TRANSACTION_WRAPPERS; }, destructor: function() { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function(method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call( this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a ); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b) { ensureInjected(); batchingStrategy.batchedUpdates(callback, param); batchingStrategy.batchedUpdates(callback, a, b); } /**", "} function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; invariant( len === dirtyComponents.length, 'Expected flush transaction's stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length ); // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountDepthComparator); for (var i = 0; i < dirtyComponents.length; i++) { for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, ignore them // TODO: Queue unmounts in the same list to avoid this happening at all var component = dirtyComponents[i];", "// stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; component.performUpdateIfNecessary(transaction); component.performUpdateIfNecessary(transaction.reconcileTransaction); if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.getReactMountReady().enqueue( transaction.callbackQueue.enqueue( callbacks[j], component );", "} } function clearDirtyComponents() { dirtyComponents.length = 0; } function flushBatchedUpdatesOnce(transaction) { // Run these in separate functions so the JIT can optimize try { runBatchedUpdates(transaction); } finally { clearDirtyComponents(); } } var flushBatchedUpdates = ReactPerf.measure( 'ReactUpdates', 'flushBatchedUpdates', function() { // flushBatchedUpdatesOnce will clear the dirtyComponents array, but // mount-ready handlers (i.e., componentDidMount/Update) may enqueue more // state updates which we should apply immediately // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks. while (dirtyComponents.length) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform(flushBatchedUpdatesOnce, null, transaction); ReactUpdates.ReactReconcileTransaction.release(transaction); var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } } );", "); if (!batchingStrategy.isBatchingUpdates) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled(); transaction.perform( component.performUpdateIfNecessary, component, transaction ); ReactUpdates.ReactReconcileTransaction.release(transaction); callback && callback.call(component); batchingStrategy.batchedUpdates(enqueueUpdate, component, callback); return; }", "expect(aUpdated).toBe(true); }); it('should flush updates in the correct order', function() { var updates = []; var Outer = React.createClass({ getInitialState: function() { return {x: 0}; }, render: function() { updates.push('Outer-render-' + this.state.x); return
    ; }, componentDidUpdate: function() { var x = this.state.x; updates.push('Outer-didUpdate-' + x); updates.push('Inner-setState-' + x); this.refs.inner.setState({x: x}, function() { updates.push('Inner-callback-' + x); }); } }); var Inner = React.createClass({ getInitialState: function() { return {x: 0}; }, render: function() { updates.push('Inner-render-' + this.props.x + '-' + this.state.x); return
    ; }, componentDidUpdate: function() { updates.push('Inner-didUpdate-' + this.props.x + '-' + this.state.x); } }); var instance = ReactTestUtils.renderIntoDocument(); updates.push('Outer-setState-1'); instance.setState({x: 1}, function() { updates.push('Outer-callback-1'); updates.push('Outer-setState-2'); instance.setState({x: 2}, function() { updates.push('Outer-callback-2'); }); }); expect(updates).toEqual([ 'Outer-render-0', 'Inner-render-0-0', 'Outer-setState-1', 'Outer-render-1', 'Inner-render-1-0', 'Inner-didUpdate-1-0', 'Outer-didUpdate-1', 'Inner-setState-1', 'Inner-render-1-1', 'Inner-didUpdate-1-1', 'Inner-callback-1', 'Outer-callback-1', 'Outer-setState-2', 'Outer-render-2', 'Inner-render-2-1', 'Inner-didUpdate-2-1', 'Outer-didUpdate-2', 'Inner-setState-2', 'Inner-render-2-2', 'Inner-didUpdate-2-2', 'Inner-callback-2', 'Outer-callback-2' ]); }); it('should queue nested updates', function() { // See https://github.com/facebook/react/issues/1147 var X = React.createClass({ getInitialState: function() { return {s: 0}; }, render: function() { if (this.state.s === 0) { return
    0
    ; } else { return
    1
    ; } }, go: function() { this.setState({s: 1}); this.setState({s: 0}); this.setState({s: 1}); } }); var Y = React.createClass({ render: function() { return
    ; } }); var Z = React.createClass({ render: function() { return
    ; }, componentWillUpdate: function() { x.go(); } }); var x; var y; x = ReactTestUtils.renderIntoDocument(); y = ReactTestUtils.renderIntoDocument(); expect(x.getDOMNode().textContent).toBe('0'); y.forceUpdate(); expect(x.getDOMNode().textContent).toBe('1'); }); it('should queue updates from during mount', function() { // See https://github.com/facebook/react/issues/1353 var a; var A = React.createClass({ getInitialState: function() { return {x: 0}; }, componentWillMount: function() { a = this; }, render: function() { return
    A{this.state.x}
    ; } }); var B = React.createClass({ componentWillMount: function() { a.setState({x: 1}); }, render: function() { return
    ; } }); ReactUpdates.batchedUpdates(function() { ReactTestUtils.renderIntoDocument( ); }); expect(a.state.x).toBe(1); expect(a.getDOMNode().textContent).toBe('A1'); }); it('calls componentWillReceiveProps setState callback properly', function() { var callbackCount = 0; var A = React.createClass({ getInitialState: function() { return {x: this.props.x}; }, componentWillReceiveProps: function(nextProps) { var newX = nextProps.x; this.setState({x: newX}, function() { // State should have updated by the time this callback gets called expect(this.state.x).toBe(newX); callbackCount++; }); }, render: function() { return
    {this.state.x}
    ; } }); var container = document.createElement('div'); React.renderComponent(
    , container); React.renderComponent(, container); expect(callbackCount).toBe(1); }); });"], "neg": []} {"query": "ReactCSSTransitionGroup doesn't work properly on (at least) Android 4.2. I've narrowed it down to the code in which is finding and properties on the test element's object and so only registering and handlers, despite the fact that Android fires events. So the end of the transition isn't properly detected. I will do some more investigation and see if there's a safer way to do this detection on Android (I seem to recall seeing something similar before).\nSee this patch for the Dojo toolkit: - basically on some Android versions is not . Could this be fixed by changing the order the properties are checked, so that is checked for before ?\nThis is still an issue on Android 4.3 (or at least on Samsung Galaxy S3 with Android 4.3). However changing the webkitTransition and transition order as suggested by it fixes the issue.\nIs TransitionEvent defined or undefined on that browser? When the unprefixed version exists it's better to use that in general because it's more forwards-compatible.", "pos": ["var ExecutionEnvironment = require('ExecutionEnvironment'); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend',", "function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed \"animation\" and \"transition\" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } for (var baseEventName in EVENT_NAME_MAP) { var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) {"], "neg": []} {"query": "I am getting this error when I run jsx. Is this happening to anybody else? Am I doing something wrong?\nversion, how are you running it, any details to help repro? cc - this is in commoner.\nThanks for the quick reply. It happened on 0.8, 0.9 and 0.10.0-rc1. I just ran it like this. Also, if I run it on a file, like this. It works. But not when I run it against a whole directory.\nThanks a lot for the report. Looks like has updated commoner and I'm sure he'll update our dependency here as soon as he pushes that to npm.\nHey guys, thanks for the quick response, and thanks for all the good work :+1:\nmysql I aslo encounter this problem today\nJust in case you still have an old version of the dependency installed, you can do", "pos": ["\"url\": \"https://github.com/facebook/react\" }, \"dependencies\": { \"commoner\": \"~0.9.1\", \"commoner\": \"^0.9.2\", \"esprima-fb\": \"~3001.1.0-dev-harmony-fb\", \"jstransform\": \"~3.0.0\" },"], "neg": []} {"query": "H:githubreactgrunt Running \"delete-build-modules\" task Running \"jsx:normal\" (jsx) task Warning: This socket is closed. Use --force to continue. Aborted due to warnings. on windows. any hint?\nThe issue arises in the jsx task at line 42: File: [no files] Warning: This socket is closed. Use --force to continue. Error: This socket is closed. at () at doWrite () at writeOrBuffer () at () at () at (c:reactgrunttasks) at Object. var path = require(\"path\"); var grunt = require(\"grunt\"); var expand = grunt.file.expand; var spawn = grunt.util.spawn;", "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);"], "neg": []} {"query": "While testing I wanted to simulate and events, but for some reason they are not firing the handlers in the component. Here's a fiddle to show you: You'll see that with the Simulate functions, only the click is actually triggered, while the other ones not. With the real events everything works perfectly. I tried to debug a little bit what's going on, but didn't get much information, especially since it's the first time I'm diving into the events mechanism internals in React. If you want more info, then I can try and dig a bit deeper, but I think the fiddle is clear enough.\nYeah, unfortunately mouseEnter/mouseLeave don't get simulated properly at the moment due to their unique bubbling situation. The biggest blocker here is picking a good API, I think. Maybe just ?\nWhy should the user care about where the mouse moves from/to? Perhaps this can be handled internally? Is the problem due to bubbling here? I may need to dive into the code a little more to get a better understanding and stop saying nonsense :P\nYes, it's due to bubbling. If you have the DOM structure and your mouse moves from C to D, then C and B receive mouseleave events, D receives a mouseenter event, and A receives nothing. All other events bubble up to the root. Perhaps it's good enough to just make simulated mouseEnter and mouseLeave events not bubble at all.\nThat would work at least where I was trying to test. While testing I generally don't need anything too complex, just making sure the right behavior triggers when the event happens. Hopefully that's the way others do as well\n(As a workaround for now, you can use SimulateNative.mouseOver and SimulateNative.mouseOut (making sure to specify relatedTarget appropriately on each) and together they will cause React to fire onMouseEnter and onMouseLeave events.)\nDo we have a good solution for such case now? I'm trying my solution but feeling so tricky. And I got still quite strange results:\ncan you give an example. I can't find any documentation on SimulateNative or how to set relatedTarget appropriately?\nYou want to do something like this: The simulates the mouse moving one element another. The element can be anything really, it\u2019s not important.\nDo we have a good solution for such case now? or It can not be solved?\nI am manually applying this patch until it is pulled into the core:\nAny update on this?\nI was able to get my tests to pass using SimulateNative. Here's my codez: Test results:\nI tried that using both and instead of but it still did not trigger my event.\nIf it helps - the difference which worked for me was calling with a and not a . Pass & fail states listed along with full test case below: This seems to also work:\nNo update so far? Maybe some workarounds?\nThis was fixed in in April as you can see a few messages up; it'll be in the 0.14 release. If you search \"workaround\" on this page you'll see that I also posted a workaround over a year ago.\nSorry, really missed it. Thanks for it!", "pos": ["var ON_CLICK_KEY = keyOf({onClick: null}); var ON_TOUCH_TAP_KEY = keyOf({onTouchTap: null}); var ON_CHANGE_KEY = keyOf({onChange: null}); var ON_MOUSE_ENTER_KEY = keyOf({onMouseEnter: null}); /**", "expect(handleParentClick.mock.calls.length).toBe(0); }); it('should have mouse enter simulated by test utils', function() { ReactBrowserEventEmitter.putListener( getID(CHILD), ON_MOUSE_ENTER_KEY, recordID.bind(null, getID(CHILD)) ); ReactTestUtils.Simulate.mouseEnter(CHILD); expect(idCallOrder.length).toBe(1); expect(idCallOrder[0]).toBe(getID(CHILD)); }); it('should infer onTouchTap from a touchStart/End', function() { ReactBrowserEventEmitter.putListener( getID(CHILD),", "node = domComponentOrNode; } var dispatchConfig = ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType]; var fakeNativeEvent = new Event(); fakeNativeEvent.target = node; // We don't use SyntheticEvent.getPooled in order to not have to worry about // properly destroying any properties assigned from `eventData` upon release var event = new SyntheticEvent( ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType], dispatchConfig, ReactMount.getID(node), fakeNativeEvent ); assign(event, eventData); EventPropagators.accumulateTwoPhaseDispatches(event); if (dispatchConfig.phasedRegistrationNames) { EventPropagators.accumulateTwoPhaseDispatches(event); } else { EventPropagators.accumulateDirectDispatches(event); } ReactUpdates.batchedUpdates(function() { EventPluginHub.enqueueEvents(event);"], "neg": []} {"query": "It's weird that gets turned into . I think we should only add if the value is an actual number.\nI'll just chime in with what I mentioned in the chat last time, I think it's a great solution. Just as means you're providing a raw CSS-string, would mean you're providing a raw CSS-string. So it makes sense logically. However, and suddenly has two very different outcomes if the component passes the value as-is to the style-object. I see no intuitive way out of this, sure enforcing numbers as is technically the right solution, but it's not obvious to new users (document it thoroughly) and it's potentially error prone for a user base accustomed to HTML (especially designers I would assume). I don't mind making the only right way, but to me it seems like there's no way to enforce it at run-time without which is a developer burden, and as I've understood it, an entirely optional feature in your eyes. So it seems kind of fragile.\nNote: this isn't actually fixed, just have a warning in place.\nYep, was autoclosed by the PR.\nshould we add a version in the warning message to this behavior be removed?\nSo just to clarify, is passing a number value as string type the only thing that will no longer have appended to it? Will passing a plain number a la still be supported, or is there also an intent to remove that as well?\nAs I understood, only string type. The example you gave, will still be supported.\nwe still have this warning in place, should we consider acting on for 16 or wait until 17?\nToo late for breaking changes for 16, let's look at doing it in 17. Can probably land soon after the release behind a flag.\nHmm. I neither see a warning, nor do I see it apply the style. I think this was fixed in 16.", "pos": ["* The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function(styles) { createMarkupForStyles: function(styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) {", "} if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue) + ';'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null;", "} propValue = this._previousStyleCopy = assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue); propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) {", "expect(console.error.argsForCall.length).toBe(2); }); it('should warn about styles with numeric string values for non-unitless properties', function() { spyOn(console, 'error'); var div = document.createElement('div'); var One = React.createClass({ render: function() { return this.props.inline ? :
    ; }, }); var Two = React.createClass({ render: function() { return
    ; }, }); ReactDOM.render(, div); expect(console.error.calls.length).toBe(1); expect(console.error.argsForCall[0][0]).toBe( 'Warning: a `div` tag (owner: `One`) was passed a numeric string value ' + 'for CSS property `fontSize` (value: `1`) which will be treated ' + 'as a unitless number in a future version of React.' ); // Don't warn again for the same component ReactDOM.render(, div); expect(console.error.calls.length).toBe(1); // Do warn for different components ReactDOM.render(, div); expect(console.error.calls.length).toBe(2); expect(console.error.argsForCall[1][0]).toBe( 'Warning: a `div` tag (owner: `Two`) was passed a numeric string value ' + 'for CSS property `fontSize` (value: `1`) which will be treated ' + 'as a unitless number in a future version of React.' ); // Really don't warn again for the same component ReactDOM.render(, div); expect(console.error.calls.length).toBe(2); }); it('should warn semi-nicely about NaN in style', function() { spyOn(console, 'error');", "'use strict'; var CSSProperty = require('CSSProperty'); var warning = require('warning'); var isUnitlessNumber = CSSProperty.isUnitlessNumber; var styleWarnings = {}; /** * Convert a value into the proper css writable value. The style name `name`", "* * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value) { function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject", "} if (typeof value === 'string') { if (__DEV__) { if (component) { var owner = component._currentElement._owner; var ownerName = owner ? owner.getName() : null; if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {}; } var warned = false; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name]; if (!warned) { warnings[name] = true; } } if (!warned) { warning( false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value ); } } } value = value.trim(); } return value + 'px';"], "neg": []} {"query": "Sometimes it's helpful for to have a playground for grokking React's features, and I like to use the live editor on the docs site to sketch out ideas and see how my code is called by the library. It'd be a huge help if the site's React source was served unminified so it's more apparent what's going on under the covers.\nI think this would be helpful:\nI think I'd be okay with this. Want to send a PR?", "pos": [" ", "react_docs: { files: [ { src: ['react.min.js', 'JSXTransformer.js'], src: ['react.js', 'JSXTransformer.js'], dest: 'docs/js/', cwd: 'build/', expand: true"], "neg": []} {"query": "Here's an example at jsbin: Clicking for the first time works (mounts a SVG +), but when clicking the same button again (which should unmount the rect+title), react throws an exception. I have no clue how to get around this. Help is very much appreciated. Thanks in advance!\nAh, this is because React doesn't let you unmount the HTML element. I don't believe there's a workaround right now, sorry. cc\nFixed by .", "pos": ["html: createFullPageComponent(ReactDOM.html), head: createFullPageComponent(ReactDOM.head), title: createFullPageComponent(ReactDOM.title), body: createFullPageComponent(ReactDOM.body) });"], "neg": []} {"query": "Logging and reveals: Which doesn't make sense (to me at least).\nCan you log the too and something to distinguish the two renderComponent calls?\nUpdated, that makes more sense,", "pos": ["var DOMProperty = require('DOMProperty'); var DOMPropertyOperations = require('DOMPropertyOperations'); var ReactBrowserEventEmitter = require('ReactBrowserEventEmitter'); var ReactComponentBrowserEnvironment = require('ReactComponentBrowserEnvironment'); var ReactMount = require('ReactMount'); var ReactMultiChild = require('ReactMultiChild'); var ReactPerf = require('ReactPerf');", "unmountComponent: function() { this.unmountChildren(); ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID); ReactMount.purgeID(this._rootNodeID); ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; }", "}, unmountComponent: function() { // TODO: Is this necessary? ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); }", "this._pendingCallbacks = null; this._pendingElement = null; ReactComponentEnvironment.unmountIDFromEnvironment(this._rootNodeID); // These fields do not really need to be reset since this object is no // longer accessible. this._context = null;", "render: function() { return
    Text
    ; } });", "React.unmountComponentAtNode(container); expect(innerUnmounted).toBe(true); // , , and both
    elements and their wrappers // each call unmountIDFromEnvironment which calls purgeID, for a total of 6. // The text and both
    elements and their wrappers each call // unmountIDFromEnvironment which calls purgeID, for a total of 3. // TODO: Test the effect of this. E.g. does the node cache get repopulated // after a getDOMNode call? expect(ReactMount.purgeID.callCount).toBe(6); expect(ReactMount.purgeID.callCount).toBe(3); }); it('should warn when shouldComponentUpdate() returns undefined', function() {"], "neg": []} {"query": "Right now we don't do this consistently, so you could have behavior that varies depending on where you put the key in your class spec. That's not great. Here's an example: (using master) This outputs: I think we should consistently behave like CompB (component, then mixin methods) but disagrees. Any other opinions. Potentially interested (once we figure out which way we go)? This is relatively contained and testable but it does take you right into core.\nDoing mixins first is more intuitive to me because that's normally how people write the specs (in my experience, at least).\nHi, thanks for the mention. I'd like to take on this if nobody minds. I agree with that calling mixins first is more intuitive.\nGo for it! Let me know if you have any questions; I'm happy to help.\nOK great. I'll try to do it tomorrow.\nMention me if there's something else I can take. I liked that although this task had a small scope, it introduced me to the way actually works and how spec transforms into a component instance. It would be cool if I could take a few small tasks in other areas (rendering, batching) that introduce me to these areas.", "pos": ["); ``` A nice feature of mixins is that if a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called. A nice feature of mixins is that if a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called. Methods defined on mixins run in the order mixins were listed, followed by a method call on the component. ", "var instantiateReactComponent = require('instantiateReactComponent'); var invariant = require('invariant'); var keyMirror = require('keyMirror'); var keyOf = require('keyOf'); var merge = require('merge'); var mixInto = require('mixInto'); var monitorCodeUse = require('monitorCodeUse');", "var shouldUpdateReactComponent = require('shouldUpdateReactComponent'); var warning = require('warning'); var MIXINS_KEY = keyOf({mixins: null}); /** * Policies that describe methods in `ReactCompositeComponentInterface`. */", "var Constructor = ConvenienceConstructor.type; var proto = Constructor.prototype; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(ConvenienceConstructor, spec.mixins); } for (var name in spec) { var property = spec[name]; if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above continue; } var property = spec[name]; validateMethodOverride(proto, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) {", "var TestComponent; var TestComponentWithPropTypes; var TestComponentWithReverseSpec; var mixinPropValidator; var componentPropValidator;", "} }; var MixinBWithReverseSpec = { componentDidMount: function() { this.props.listener('MixinBWithReverseSpec didMount'); }, mixins: [MixinA] }; var MixinC = { statics: { staticC: function() {}", "} }); TestComponentWithReverseSpec = React.createClass({ render: function() { return
    ; }, componentDidMount: function() { this.props.listener('Component didMount'); }, mixins: [MixinBWithReverseSpec, MixinC, MixinD] }); TestComponentWithPropTypes = React.createClass({ mixins: [MixinD], propTypes: {", "]); }); it('should chain functions regardless of spec property order', function() { var listener = mocks.getMockFunction(); var instance = ; instance = ReactTestUtils.renderIntoDocument(instance); expect(listener.mock.calls).toEqual([ ['MixinA didMount'], ['MixinBWithReverseSpec didMount'], ['MixinC didMount'], ['Component didMount'] ]); }); it('should validate prop types via mixins', function() { expect(TestComponent.type.propTypes).toBeDefined(); expect(TestComponent.type.propTypes.value)"], "neg": []} {"query": "It's nice to have prebuilt binaries available through the current package managers. Right now there's a prebuilt package for , but it'd be nice to also have them on npm / component / What do you think is the best way to create and maintain these packages? cc/\nSee also .\ncc -- Not a blocker for 0.11, but it would be nice if could be merged.\nBy \"binaries\" do you actually mean prebuilt versions of React that you can just include on a web page? React doesn't really have binary components.\nYep, that's what I mean.\nI'm using in a project and I would love to be able to include react that way. The last conversation about this ended in\nWe don't have plans to do this right now.", "pos": ["var dest = 'build/npm-react/'; var modSrc = 'build/modules/'; var lib = dest + 'lib/'; var dist = dest + 'dist/'; var distFiles = [ 'react.js', 'react.min.js', 'JSXTransformer.js', 'react-with-addons.js', 'react-with-addons.min.js' ]; function buildRelease() { // delete build/react-core for fresh start", "} }); // Make built source available inside npm package grunt.file.mkdir(dist); distFiles.forEach(function(file) { grunt.file.copy('build/' + file, dist + file); }); // modify build/react-core/package.json to set version ## var pkg = grunt.file.readJSON(dest + 'package.json'); pkg.version = grunt.config.data.pkg.version;", "\"README.md\", \"addons.js\", \"react.js\", \"dist/\", \"lib/\" ], \"main\": \"react.js\","], "neg": []} {"query": "From : cc\nFixed.\nReopening because new docs don't have that info, and it is confusing. We should re-add it.\nI am looking to make my first contribution and would like to fix this issue.\nI also opened a PR for this on last week, restoring the original note. I notes for discussion on a more thorough example on the PR, like the current example has, but have not done much beyond that. Do we think that such an example would be beneficial? I almost think not, since the difference is just treating as an array with , but I'm curious to hear everyone else's thoughts on that.\nThere hasn't been any further discussion in PR or on this issue in the last two months, so is that PR all we need to do for this? cc\nSorry. We\u2019ve been busy with a rewrite for React 16, and haven\u2019t been actively reviewing the PRs.\nFixed in\nNo sweat, I figured as much. React 16 was absolutely worth it, great work!", "pos": ["``` To make an uncontrolled component, `defaultValue` is used instead. > Note: > > You can pass an array into the `value` attribute, allowing you to select multiple options in a `select` tag: `