Skip to content

Commit ed329ea

Browse files
committed
Merge branch 'master' into mateoholman-community-section-new
2 parents 5d24533 + 523abd8 commit ed329ea

15 files changed

+466
-17
lines changed

content/blog/2017-04-07-react-v15.5.0.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ jscodeshift -t react-codemod/transforms/React-PropTypes-to-prop-types.js <path>
6363

6464
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.
6565

66-
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).
66+
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/).
6767

6868
### Migrating from React.createClass
6969

content/docs/faq-ajax.md

+80
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
---
2+
id: faq-ajax
3+
title: AJAX and APIs
4+
permalink: docs/faq-ajax.html
5+
layout: docs
6+
category: FAQ
7+
---
8+
9+
### How can I make an AJAX call?
10+
11+
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).
12+
13+
### Where in the component lifecycle should I make an AJAX call?
14+
15+
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.
16+
17+
### Example: Using AJAX results to set local state
18+
19+
The component below demonstrates how to make an AJAX call in `componentDidMount` to populate local component state.
20+
21+
The example API returns a JSON object like this:
22+
23+
```
24+
{
25+
items: [
26+
{ id: 1, name: 'Apples', price: '$2' },
27+
{ id: 2, name: 'Peaches', price: '$5' }
28+
]
29+
}
30+
```
31+
32+
```jsx
33+
class MyComponent extends React.Component {
34+
state = {
35+
error: null,
36+
isLoaded: false,
37+
items: []
38+
};
39+
40+
componentDidMount() {
41+
fetch("https://api.example.com/items")
42+
.then(res => res.json())
43+
.then(result =>
44+
this.setState({
45+
isLoaded: true,
46+
items: result.items
47+
})
48+
)
49+
.catch(error =>
50+
this.setState({
51+
isLoaded: true,
52+
error
53+
})
54+
);
55+
}
56+
57+
render() {
58+
const { error, items } = this.state;
59+
if (error) {
60+
return <div>Error: {error.message}</div>;
61+
} else if (!isLoaded) {
62+
return <div>Loading ...</div>;
63+
} else {
64+
return (
65+
<ul>
66+
{items.map(item => (
67+
<li key={item.name}>
68+
{item.name} {item.price}
69+
</li>
70+
))}
71+
</ul>
72+
);
73+
}
74+
}
75+
}
76+
```
77+
78+
### Cancellation
79+
80+
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.

content/docs/faq-build.md

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
id: faq-build
3+
title: Babel, JSX, and Build Steps
4+
permalink: docs/faq-build.html
5+
layout: docs
6+
category: FAQ
7+
---
8+
9+
### Do I need to use JSX with React?
10+
11+
No! Check out ["React Without JSX"](/docs/react-without-jsx.html) to learn more.
12+
13+
### Do I need to use ES6 (+) with React?
14+
15+
No! Check out ["React Without ES6"](/docs/react-without-es6.html) to learn more.
16+
17+
### How can I write comments in JSX?
18+
19+
```jsx
20+
<div>
21+
{/* Comment goes here */}
22+
Hello, {name}!
23+
</div>
24+
```

content/docs/faq-functions.md

+179
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,179 @@
1+
---
2+
id: faq-functions
3+
title: Passing Functions to Components
4+
permalink: docs/faq-functions.html
5+
layout: docs
6+
category: FAQ
7+
---
8+
9+
### How do I pass an event handler (like onClick) to a component?
10+
11+
Pass event handlers and other functions as props to child components:
12+
13+
```jsx
14+
<button onClick={this.handleClick}>
15+
```
16+
17+
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).
18+
19+
### How do I bind a function to a component instance?
20+
21+
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.
22+
23+
#### Bind in Constructor (ES2015)
24+
25+
```jsx
26+
class Foo extends Component {
27+
constructor () {
28+
this.handleClick = this.handleClick.bind(this)
29+
}
30+
handleClick() {
31+
console.log('Click happened')
32+
}
33+
render() {
34+
return <button onClick={this.handleClick}>Click Me</button>
35+
}
36+
}
37+
```
38+
39+
#### Class Properties (Stage 3 Proposal)
40+
41+
```jsx
42+
class Foo extends Component {
43+
handleClick = () => {
44+
console.log('Click happened')
45+
}
46+
render() {
47+
return <button onClick={this.handleClick}>Click Me</button>
48+
}
49+
}
50+
```
51+
52+
#### Bind in Render
53+
54+
```jsx
55+
class Foo extends Component {
56+
handleClick () {
57+
console.log('Click happened')
58+
}
59+
render() {
60+
return <button onClick={this.handleClick.bind(this)}>Click Me</button>
61+
}
62+
}
63+
```
64+
65+
>**Note:**
66+
>
67+
>Using `Function.prototype.bind` in render creates a new function each time the component renders, which may have performance implications; (see below).
68+
69+
#### Arrow Function in Render
70+
71+
```jsx
72+
class Foo extends Component {
73+
handleClick () {
74+
console.log('Click happened')
75+
}
76+
render() {
77+
return <button onClick={() => this.handleClick()}>Click Me</button>
78+
}
79+
}
80+
```
81+
82+
>**Note:**
83+
>
84+
>Using an arrow function in render creates a new function each time the component renders, which may have performance implications; (see below).
85+
86+
### Is it OK to use arrow functions in render methods?
87+
88+
Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions.
89+
90+
If you do have performance issues, by all means, optimize!
91+
92+
### Why is my function being called every time the component renders?
93+
94+
Make sure you aren't _calling the function_ when you pass it to the component:
95+
96+
```jsx
97+
render() {
98+
{/* handleClick is called instead of passed as a reference! */}
99+
return <button onClick={this.handleClick()}>Click Me</button>
100+
}
101+
```
102+
103+
### How do I pass a parameter to an event handler or callback?
104+
105+
You can use an arrow function to wrap around an event handler and pass parameters:
106+
107+
```jsx
108+
<Element onClick={() => this.handleClick(id)} />
109+
```
110+
111+
This is equivalent to calling `.bind`:
112+
113+
```jsx
114+
<Element onClick={this.handleClick.bind(this, id)} />
115+
```
116+
117+
#### Example: Passing params using arrow functions
118+
119+
```jsx
120+
const A = 65 // ASCII character code
121+
class Alphabet extends React.Component {
122+
state = {
123+
justClicked: null,
124+
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
125+
}
126+
127+
handleClick = letter => this.setState({ justClicked: letter })
128+
129+
render () {
130+
return (
131+
<div>
132+
Just clicked: {this.state.justClicked}
133+
<ul>
134+
{ this.state.letters.map(letter =>
135+
<li key={letter} onClick={() => this.handleClick(letter)}>
136+
{letter}
137+
</li>
138+
) }
139+
</ul>
140+
</div>
141+
)
142+
}
143+
}
144+
```
145+
146+
#### Example: Passing params using data-attributes
147+
148+
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.
149+
150+
```jsx
151+
const A = 65 // ASCII character code
152+
class Alphabet extends React.Component {
153+
state = {
154+
justClicked: null,
155+
letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i))
156+
}
157+
158+
handleClick = event => {
159+
this.setState({
160+
justClicked: event.target.dataset.letter
161+
})
162+
}
163+
164+
render () {
165+
return (
166+
<div>
167+
Just clicked: {this.state.justClicked}
168+
<ul>
169+
{ this.state.letters.map(letter =>
170+
<li key={letter} data-letter={letter} onClick={this.handleClick}>
171+
{letter}
172+
</li>
173+
) }
174+
</ul>
175+
</div>
176+
)
177+
}
178+
}
179+
```

content/docs/faq-internals.md

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
id: faq-internals
3+
title: Virtual DOM and Internals
4+
permalink: docs/faq-internals.html
5+
layout: docs
6+
category: FAQ
7+
---
8+
9+
### What is the Virtual DOM?
10+
11+
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).
12+
13+
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.
14+
15+
### Is the Shadow DOM the same as the Virtual DOM?
16+
17+
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.
18+
19+
### What is "React Fiber"?
20+
21+
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).

content/docs/faq-state.md

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
id: faq-state
3+
title: Component State
4+
permalink: docs/faq-state.html
5+
layout: docs
6+
category: FAQ
7+
---
8+
9+
### What does setState do?
10+
11+
`setState()` schedules an update to a component's `state` object. When state changes, the component responds by re-rendering.
12+
13+
### Why is `setState` is giving me the wrong value?
14+
15+
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).
16+
17+
Example of code that will not behave as expected:
18+
19+
```jsx
20+
incrementCount = () => {
21+
this.setState({count: this.state.count + 1})
22+
}
23+
24+
handleSomething() {
25+
// this.state.count is 1, then we do this:
26+
this.incrementCount()
27+
this.incrementCount() // state wasn't updated yet, so this sets 2 not 3
28+
}
29+
```
30+
31+
See below for how to fix this problem.
32+
33+
### How do I update state with values that depend on the current state?
34+
35+
Pass a function instead of an object to setState to ensure the call always uses the most updated version of state (see below).
36+
37+
### What is the difference between passing an object or a function in setState?
38+
39+
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:
40+
41+
```jsx
42+
incrementCount = () => {
43+
this.setState((prevState) => {
44+
return {count: prevState.count + 1}
45+
})
46+
}
47+
48+
handleSomething() {
49+
// this.state.count is 1, then we do this:
50+
this.incrementCount()
51+
this.incrementCount() // count is now 3
52+
}
53+
```
54+
55+
[Learn more about setState](/docs/react-component.html#setstate)
56+
57+
### Should I use a state management library like Redux or MobX?
58+
59+
[Maybe.](http://redux.js.org/docs/faq/General.html#general-when-to-use)
60+
61+
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.

0 commit comments

Comments
 (0)