Brian Vaughn
7 years ago
committed by
GitHub
8 changed files with 442 additions and 1 deletions
@ -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. |
@ -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> |
||||
|
``` |
@ -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> |
||||
|
) |
||||
|
} |
||||
|
} |
||||
|
``` |
@ -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). |
@ -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. |
@ -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 |
||||
|
``` |
@ -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. |
Loading…
Reference in new issue