From bca474ddda28307e9a04e0af6f64677505115fd6 Mon Sep 17 00:00:00 2001 From: Darren Scerri Date: Sat, 11 Nov 2017 16:31:42 +0100 Subject: [PATCH 01/22] Render Modal children on a mounted element --- content/docs/portals.md | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/content/docs/portals.md b/content/docs/portals.md index e8b486f5..a9292f13 100644 --- a/content/docs/portals.md +++ b/content/docs/portals.md @@ -65,7 +65,7 @@ This includes event bubbling. An event fired from inside a portal will propagate A `Parent` component in `#app-root` would be able to catch an uncaught, bubbling event from the sibling node `#modal-root`. -```js{20-23,34-41,45,53-55,62-63,66} +```js{29-34,45-52,56,64-66,73-75,77} // These two containers are siblings in the DOM const appRoot = document.getElementById('app-root'); const modalRoot = document.getElementById('modal-root'); @@ -74,10 +74,19 @@ class Modal extends React.Component { constructor(props) { super(props); this.el = document.createElement('div'); + // We need to keep track of when the portal element + // is inserted in the DOM tree since we should only + // render the modal's children on a mounted element + this.state = { + mounted: false + }; } componentDidMount() { modalRoot.appendChild(this.el); + this.setState({ + mounted: true + }); } componentWillUnmount() { @@ -86,7 +95,9 @@ class Modal extends React.Component { render() { return ReactDOM.createPortal( - this.props.children, + // This will allow any children's 'componentDidMount()' + // to be called on a mounted node + this.state.mounted ? this.props.children : null, this.el, ); } From ec575b1c9771dd4650092077795be7d1b0508f1f Mon Sep 17 00:00:00 2001 From: Mike Wilcox Date: Sun, 12 Nov 2017 13:28:13 -0500 Subject: [PATCH 02/22] Fix link (#277) Fixes the link hash --- content/docs/typechecking-with-proptypes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/typechecking-with-proptypes.md b/content/docs/typechecking-with-proptypes.md index 1605af60..a0c55898 100644 --- a/content/docs/typechecking-with-proptypes.md +++ b/content/docs/typechecking-with-proptypes.md @@ -10,7 +10,7 @@ redirect_from: > > `React.PropTypes` has moved into a different package since React v15.5. Please use [the `prop-types` library instead](https://www.npmjs.com/package/prop-types). > ->We provide [a codemod script](/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes) to automate the conversion. +>We provide [a codemod script](/blog/2017/04/07/react-v15.5.0.html#migrating-from-reactproptypes) to automate the conversion. As your app grows, you can catch a lot of bugs with typechecking. For some applications, you can use JavaScript extensions like [Flow](https://flowtype.org/) or [TypeScript](https://www.typescriptlang.org/) to typecheck your whole application. But even if you don't use those, React has some built-in typechecking abilities. To run typechecking on the props for a component, you can assign the special `propTypes` property: From 79288e29591bd4b93e4f7918ff206c95e59358a4 Mon Sep 17 00:00:00 2001 From: Mike Wilcox Date: Sun, 12 Nov 2017 13:28:29 -0500 Subject: [PATCH 03/22] Fix link (#278) Updates the link page location --- content/blog/2017-04-07-react-v15.5.0.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/blog/2017-04-07-react-v15.5.0.md b/content/blog/2017-04-07-react-v15.5.0.md index 7a61d6e8..a0654165 100644 --- a/content/blog/2017-04-07-react-v15.5.0.md +++ b/content/blog/2017-04-07-react-v15.5.0.md @@ -63,7 +63,7 @@ jscodeshift -t react-codemod/transforms/React-PropTypes-to-prop-types.js The `propTypes`, `contextTypes`, and `childContextTypes` APIs will work exactly as before. The only change is that the built-in validators now live in a separate package. -You may also consider using [Flow](https://flow.org/) to statically type check your JavaScript code, including [React components](https://flow.org/en/docs/frameworks/react/#setup-flow-with-react-a-classtoc-idtoc-setup-flow-with-react-hreftoc-setup-flow-with-reacta). +You may also consider using [Flow](https://flow.org/) to statically type check your JavaScript code, including [React components](https://flow.org/en/docs/react/components/). ### Migrating from React.createClass From da283ec8ff6c47be08881e471fa105c1883c85ec Mon Sep 17 00:00:00 2001 From: Iurii Kucherov Date: Sun, 12 Nov 2017 19:51:34 +0100 Subject: [PATCH 04/22] Update reference-react.md (#276) Hi guys, I was reading docs on `React.Children.only()` method and saw this statement `Otherwise this method throws.` and it seemed a bit unclear for me what it supposed to throw. Please let me know if this PR makes sense. Thank you! --- content/docs/reference-react.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/reference-react.md b/content/docs/reference-react.md index 4b1885ae..7cbd4a9d 100644 --- a/content/docs/reference-react.md +++ b/content/docs/reference-react.md @@ -175,7 +175,7 @@ Returns the total number of components in `children`, equal to the number of tim React.Children.only(children) ``` -Verifies that `children` has only one child (a React element) and returns it. Otherwise this method throws. +Verifies that `children` has only one child (a React element) and returns it. Otherwise this method throws an error. > Note: > From 5dfd480fe27c0cffe5f9609600af00a6bc941e5a Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Sun, 12 Nov 2017 20:26:49 +0000 Subject: [PATCH 05/22] Try to work around #280 by using Markdown for link --- content/docs/installation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/installation.md b/content/docs/installation.md index 2a5a3730..77844cfd 100644 --- a/content/docs/installation.md +++ b/content/docs/installation.md @@ -24,7 +24,7 @@ Here are a couple of ways to get started: If you're just interested in playing around with React, you can use CodePen. Try starting from [this Hello World example code](http://codepen.io/gaearon/pen/rrpgNB?editors=0010). You don't need to install anything; you can just modify the code and see if it works. -If you prefer to use your own text editor, you can also download this HTML file, edit it, and open it from the local filesystem in your browser. It does a slow runtime code transformation, so don't use it in production. +If you prefer to use your own text editor, you can also [download this HTML file](https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html), edit it, and open it from the local filesystem in your browser. It does a slow runtime code transformation, so don't use it in production. If you want to use it for a full application, there are two popular ways to get started with React: using Create React App, or adding it to an existing application. From 1dd43b2a5346c78418140db1ade16ee44052e3c5 Mon Sep 17 00:00:00 2001 From: Dani Lewandowski Date: Sun, 12 Nov 2017 20:54:14 -0500 Subject: [PATCH 06/22] Fixed an to a HOC --- content/docs/higher-order-components.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/content/docs/higher-order-components.md b/content/docs/higher-order-components.md index f4e29455..fca191d9 100644 --- a/content/docs/higher-order-components.md +++ b/content/docs/higher-order-components.md @@ -163,7 +163,7 @@ function withSubscription(WrappedComponent, selectData) { } ``` -Note that an HOC doesn't modify the input component, nor does it use inheritance to copy its behavior. Rather, an HOC *composes* the original component by *wrapping* it in a container component. An HOC is a pure function with zero side-effects. +Note that a HOC doesn't modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC *composes* the original component by *wrapping* it in a container component. A HOC is a pure function with zero side-effects. And that's it! The wrapped component receives all the props of the container, along with a new prop, `data`, which it uses to render its output. The HOC isn't concerned with how or why the data is used, and the wrapped component isn't concerned with where the data came from. @@ -173,7 +173,7 @@ Like components, the contract between `withSubscription` and the wrapped compone ## Don't Mutate the Original Component. Use Composition. -Resist the temptation to modify a component's prototype (or otherwise mutate it) inside an HOC. +Resist the temptation to modify a component's prototype (or otherwise mutate it) inside a HOC. ```js function logProps(InputComponent) { @@ -217,7 +217,7 @@ You may have noticed similarities between HOCs and a pattern called **container ## Convention: Pass Unrelated Props Through to the Wrapped Component -HOCs add features to a component. They shouldn't drastically alter its contract. It's expected that the component returned from an HOC has a similar interface to the wrapped component. +HOCs add features to a component. They shouldn't drastically alter its contract. It's expected that the component returned from a HOC has a similar interface to the wrapped component. HOCs should pass through props that are unrelated to its specific concern. Most HOCs contain a render method that looks something like this: @@ -269,7 +269,7 @@ const ConnectedComment = connect(commentSelector, commentActions)(CommentList); ```js // connect is a function that returns another function const enhance = connect(commentListSelector, commentListActions); -// The returned function is an HOC, which returns a component that is connected +// The returned function is a HOC, which returns a component that is connected // to the Redux store const ConnectedComment = enhance(CommentList); ``` @@ -297,7 +297,7 @@ The `compose` utility function is provided by many third-party libraries includi ## Convention: Wrap the Display Name for Easy Debugging -The container components created by HOCs show up in the [React Developer Tools](https://github.com/facebook/react-devtools) like any other component. To ease debugging, choose a display name that communicates that it's the result of an HOC. +The container components created by HOCs show up in the [React Developer Tools](https://github.com/facebook/react-devtools) like any other component. To ease debugging, choose a display name that communicates that it's the result of a HOC. The most common technique is to wrap the display name of the wrapped component. So if your higher-order component is named `withSubscription`, and the wrapped component's display name is `CommentList`, use the display name `WithSubscription(CommentList)`: @@ -322,7 +322,7 @@ Higher-order components come with a few caveats that aren't immediately obvious React's diffing algorithm (called reconciliation) uses component identity to determine whether it should update the existing subtree or throw it away and mount a new one. If the component returned from `render` is identical (`===`) to the component from the previous render, React recursively updates the subtree by diffing it with the new one. If they're not equal, the previous subtree is unmounted completely. -Normally, you shouldn't need to think about this. But it matters for HOCs because it means you can't apply an HOC to a component within the render method of a component: +Normally, you shouldn't need to think about this. But it matters for HOCs because it means you can't apply a HOC to a component within the render method of a component: ```js render() { @@ -338,18 +338,18 @@ The problem here isn't just about performance — remounting a component causes Instead, apply HOCs outside the component definition so that the resulting component is created only once. Then, its identity will be consistent across renders. This is usually what you want, anyway. -In those rare cases where you need to apply an HOC dynamically, you can also do it inside a component's lifecycle methods or its constructor. +In those rare cases where you need to apply a HOC dynamically, you can also do it inside a component's lifecycle methods or its constructor. ### Static Methods Must Be Copied Over Sometimes it's useful to define a static method on a React component. For example, Relay containers expose a static method `getFragment` to facilitate the composition of GraphQL fragments. -When you apply an HOC to a component, though, the original component is wrapped with a container component. That means the new component does not have any of the static methods of the original component. +When you apply a HOC to a component, though, the original component is wrapped with a container component. That means the new component does not have any of the static methods of the original component. ```js // Define a static method WrappedComponent.staticMethod = function() {/*...*/} -// Now apply an HOC +// Now apply a HOC const EnhancedComponent = enhance(WrappedComponent); // The enhanced component has no static method @@ -394,7 +394,7 @@ import MyComponent, { someFunction } from './MyComponent.js'; ### Refs Aren't Passed Through -While the convention for higher-order components is to pass through all props to the wrapped component, it's not possible to pass through refs. That's because `ref` is not really a prop — like `key`, it's handled specially by React. If you add a ref to an element whose component is the result of an HOC, the ref refers to an instance of the outermost container component, not the wrapped component. +While the convention for higher-order components is to pass through all props to the wrapped component, it's not possible to pass through refs. That's because `ref` is not really a prop — like `key`, it's handled specially by React. If you add a ref to an element whose component is the result of a HOC, the ref refers to an instance of the outermost container component, not the wrapped component. If you find yourself facing this problem, the ideal solution is to figure out how to avoid using `ref` at all. Occasionally, users who are new to the React paradigm rely on refs in situations where a prop would work better. From e9b132a28079f13dc243dbfe01ea94330efc70d9 Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Fri, 6 Oct 2017 19:32:46 -0700 Subject: [PATCH 07/22] Add FAQ pages --- content/docs/faq-ajax.md | 15 +++++ content/docs/faq-build.md | 21 +++++++ content/docs/faq-functions.md | 111 ++++++++++++++++++++++++++++++++++ content/docs/faq-internals.md | 21 +++++++ content/docs/faq-state.md | 59 ++++++++++++++++++ content/docs/faq-structure.md | 25 ++++++++ content/docs/faq-styling.md | 35 +++++++++++ content/docs/nav.yml | 18 +++++- 8 files changed, 304 insertions(+), 1 deletion(-) create mode 100644 content/docs/faq-ajax.md create mode 100644 content/docs/faq-build.md create mode 100644 content/docs/faq-functions.md create mode 100644 content/docs/faq-internals.md create mode 100644 content/docs/faq-state.md create mode 100644 content/docs/faq-structure.md create mode 100644 content/docs/faq-styling.md diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md new file mode 100644 index 00000000..88078990 --- /dev/null +++ b/content/docs/faq-ajax.md @@ -0,0 +1,15 @@ +--- +id: faq-ajax +title: AJAX and APIs +permalink: docs/faq-ajax.html +layout: docs +category: FAQ +--- + +### How can I make an AJAX call? + +You can use an AJAX library you like with React. Some popular ones are [Axios](https://github.com/axios/axios), [jQuery AJAX](https://api.jquery.com/jQuery.ajax/), and the browser built-in [window.fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). + +### Where in the component lifecycle should I make an AJAX call? + +You should populate data with AJAX calls in the [`componentDidMount`](https://reactjs.org/docs/react-component.html#mounting) lifecycle method. This is so you can use `setState` to update your component when the data is retrieved. diff --git a/content/docs/faq-build.md b/content/docs/faq-build.md new file mode 100644 index 00000000..788885b6 --- /dev/null +++ b/content/docs/faq-build.md @@ -0,0 +1,21 @@ +--- +id: faq-build +title: Babel, JSX, and Build Steps +permalink: docs/faq-build.html +layout: docs +category: FAQ +--- + +### Do I need to use JSX with React? + +No! Check out https://reactjs.org/docs/react-without-jsx.html + +### Do I need to use ES6 (+) with React? + +No! Check out https://reactjs.org/docs/react-without-es6.html + +### How can I write comments in JSX? + +``` + {*/ Comment goes here */} +``` diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md new file mode 100644 index 00000000..89837762 --- /dev/null +++ b/content/docs/faq-functions.md @@ -0,0 +1,111 @@ +--- +id: faq-functions +title: Passing Functions to Components +permalink: docs/faq-functions.html +layout: docs +category: FAQ +--- + +### How do I pass an event handler (like onClick) to a component? + +Pass event handlers and other functions as props to child components: + +```jsx + + } +} +``` + +#### Class Properties (Stage 3 Proposal) + +```jsx +class Foo extends Component { + handleClick = () => { + console.log('Click happened') + } + render() { + return + } +} +``` + +#### Bind in Render + +```jsx +class Foo extends Component { + handleClick () { + console.log('Click happened') + } + render() { + return + } +} +``` + +#### Arrow Function in Render + +```jsx +class Foo extends Component { + handleClick () { + console.log('Click happened') + } + render() { + return + } +} +``` + +**Note**: Using an arrow function or binding in render creates a new function each time the component renders, which may have performance implications (see below). + +### Is it OK to use arrow functions in render methods? + +Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions. + +If you do have performance issues, by all means, optimize! + +### Why is my function being called every time the component re-renders? + +Make sure you aren't _calling the function_ when you pass it to the component: + +```jsx +render() { + {*/ handleClick is called instead of passed as a reference! */} + return +} +``` + +### How do I pass a parameter to an event handler or callback? + +You can use an arrow function to wrap around an event handler and pass parameters: + +```jsx +class Foo extends Component { + handleClick (name) { + console.log('Clicked ' + name) + } + render() { + const name = 'My Button' + return + } +} +``` diff --git a/content/docs/faq-internals.md b/content/docs/faq-internals.md new file mode 100644 index 00000000..e90bed8d --- /dev/null +++ b/content/docs/faq-internals.md @@ -0,0 +1,21 @@ +--- +id: faq-internals +title: Virtual DOM and Internals +permalink: docs/faq-internals.html +layout: docs +category: FAQ +--- + +### What is the Virtual DOM? + +The virtual DOM (VDOM) is a programming concept where an ideal, or "virtual" representation of a UI is kept in memory and synced with the "real" DOM by a reconciliation engine/renderer (ie React Fiber + ReactDOM). + +React uses the virtual DOM to enable its declarative API: You tell React what state you want the UI to be in, and it makes sure the DOM matches that state. This abstracts out the class manipulation, event handling, and manual DOM updating that you would otherwise have to use to build your app. + +### Is the Shadow DOM the same as the Virtual DOM? + +No, they are different. The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The virtual DOM is a concept implemented by libraries in Javascript on top of browser APIs. + +### What is "React Fiber"? + +Fiber is the new reconciliation engine in React 16. It's main goal is to enable incremental rendering of the virtual DOM. [Read more](https://github.com/acdlite/react-fiber-architecture). diff --git a/content/docs/faq-state.md b/content/docs/faq-state.md new file mode 100644 index 00000000..99160b44 --- /dev/null +++ b/content/docs/faq-state.md @@ -0,0 +1,59 @@ +--- +id: faq-state +title: Component State +permalink: docs/faq-state.html +layout: docs +category: FAQ +--- + +### What does setState do? + +`setState()` schedules an update to a component's `state` object. When state changes, the component responds by re-rendering. + +### Why is `setState` is giving me the wrong value? + +Calls to `setState` are batched, so it is possible to "lose" an update if you call it with the partial object syntax: + +```jsx +incrementCount = () => { + this.setState({count: this.state.count + 1}) +} + +handleSomething() { + // this.state.count is 1, then we do this: + this.incrementCount() + this.incrementCount() // state wasn't updated yet, so this sets 2 not 3 +} +``` + +See below for how to fix this problem. + +### How do I do ordered state updates? + +Pass a function instead of an object to setState to ensure the call always uses the most updated version of state (see below). + +### What is the difference between passing an object or a function in setState? + +Passing an update function allows you to access the current state value inside the updater. Since `setState` calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting: + +```jsx +incrementCount = () => { + this.setState((prevState) => { + return {count: prevState.count + 1} + }) +} + +handleSomething() { + // this.state.count is 1, then we do this: + this.incrementCount() + this.incrementCount() // count is now 3 +} +``` + +https://reactjs.org/docs/react-component.html#setstate + +### Should I use a state management library like Redux or MobX? + +[Maybe.](http://redux.js.org/docs/faq/General.html#general-when-to-use) + +It's a good idea to get to know React first, before adding in additional libraries. You can build quite complex applications using only React. diff --git a/content/docs/faq-structure.md b/content/docs/faq-structure.md new file mode 100644 index 00000000..236a0387 --- /dev/null +++ b/content/docs/faq-structure.md @@ -0,0 +1,25 @@ +--- +id: faq-structure +title: File Structure +permalink: docs/faq-structure.html +layout: docs +category: FAQ +--- + +### Is there a recommended way to structure React projects? + +One common way to structure projects is locate CSS, JSX, and tests together inside folders grouped by feature or route. + +``` +FeatureA + index.jsx + ComponentA.jsx + ComponentA.scss + ComponentA.test.js + Helper.jsx + Helper.test.js +FeatureB + index.jsx + ComponentB.jsx + ComponentB.test.jsx +``` diff --git a/content/docs/faq-styling.md b/content/docs/faq-styling.md new file mode 100644 index 00000000..2ccd14a1 --- /dev/null +++ b/content/docs/faq-styling.md @@ -0,0 +1,35 @@ +--- +id: faq-styling +title: Styling and CSS +permalink: docs/faq-styling.html +layout: docs +category: FAQ +--- + +### How do I add CSS classes to components? + +Pass a string as the `className` prop: + +```jsx +render() { + return Menu +} +``` + +### Can I use inline styles? + +Yes, see https://reactjs.org/docs/dom-elements.html#style + +### Are inline styles bad? + +CSS classes are generally more efficient than inline styles. + +### What is CSS-in-JS? + +CSS-in-JS refers to a pattern where CSS is written with Javascript, then extracted into a stylesheet. + +[Comparison of CSS-in-JS Libraries](https://github.com/MicheleBertoli/css-in-js) + +### Can I do animations in React? + +React can be used to power animations. See [React Transition Group](https://reactcommunity.org/react-transition-group/), for example. diff --git a/content/docs/nav.yml b/content/docs/nav.yml index 71ef81aa..ecb84207 100644 --- a/content/docs/nav.yml +++ b/content/docs/nav.yml @@ -94,4 +94,20 @@ - id: implementation-notes title: Implementation Notes - id: design-principles - title: Design Principles \ No newline at end of file + title: Design Principles +- title: FAQ + items: + - id: faq-ajax + title: AJAX and APIs + - id: faq-build + title: Babel, JSX, and Build Steps + - id: faq-functions + title: Passing Functions to Components + - id: faq-state + title: Component State + - id: faq-styling + title: Styling and CSS + - id: faq-structure + title: File Structure + - id: faq-internals + title: Virtual DOM and Internals \ No newline at end of file From 84c63dd29dc5da5ef6711496925f08166146fc95 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 8 Oct 2017 21:55:33 -0700 Subject: [PATCH 08/22] add example component to AJAX FAQ --- content/docs/faq-ajax.md | 45 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md index 88078990..985d34dc 100644 --- a/content/docs/faq-ajax.md +++ b/content/docs/faq-ajax.md @@ -13,3 +13,48 @@ You can use an AJAX library you like with React. Some popular ones are [Axios](h ### Where in the component lifecycle should I make an AJAX call? You should populate data with AJAX calls in the [`componentDidMount`](https://reactjs.org/docs/react-component.html#mounting) lifecycle method. This is so you can use `setState` to update your component when the data is retrieved. + +### Example: Using AJAX results to set local state + +The component below demonstrates how to make an AJAX call in `componentDidMount` to populate local component state. + +The example API returns a JSON object like this: + +``` +{ + items: [ + { id: 1, name: 'Apples', price: '$2' }, + { id: 2, name: 'Peaches', price: '$5' } + ] +} +``` + +```jsx +class MyComponent extends React.Component { + constructor(props) { + super(props) + this.state = { + isLoaded: false, + error: null, + items: [], + } + } + + componentDidMount() { + fetch('https://api.example.com/items') + .then(res => res.json()) + .then(result => this.setState({items: result.items)) + .catch(err => this.setState({ err: error })) + } + + render() { + const {error, items} = this.state + if (err) return
{error}
+ return ( +
    + { items.map(item =>
  • {item.name} {item.price}
  • } +
+ ) + } +} +``` From a90414000536624f7fe1286ebe50d73a525882a0 Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 8 Oct 2017 22:03:24 -0700 Subject: [PATCH 09/22] add cancellation topic to AJAX FAQ --- content/docs/faq-ajax.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md index 985d34dc..f0b741da 100644 --- a/content/docs/faq-ajax.md +++ b/content/docs/faq-ajax.md @@ -58,3 +58,7 @@ class MyComponent extends React.Component { } } ``` + +### Cancellation + +Note that if the component unmounts before an AJAX call is complete, you may see a warning like `cannot read property 'setState' of undefined`. If this is an issue you may want to keep track of inflight AJAX requests and cancel them in the `componentWillUnmount` lifecycle method. From 0143515ed5fcc202476ab6c2e1a3af20c31e02ae Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 8 Oct 2017 22:59:35 -0700 Subject: [PATCH 10/22] fix typos --- content/docs/faq-ajax.md | 2 +- content/docs/faq-build.md | 4 ++-- content/docs/faq-functions.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md index f0b741da..511f0a9a 100644 --- a/content/docs/faq-ajax.md +++ b/content/docs/faq-ajax.md @@ -8,7 +8,7 @@ category: FAQ ### How can I make an AJAX call? -You can use an AJAX library you like with React. Some popular ones are [Axios](https://github.com/axios/axios), [jQuery AJAX](https://api.jquery.com/jQuery.ajax/), and the browser built-in [window.fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). +You can use any AJAX library you like with React. Some popular ones are [Axios](https://github.com/axios/axios), [jQuery AJAX](https://api.jquery.com/jQuery.ajax/), and the browser built-in [window.fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). ### Where in the component lifecycle should I make an AJAX call? diff --git a/content/docs/faq-build.md b/content/docs/faq-build.md index 788885b6..c447eadc 100644 --- a/content/docs/faq-build.md +++ b/content/docs/faq-build.md @@ -16,6 +16,6 @@ No! Check out https://reactjs.org/docs/react-without-es6.html ### How can I write comments in JSX? -``` - {*/ Comment goes here */} +```jsx + {/* Comment goes here */} ``` diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md index 89837762..8f708c7f 100644 --- a/content/docs/faq-functions.md +++ b/content/docs/faq-functions.md @@ -89,7 +89,7 @@ Make sure you aren't _calling the function_ when you pass it to the component: ```jsx render() { - {*/ handleClick is called instead of passed as a reference! */} + {/* handleClick is called instead of passed as a reference! */} return } ``` From bac965ed83a92edd3fc9fd29d8dcef332d627f47 Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 8 Oct 2017 23:54:16 -0700 Subject: [PATCH 11/22] add example using data-attributes for event handler data --- content/docs/faq-functions.md | 72 ++++++++++++++++++++++++++++++++--- 1 file changed, 66 insertions(+), 6 deletions(-) diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md index 8f708c7f..0dcbe3c3 100644 --- a/content/docs/faq-functions.md +++ b/content/docs/faq-functions.md @@ -99,13 +99,73 @@ render() { You can use an arrow function to wrap around an event handler and pass parameters: ```jsx -class Foo extends Component { - handleClick (name) { - console.log('Clicked ' + name) + this.handleClick(id)} /> +``` + +This is equivalent to calling `.bind`: + +```jsx + +``` + +#### Example: Passing params using arrow functions + +```jsx +class Component extends React.Component { + state = { + justClicked: 0, + items: Array.from({length: 5}, (_, i) => i) } - render() { - const name = 'My Button' - return + + handleClick = i => this.setState({ justClicked: i }) + + render () { + return ( +
+ Just clicked: {this.state.justClicked} +
    + { this.state.items.map(i => +
  • this.handleClick(i)}> + Item: {i} +
  • + ) } +
+
+ ) + } +} +``` + +#### Example: Passing params using data-attributes + +Alternately, you can use DOM APIs to store data needed for event handlers. Consider this approach if you need to optimize a large number of elements or have a render tree that relies on React.PureComponent equality checks. + +```jsx +class Component extends React.Component { + state = { + justClicked: 0, + items: Array.from({length: 5}, (_, i) => i) + } + + handleClick = event => { + this.setState({ + justClicked: event.target.dataset.i + }) + } + + render () { + return ( +
+ Just clicked: {this.state.justClicked} +
    + { this.state.items.map(i => +
  • + Item: {i} +
  • + ) } +
+
+ ) } } ``` From b1d64dc8a299bacd96f5ec540b22f3262ff93dda Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 12 Nov 2017 20:04:10 -0800 Subject: [PATCH 12/22] Handle more states in async example code --- content/docs/faq-ajax.md | 56 ++++++++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 20 deletions(-) diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md index 511f0a9a..5dd852e0 100644 --- a/content/docs/faq-ajax.md +++ b/content/docs/faq-ajax.md @@ -31,30 +31,46 @@ The example API returns a JSON object like this: ```jsx class MyComponent extends React.Component { - constructor(props) { - super(props) - this.state = { - isLoaded: false, - error: null, - items: [], - } - } - + state = { + error: null, + isLoaded: false, + items: [] + }; + componentDidMount() { - fetch('https://api.example.com/items') + fetch("https://api.example.com/items") .then(res => res.json()) - .then(result => this.setState({items: result.items)) - .catch(err => this.setState({ err: error })) + .then(result => + this.setState({ + isLoaded: true, + items: result.items + }) + ) + .catch(error => + this.setState({ + isLoaded: true, + error + }) + ); } - + render() { - const {error, items} = this.state - if (err) return
{error}
- return ( -
    - { items.map(item =>
  • {item.name} {item.price}
  • } -
- ) + const { error, items } = this.state; + if (error) { + return
Error: {error.message}
; + } else if (!isLoaded) { + return
Loading ...
; + } else { + return ( +
    + {items.map(item => ( +
  • + {item.name} {item.price} +
  • + ))} +
+ ); + } } } ``` From 3dbc6355e9056eb9021ae27ed0f9c5abba766cb2 Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 12 Nov 2017 20:04:21 -0800 Subject: [PATCH 13/22] Add context to comment syntax example --- content/docs/faq-build.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/content/docs/faq-build.md b/content/docs/faq-build.md index c447eadc..8b63c912 100644 --- a/content/docs/faq-build.md +++ b/content/docs/faq-build.md @@ -17,5 +17,8 @@ No! Check out https://reactjs.org/docs/react-without-es6.html ### How can I write comments in JSX? ```jsx - {/* Comment goes here */} +
+ {/* Comment goes here */} + Hello, {name}! +
``` From 3a029d59e8a2fe45ad90e97d4fe2e7a33cd043d5 Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 12 Nov 2017 20:04:55 -0800 Subject: [PATCH 14/22] Add note about performance implications of .bind in render --- content/docs/faq-functions.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md index 0dcbe3c3..816f5bcc 100644 --- a/content/docs/faq-functions.md +++ b/content/docs/faq-functions.md @@ -62,6 +62,8 @@ class Foo extends Component { } ``` +**Note**: Using an arrow function or binding in render creates a new function each time the component renders, which may have performance implications (see below). + #### Arrow Function in Render ```jsx From d7beebb65a95f80effd7ffd2b7927939bf1395e4 Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 12 Nov 2017 20:05:27 -0800 Subject: [PATCH 15/22] make sure param-passing example uses keys realistically --- content/docs/faq-functions.md | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md index 816f5bcc..69438703 100644 --- a/content/docs/faq-functions.md +++ b/content/docs/faq-functions.md @@ -113,22 +113,23 @@ This is equivalent to calling `.bind`: #### Example: Passing params using arrow functions ```jsx -class Component extends React.Component { +const A = 65 // ASCII character code +class Alphabet extends React.Component { state = { - justClicked: 0, - items: Array.from({length: 5}, (_, i) => i) + justClicked: null, + letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i)) } - handleClick = i => this.setState({ justClicked: i }) + handleClick = letter => this.setState({ justClicked: letter }) render () { return (
Just clicked: {this.state.justClicked}
    - { this.state.items.map(i => -
  • this.handleClick(i)}> - Item: {i} + { this.state.letters.map(letter => +
  • this.handleClick(letter)}> + {letter}
  • ) }
@@ -143,15 +144,16 @@ class Component extends React.Component { Alternately, you can use DOM APIs to store data needed for event handlers. Consider this approach if you need to optimize a large number of elements or have a render tree that relies on React.PureComponent equality checks. ```jsx -class Component extends React.Component { +const A = 65 // ASCII character code +class Alphabet extends React.Component { state = { - justClicked: 0, - items: Array.from({length: 5}, (_, i) => i) + justClicked: null, + letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i)) } handleClick = event => { this.setState({ - justClicked: event.target.dataset.i + justClicked: event.target.dataset.letter }) } @@ -160,9 +162,9 @@ class Component extends React.Component {
Just clicked: {this.state.justClicked}
    - { this.state.items.map(i => -
  • - Item: {i} + { this.state.letters.map(letter => +
  • + {letter}
  • ) }
From 6d8c199203d7cbbbd89761522ba45c48204fc77a Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 12 Nov 2017 20:06:22 -0800 Subject: [PATCH 16/22] Don't show raw URLs in links --- content/docs/faq-state.md | 2 +- content/docs/faq-styling.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/content/docs/faq-state.md b/content/docs/faq-state.md index 99160b44..bbba16a3 100644 --- a/content/docs/faq-state.md +++ b/content/docs/faq-state.md @@ -50,7 +50,7 @@ handleSomething() { } ``` -https://reactjs.org/docs/react-component.html#setstate +[Learn more about setState](/docs/react-component.html#setstate) ### Should I use a state management library like Redux or MobX? diff --git a/content/docs/faq-styling.md b/content/docs/faq-styling.md index 2ccd14a1..c69eeb17 100644 --- a/content/docs/faq-styling.md +++ b/content/docs/faq-styling.md @@ -18,7 +18,7 @@ render() { ### Can I use inline styles? -Yes, see https://reactjs.org/docs/dom-elements.html#style +Yes, see the docs on styling [here](/docs/dom-elements.html#style). ### Are inline styles bad? From 21143853fcda2fc6f5d5408d89ce2806a85e8c57 Mon Sep 17 00:00:00 2001 From: Alex Krolick Date: Sun, 12 Nov 2017 20:06:44 -0800 Subject: [PATCH 17/22] Clarify setState troubleshooting example --- content/docs/faq-state.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/content/docs/faq-state.md b/content/docs/faq-state.md index bbba16a3..1fe0393b 100644 --- a/content/docs/faq-state.md +++ b/content/docs/faq-state.md @@ -12,7 +12,9 @@ category: FAQ ### Why is `setState` is giving me the wrong value? -Calls to `setState` are batched, so it is possible to "lose" an update if you call it with the partial object syntax: +Calls to `setState` are asynchronous - don't rely on `this.state` to reflect the new value immediately after calling `setState`. Pass an updater function instead of an object if you need compute values based on the current state (see below for details). + +Example of code that will not behave as expected: ```jsx incrementCount = () => { @@ -28,7 +30,7 @@ handleSomething() { See below for how to fix this problem. -### How do I do ordered state updates? +### How do I update state with values that depend on the current state? Pass a function instead of an object to setState to ensure the call always uses the most updated version of state (see below). From f3fdc9b3b154cbca2e5ba77107cf5884a3182a9c Mon Sep 17 00:00:00 2001 From: Darren Scerri Date: Mon, 13 Nov 2017 17:05:38 +0100 Subject: [PATCH 18/22] Add warning about Modal children mounting detached from DOM tree --- content/docs/portals.md | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/content/docs/portals.md b/content/docs/portals.md index a9292f13..d0080447 100644 --- a/content/docs/portals.md +++ b/content/docs/portals.md @@ -65,7 +65,7 @@ This includes event bubbling. An event fired from inside a portal will propagate A `Parent` component in `#app-root` would be able to catch an uncaught, bubbling event from the sibling node `#modal-root`. -```js{29-34,45-52,56,64-66,73-75,77} +```js{28-31,42-49,53,61-63,70-71,74} // These two containers are siblings in the DOM const appRoot = document.getElementById('app-root'); const modalRoot = document.getElementById('modal-root'); @@ -74,19 +74,18 @@ class Modal extends React.Component { constructor(props) { super(props); this.el = document.createElement('div'); - // We need to keep track of when the portal element - // is inserted in the DOM tree since we should only - // render the modal's children on a mounted element - this.state = { - mounted: false - }; } componentDidMount() { + // The portal element is inserted in the DOM tree after + // the Modal's children are mounted, meaning that children + // will be mounted on a detached DOM node. If a child + // component requires to be attached to the DOM tree + // immediately when mounted, for example to measure a + // DOM node, or uses 'autoFocus' in a descendant, add + // state to Modal and only render the children when Modal + // is inserted in the DOM tree. modalRoot.appendChild(this.el); - this.setState({ - mounted: true - }); } componentWillUnmount() { @@ -95,9 +94,7 @@ class Modal extends React.Component { render() { return ReactDOM.createPortal( - // This will allow any children's 'componentDidMount()' - // to be called on a mounted node - this.state.mounted ? this.props.children : null, + this.props.children, this.el, ); } From c4faaf6ab6c56a94c1cb9040ab1edcce58b20466 Mon Sep 17 00:00:00 2001 From: Brian Vaughn Date: Mon, 13 Nov 2017 08:06:45 -0800 Subject: [PATCH 19/22] Changed link style --- content/docs/faq-build.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/docs/faq-build.md b/content/docs/faq-build.md index 8b63c912..9c112cd2 100644 --- a/content/docs/faq-build.md +++ b/content/docs/faq-build.md @@ -8,11 +8,11 @@ category: FAQ ### Do I need to use JSX with React? -No! Check out https://reactjs.org/docs/react-without-jsx.html +No! Check out ["React Without JSX"](/docs/react-without-jsx.html) to learn more. ### Do I need to use ES6 (+) with React? -No! Check out https://reactjs.org/docs/react-without-es6.html +No! Check out ["React Without ES6"](/docs/react-without-es6.html) to learn more. ### How can I write comments in JSX? From 996508d16f5002d2995cf6cc4ad6e922be2520f1 Mon Sep 17 00:00:00 2001 From: Brian Vaughn Date: Mon, 13 Nov 2017 08:11:22 -0800 Subject: [PATCH 20/22] Formatted inline "Notes" --- content/docs/faq-functions.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md index 69438703..9fe225da 100644 --- a/content/docs/faq-functions.md +++ b/content/docs/faq-functions.md @@ -62,7 +62,9 @@ class Foo extends Component { } ``` -**Note**: Using an arrow function or binding in render creates a new function each time the component renders, which may have performance implications (see below). +>**Note:** +> +>Using `Function.prototype.bind` in render creates a new function each time the component renders, which may have performance implications; (see below). #### Arrow Function in Render @@ -77,7 +79,9 @@ class Foo extends Component { } ``` -**Note**: Using an arrow function or binding in render creates a new function each time the component renders, which may have performance implications (see below). +>**Note:** +> +>Using an arrow in render creates a new function each time the component renders, which may have performance implications; (see below). ### Is it OK to use arrow functions in render methods? @@ -85,7 +89,7 @@ Generally speaking, yes, it is OK, and it is often the easiest way to pass param If you do have performance issues, by all means, optimize! -### Why is my function being called every time the component re-renders? +### Why is my function being called every time the component renders? Make sure you aren't _calling the function_ when you pass it to the component: From 1b6dad1eed4cffc94297861ed583b9b672d7febe Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Mon, 13 Nov 2017 16:16:05 +0000 Subject: [PATCH 21/22] React 16.1.1 --- src/site-constants.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/site-constants.js b/src/site-constants.js index 9de60e45..866fd14e 100644 --- a/src/site-constants.js +++ b/src/site-constants.js @@ -10,7 +10,7 @@ // NOTE: We can't just use `location.toString()` because when we are rendering // the SSR part in node.js we won't have a proper location. const urlRoot = 'https://reactjs.org'; -const version = '16.1.0'; +const version = '16.1.1'; const babelURL = '//unpkg.com/babel-standalone@6.26.0/babel.min.js'; export {urlRoot, version, babelURL}; From 2b4b34ac0f83ea369c8dbac04491973b72e39646 Mon Sep 17 00:00:00 2001 From: Brian Vaughn Date: Mon, 13 Nov 2017 08:16:58 -0800 Subject: [PATCH 22/22] Corrected my own typo :) --- content/docs/faq-functions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md index 9fe225da..6cb41a57 100644 --- a/content/docs/faq-functions.md +++ b/content/docs/faq-functions.md @@ -81,7 +81,7 @@ class Foo extends Component { >**Note:** > ->Using an arrow in render creates a new function each time the component renders, which may have performance implications; (see below). +>Using an arrow function in render creates a new function each time the component renders, which may have performance implications; (see below). ### Is it OK to use arrow functions in render methods?