Browse Source

Merge branch 'master' into mateoholman-community-section-new

main
Matthew Holman 7 years ago
parent
commit
ed329eac8d
  1. 2
      content/blog/2017-04-07-react-v15.5.0.md
  2. 80
      content/docs/faq-ajax.md
  3. 24
      content/docs/faq-build.md
  4. 179
      content/docs/faq-functions.md
  5. 21
      content/docs/faq-internals.md
  6. 61
      content/docs/faq-state.md
  7. 25
      content/docs/faq-structure.md
  8. 35
      content/docs/faq-styling.md
  9. 20
      content/docs/higher-order-components.md
  10. 2
      content/docs/installation.md
  11. 18
      content/docs/nav.yml
  12. 10
      content/docs/portals.md
  13. 2
      content/docs/reference-react.md
  14. 2
      content/docs/typechecking-with-proptypes.md
  15. 2
      src/site-constants.js

2
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 <path>
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

80
content/docs/faq-ajax.md

@ -0,0 +1,80 @@
---
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 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?
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 {
state = {
error: null,
isLoaded: false,
items: []
};
componentDidMount() {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(result =>
this.setState({
isLoaded: true,
items: result.items
})
)
.catch(error =>
this.setState({
isLoaded: true,
error
})
);
}
render() {
const { error, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading ...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
}
```
### 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.

24
content/docs/faq-build.md

@ -0,0 +1,24 @@
---
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 ["React Without JSX"](/docs/react-without-jsx.html) to learn more.
### Do I need to use ES6 (+) with React?
No! Check out ["React Without ES6"](/docs/react-without-es6.html) to learn more.
### How can I write comments in JSX?
```jsx
<div>
{/* Comment goes here */}
Hello, {name}!
</div>
```

179
content/docs/faq-functions.md

@ -0,0 +1,179 @@
---
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
<button onClick={this.handleClick}>
```
If you need to have access to the parent component in the handler, you also need to bind the function to the component instance (see below).
### How do I bind a function to a component instance?
There are several ways to make sure functions have access to component attributes like `this.props` and `this.state`, depending on which syntax and build steps you are using.
#### Bind in Constructor (ES2015)
```jsx
class Foo extends Component {
constructor () {
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
console.log('Click happened')
}
render() {
return <button onClick={this.handleClick}>Click Me</button>
}
}
```
#### Class Properties (Stage 3 Proposal)
```jsx
class Foo extends Component {
handleClick = () => {
console.log('Click happened')
}
render() {
return <button onClick={this.handleClick}>Click Me</button>
}
}
```
#### Bind in Render
```jsx
class Foo extends Component {
handleClick () {
console.log('Click happened')
}
render() {
return <button onClick={this.handleClick.bind(this)}>Click Me</button>
}
}
```
>**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
```jsx
class Foo extends Component {
handleClick () {
console.log('Click happened')
}
render() {
return <button onClick={() => this.handleClick()}>Click Me</button>
}
}
```
>**Note:**
>
>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?
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 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 <button onClick={this.handleClick()}>Click Me</button>
}
```
### 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
<Element onClick={() => this.handleClick(id)} />
```
This is equivalent to calling `.bind`:
```jsx
<Element onClick={this.handleClick.bind(this, id)} />
```
#### Example: Passing params using arrow functions
```jsx
const A = 65 // ASCII character code
class Alphabet extends React.Component {
state = {
justClicked: null,
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
}
handleClick = letter => this.setState({ justClicked: letter })
render () {
return (
<div>
Just clicked: {this.state.justClicked}
<ul>
{ this.state.letters.map(letter =>
<li key={letter} onClick={() => this.handleClick(letter)}>
{letter}
</li>
) }
</ul>
</div>
)
}
}
```
#### 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
const A = 65 // ASCII character code
class Alphabet extends React.Component {
state = {
justClicked: null,
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
}
handleClick = event => {
this.setState({
justClicked: event.target.dataset.letter
})
}
render () {
return (
<div>
Just clicked: {this.state.justClicked}
<ul>
{ this.state.letters.map(letter =>
<li key={letter} data-letter={letter} onClick={this.handleClick}>
{letter}
</li>
) }
</ul>
</div>
)
}
}
```

21
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).

61
content/docs/faq-state.md

@ -0,0 +1,61 @@
---
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 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 = () => {
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 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).
### 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
}
```
[Learn more about setState](/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.

25
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
```

35
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 <span className="menu navigation-menu">Menu</span>
}
```
### Can I use inline styles?
Yes, see the docs on styling [here](/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.

20
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.

2
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 <a href="https://raw.githubusercontent.com/reactjs/reactjs.org/master/static/html/single-file-example.html" download="hello.html">download this HTML file</a>, 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.

18
content/docs/nav.yml

@ -94,4 +94,20 @@
- id: implementation-notes
title: Implementation Notes
- id: design-principles
title: Design Principles
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

10
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{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');
@ -77,6 +77,14 @@ class Modal extends React.Component {
}
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);
}

2
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:
>

2
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:

2
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};

Loading…
Cancel
Save