diff --git a/content/docs/faq-ajax.md b/content/docs/faq-ajax.md new file mode 100644 index 00000000..5dd852e0 --- /dev/null +++ b/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
Error: {error.message}
; + } else if (!isLoaded) { + return
Loading ...
; + } else { + return ( + + ); + } + } +} +``` + +### 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. diff --git a/content/docs/faq-build.md b/content/docs/faq-build.md new file mode 100644 index 00000000..9c112cd2 --- /dev/null +++ b/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 +
+ {/* Comment goes here */} + Hello, {name}! +
+``` diff --git a/content/docs/faq-functions.md b/content/docs/faq-functions.md new file mode 100644 index 00000000..6cb41a57 --- /dev/null +++ b/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 + + } +} +``` + +#### 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 + } +} +``` + +>**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 + } +} +``` + +>**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 +} +``` + +### 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 + this.handleClick(id)} /> +``` + +This is equivalent to calling `.bind`: + +```jsx + +``` + +#### 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 ( +
+ Just clicked: {this.state.justClicked} +
    + { this.state.letters.map(letter => +
  • this.handleClick(letter)}> + {letter} +
  • + ) } +
+
+ ) + } +} +``` + +#### 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 ( +
+ Just clicked: {this.state.justClicked} +
    + { this.state.letters.map(letter => +
  • + {letter} +
  • + ) } +
+
+ ) + } +} +``` 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..1fe0393b --- /dev/null +++ b/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. 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..c69eeb17 --- /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 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. 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