Browse Source

Add git hook to generate headings ids (#4043)

* Add git hook to generate headings ids

* Fixes "Analyze Bundle" workflow
main
Alexey Pyltsyn 3 years ago
committed by GitHub
parent
commit
0b7fd7b7a4
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 6
      beta/.husky/pre-commit
  2. 7
      beta/package.json
  3. 12
      beta/src/pages/community/acknowledgements.md
  4. 8
      beta/src/pages/community/index.md
  5. 22
      beta/src/pages/community/meet-the-team.md
  6. 10
      beta/src/pages/index.md
  7. 22
      beta/src/pages/learn/add-react-to-a-website.md
  8. 16
      beta/src/pages/learn/adding-interactivity.md
  9. 20
      beta/src/pages/learn/choosing-the-state-structure.md
  10. 18
      beta/src/pages/learn/conditional-rendering.md
  11. 18
      beta/src/pages/learn/describing-the-ui.md
  12. 10
      beta/src/pages/learn/editor-setup.md
  13. 22
      beta/src/pages/learn/extracting-state-logic-into-a-reducer.md
  14. 8
      beta/src/pages/learn/importing-and-exporting-components.md
  15. 18
      beta/src/pages/learn/index.md
  16. 10
      beta/src/pages/learn/installation.md
  17. 16
      beta/src/pages/learn/javascript-in-jsx-with-curly-braces.md
  18. 14
      beta/src/pages/learn/keeping-components-pure.md
  19. 16
      beta/src/pages/learn/managing-state.md
  20. 20
      beta/src/pages/learn/manipulating-the-dom-with-refs.md
  21. 20
      beta/src/pages/learn/passing-data-deeply-with-context.md
  22. 22
      beta/src/pages/learn/passing-props-to-a-component.md
  23. 26
      beta/src/pages/learn/preserving-and-resetting-state.md
  24. 14
      beta/src/pages/learn/queueing-a-series-of-state-updates.md
  25. 6
      beta/src/pages/learn/react-developer-tools.md
  26. 20
      beta/src/pages/learn/reacting-to-input-with-state.md
  27. 20
      beta/src/pages/learn/referencing-values-with-refs.md
  28. 12
      beta/src/pages/learn/render-and-commit.md
  29. 20
      beta/src/pages/learn/rendering-lists.md
  30. 22
      beta/src/pages/learn/responding-to-events.md
  31. 10
      beta/src/pages/learn/scaling-up-with-reducer-and-context.md
  32. 14
      beta/src/pages/learn/sharing-state-between-components.md
  33. 12
      beta/src/pages/learn/start-a-new-react-project.md
  34. 20
      beta/src/pages/learn/state-a-components-memory.md
  35. 8
      beta/src/pages/learn/state-as-a-snapshot.md
  36. 14
      beta/src/pages/learn/thinking-in-react.md
  37. 26
      beta/src/pages/learn/updating-arrays-in-state.md
  38. 16
      beta/src/pages/learn/updating-objects-in-state.md
  39. 16
      beta/src/pages/learn/writing-markup-with-jsx.md
  40. 24
      beta/src/pages/learn/your-first-component.md
  41. 4
      beta/src/pages/reference/index.md
  42. 6
      beta/src/pages/reference/reactdom.md
  43. 10
      beta/src/pages/reference/render.md
  44. 24
      beta/src/pages/reference/usestate.md
  45. 17
      beta/yarn.lock

6
beta/.husky/pre-commit

@ -0,0 +1,6 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
cd beta
yarn generate-ids
git add -u src/pages/**/*.md

7
beta/package.json

@ -12,10 +12,11 @@
"nit:source": "prettier --config .prettierrc --list-different \"{plugins,src}/**/*.{js,ts,jsx,tsx}\"", "nit:source": "prettier --config .prettierrc --list-different \"{plugins,src}/**/*.{js,ts,jsx,tsx}\"",
"prettier": "yarn format:source", "prettier": "yarn format:source",
"prettier:diff": "yarn nit:source", "prettier:diff": "yarn nit:source",
"generate-ids": "node scripts/generateHeadingIDs.js src/pages/docs && node scripts/generateHeadingIDs.js src/pages/blog", "generate-ids": "node scripts/generateHeadingIDs.js src/pages/",
"ci-check": "npm-run-all prettier:diff --parallel lint tsc", "ci-check": "npm-run-all prettier:diff --parallel lint tsc",
"tsc": "tsc --noEmit", "tsc": "tsc --noEmit",
"start": "next start" "start": "next start",
"postinstall": "is-ci || (cd .. && husky install beta/.husky)"
}, },
"dependencies": { "dependencies": {
"@codesandbox/sandpack-react": "^0.1.20", "@codesandbox/sandpack-react": "^0.1.20",
@ -66,6 +67,8 @@
"fs-extra": "^9.0.1", "fs-extra": "^9.0.1",
"globby": "^11.0.1", "globby": "^11.0.1",
"gray-matter": "^4.0.2", "gray-matter": "^4.0.2",
"husky": "^7.0.4",
"is-ci": "^3.0.1",
"mdast-util-to-string": "^1.1.0", "mdast-util-to-string": "^1.1.0",
"npm-run-all": "^4.1.5", "npm-run-all": "^4.1.5",
"patch-package": "^6.2.2", "patch-package": "^6.2.2",

12
beta/src/pages/community/acknowledgements.md

@ -3,7 +3,7 @@ title: Acknowledgements
layout: Home layout: Home
--- ---
## React ## React {#react}
React was originally created by [Jordan Walke](https://github.com/jordwalke). Today, React has a [dedicated full-time team working on it](/community/team.html), as well as over a thousand [open source contributors](https://github.com/facebook/react/blob/main/AUTHORS). We'd like to recognize a few people who have made significant contributions to React and its documentation in the past and have helped maintain them over the years: React was originally created by [Jordan Walke](https://github.com/jordwalke). Today, React has a [dedicated full-time team working on it](/community/team.html), as well as over a thousand [open source contributors](https://github.com/facebook/react/blob/main/AUTHORS). We'd like to recognize a few people who have made significant contributions to React and its documentation in the past and have helped maintain them over the years:
@ -46,21 +46,21 @@ This list is not exhaustive.
We'd like to give special thanks to [Tom Occhino](https://github.com/tomocchino) and [Adam Wolff](https://github.com/wolffiex) for their guidance and support over the years. We are also thankful to all the volunteers who [translated React into other languages](https://translations.reactjs.org/). We'd like to give special thanks to [Tom Occhino](https://github.com/tomocchino) and [Adam Wolff](https://github.com/wolffiex) for their guidance and support over the years. We are also thankful to all the volunteers who [translated React into other languages](https://translations.reactjs.org/).
## React Docs ## React Docs {#react-docs}
### Documentation ### Documentation {#documentation}
* [Rachel Nabors](https://twitter.com/RachelNabors): editing, writing, illustrating * [Rachel Nabors](https://twitter.com/RachelNabors): editing, writing, illustrating
* [Dan Abramov](https://twitter.com/dan_abramov): writing, curriculum design * [Dan Abramov](https://twitter.com/dan_abramov): writing, curriculum design
* [Sylwia Vargas](https://twitter.com/SylwiaVargas): example code * [Sylwia Vargas](https://twitter.com/SylwiaVargas): example code
### Design ### Design {#design}
* [Dan Lebowitz](https://twitter.com/lebo): design * [Dan Lebowitz](https://twitter.com/lebo): design
* [Razvan Gradinar](https://dribbble.com/GradinarRazvan): design * [Razvan Gradinar](https://dribbble.com/GradinarRazvan): design
* [Maggie Appleton](https://maggieappleton.com/): diagram system * [Maggie Appleton](https://maggieappleton.com/): diagram system
### Development ### Development {#development}
* [Jared Palmer](https://twitter.com/jaredpalmer): site development * [Jared Palmer](https://twitter.com/jaredpalmer): site development
* [ThisDotLabs](https://www.thisdot.co/) ([Dane Grant](https://twitter.com/danecando), [Dustin Goodman](https://twitter.com/dustinsgoodman)): site development * [ThisDotLabs](https://www.thisdot.co/) ([Dane Grant](https://twitter.com/danecando), [Dustin Goodman](https://twitter.com/dustinsgoodman)): site development
@ -69,7 +69,7 @@ We'd like to give special thanks to [Tom Occhino](https://github.com/tomocchino)
We'd also like to thank countless alpha testers and community members who gave us feedback along the way. We'd also like to thank countless alpha testers and community members who gave us feedback along the way.
## Additional Thanks ## Additional Thanks {#additional-thanks}
Additionally, we're grateful to: Additionally, we're grateful to:

8
beta/src/pages/community/index.md

@ -9,11 +9,11 @@ React has a community of millions of developers. On this page we've listed some
</Intro> </Intro>
## Code of Conduct ## Code of Conduct {#code-of-conduct}
Before participating in React's communities, [please read our Code of Conduct](https://github.com/facebook/react/blob/main/CODE_OF_CONDUCT.md). We have adopted the [Contributor Covenant](https://www.contributor-covenant.org/) and we expect that all community members adhere to the guidelines within. Before participating in React's communities, [please read our Code of Conduct](https://github.com/facebook/react/blob/main/CODE_OF_CONDUCT.md). We have adopted the [Contributor Covenant](https://www.contributor-covenant.org/) and we expect that all community members adhere to the guidelines within.
## Stack Overflow ## Stack Overflow {#stack-overflow}
Stack Overflow is a popular forum to ask code-level questions or if you're stuck with a specific error. Read through the [existing questions](https://stackoverflow.com/questions/tagged/reactjs) tagged with **reactjs** or [ask your own](https://stackoverflow.com/questions/ask?tags=reactjs)! Stack Overflow is a popular forum to ask code-level questions or if you're stuck with a specific error. Read through the [existing questions](https://stackoverflow.com/questions/tagged/reactjs) tagged with **reactjs** or [ask your own](https://stackoverflow.com/questions/ask?tags=reactjs)!
@ -21,7 +21,7 @@ Stack Overflow is a popular forum to ask code-level questions or if you're stuck
TODO: decide on the criteria for inclusion before uncommenting. TODO: decide on the criteria for inclusion before uncommenting.
## Popular Discussion Forums ## Popular Discussion Forums {#popular-discussion-forums}
There are many online forums which are a great place for discussion about best practices and application architecture as well as the future of React. If you have an answerable code-level question, Stack Overflow is usually a better fit. There are many online forums which are a great place for discussion about best practices and application architecture as well as the future of React. If you have an answerable code-level question, Stack Overflow is usually a better fit.
@ -34,6 +34,6 @@ Each community consists of many thousands of React users.
--> -->
## News ## News {#news}
For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs) and the [official React blog](/blog/) on this website. For the latest news about React, [follow **@reactjs** on Twitter](https://twitter.com/reactjs) and the [official React blog](/blog/) on this website.

22
beta/src/pages/community/meet-the-team.md

@ -8,13 +8,13 @@ React development is led by a small dedicated team working full time at Facebook
</Intro> </Intro>
## React Core ## React Core {#react-core}
The React Core team members work full time on the core component APIs, the engine that powers React DOM and React Native, React DevTools, and the React documentation website. The React Core team members work full time on the core component APIs, the engine that powers React DOM and React Native, React DevTools, and the React documentation website.
Current members of the React team are listed in alphabetical order below. Current members of the React team are listed in alphabetical order below.
### Andrew Clark ### Andrew Clark {#andrew-clark}
![Andrew Clark](../images/team/acdlite.jpg) ![Andrew Clark](../images/team/acdlite.jpg)
@ -22,7 +22,7 @@ Current members of the React team are listed in alphabetical order below.
Andrew got started with web development by making sites with WordPress, and eventually tricked himself into doing JavaScript. His favorite pastime is karaoke. Andrew is either a Disney villain or a Disney princess, depending on the day. Andrew got started with web development by making sites with WordPress, and eventually tricked himself into doing JavaScript. His favorite pastime is karaoke. Andrew is either a Disney villain or a Disney princess, depending on the day.
### Brian Vaughn ### Brian Vaughn {#brian-vaughn}
![Brian Vaughn](../images/team/bvaughn.jpg) ![Brian Vaughn](../images/team/bvaughn.jpg)
@ -30,7 +30,7 @@ Andrew got started with web development by making sites with WordPress, and even
Brian studied art in college and did programming on the side to pay for his education. Eventually, he realized that he enjoys working on open source. Brian has one [one-person band](https://soundcloud.com/brianvaughn/) and two [two-person](https://soundcloud.com/pilotlessdrone) [bands](https://soundcloud.com/pinwurm). He also takes care of the cutest cat in the world. Brian studied art in college and did programming on the side to pay for his education. Eventually, he realized that he enjoys working on open source. Brian has one [one-person band](https://soundcloud.com/brianvaughn/) and two [two-person](https://soundcloud.com/pilotlessdrone) [bands](https://soundcloud.com/pinwurm). He also takes care of the cutest cat in the world.
### Dan Abramov ### Dan Abramov {#dan-abramov}
![Dan Abramov](../images/team/gaearon.jpg) ![Dan Abramov](../images/team/gaearon.jpg)
@ -38,7 +38,7 @@ Brian studied art in college and did programming on the side to pay for his educ
Dan got into programming after he accidentally discovered Visual Basic inside Microsoft PowerPoint. He has found his true calling in turning [Sebastian](#sebastian-markbåge)'s tweets into long-form blog posts. Dan occasionally wins at Fortnite by hiding in a bush until the game ends. Dan got into programming after he accidentally discovered Visual Basic inside Microsoft PowerPoint. He has found his true calling in turning [Sebastian](#sebastian-markbåge)'s tweets into long-form blog posts. Dan occasionally wins at Fortnite by hiding in a bush until the game ends.
### Luna Ruan ### Luna Ruan {#luna-ruan}
![Luna](../images/team/lunaruan.jpg) ![Luna](../images/team/lunaruan.jpg)
@ -46,7 +46,7 @@ Dan got into programming after he accidentally discovered Visual Basic inside Mi
Luna learned programming because she thought it meant creating video games. Instead, she ended up working on the Pinterest web app, and now on React itself. Luna doesn't want to make video games anymore, but she plans to do creative writing if she ever gets bored. Luna learned programming because she thought it meant creating video games. Instead, she ended up working on the Pinterest web app, and now on React itself. Luna doesn't want to make video games anymore, but she plans to do creative writing if she ever gets bored.
### Marco Salazar ### Marco Salazar {#marco-salazar}
![Marco](../images/team/salazarm.jpeg) ![Marco](../images/team/salazarm.jpeg)
@ -54,7 +54,7 @@ Luna learned programming because she thought it meant creating video games. Inst
Marco's first programming language was Assembly because he could use it to hack video games. Now online games are much more secure so he settles for playing fairly (mostly). In his spare time he plays games on his treadmill desk and makes art that he never finishes. Hopefully his PRs don't have the same fate. Marco's first programming language was Assembly because he could use it to hack video games. Now online games are much more secure so he settles for playing fairly (mostly). In his spare time he plays games on his treadmill desk and makes art that he never finishes. Hopefully his PRs don't have the same fate.
### Rachel Nabors ### Rachel Nabors {#rachel-nabors}
![Rachel](../images/team/rnabors.jpg) ![Rachel](../images/team/rnabors.jpg)
@ -62,7 +62,7 @@ Marco's first programming language was Assembly because he could use it to hack
Rachel wrote a [book about UI animation](https://abookapart.com/products/animation-at-work) once and worked with MDN and the W3C on the web animations API. Now she is busy with education materials and community engineering on the React team. Secretly, she is an award-winning cartoonist for teenage girls. Catch her making fancy tea with lukewarm water in the microkitchen. Rachel wrote a [book about UI animation](https://abookapart.com/products/animation-at-work) once and worked with MDN and the W3C on the web animations API. Now she is busy with education materials and community engineering on the React team. Secretly, she is an award-winning cartoonist for teenage girls. Catch her making fancy tea with lukewarm water in the microkitchen.
### Rick Hanlon ### Rick Hanlon {#rick-hanlon}
![Ricky](../images/team/rickhanlonii.jpg) ![Ricky](../images/team/rickhanlonii.jpg)
@ -70,7 +70,7 @@ Rachel wrote a [book about UI animation](https://abookapart.com/products/animati
Ricky majored in theoretical math and somehow found himself on the React Native team for a couple years before joining the React team. When he's not programming you can find him snowboarding, biking, climbing, golfing, or closing GitHub issues that do not match the issue template. Ricky majored in theoretical math and somehow found himself on the React Native team for a couple years before joining the React team. When he's not programming you can find him snowboarding, biking, climbing, golfing, or closing GitHub issues that do not match the issue template.
### Sebastian Markbåge ### Sebastian Markbåge {#sebastian-markbåge}
![Sebastian](../images/team/sebmarkbage.jpg) ![Sebastian](../images/team/sebmarkbage.jpg)
@ -78,7 +78,7 @@ Ricky majored in theoretical math and somehow found himself on the React Native
Sebastian majored in psychology. He's usually quiet. Even when he says something, it often doesn't make sense to the rest of us until a few months later. The correct way to pronounce his surname is "mark-boa-geh" but he settled for "mark-beige" out of pragmatism -- and that's how he approaches React. Sebastian majored in psychology. He's usually quiet. Even when he says something, it often doesn't make sense to the rest of us until a few months later. The correct way to pronounce his surname is "mark-boa-geh" but he settled for "mark-beige" out of pragmatism -- and that's how he approaches React.
### Seth Webster ### Seth Webster {#seth-webster}
![Seth](../images/team/sethwebster.jpg) ![Seth](../images/team/sethwebster.jpg)
@ -86,7 +86,7 @@ Sebastian majored in psychology. He's usually quiet. Even when he says something
Seth started programming as a kid growing up in Tucson, AZ. After school, he was bitten by the music bug and was a touring musician for about 10 years before returning to *work*, starting with Intuit. In his spare time, he loves [taking pictures](https://www.sethwebster.com) and flying for animal rescues in the northeastern United States. Seth started programming as a kid growing up in Tucson, AZ. After school, he was bitten by the music bug and was a touring musician for about 10 years before returning to *work*, starting with Intuit. In his spare time, he loves [taking pictures](https://www.sethwebster.com) and flying for animal rescues in the northeastern United States.
## Past contributors ## Past contributors {#past-contributors}
You can find the past team members and other people who significantly contributed to React over the years on the [acknowledgements](/community/acknowledgements) page. You can find the past team members and other people who significantly contributed to React over the years on the [acknowledgements](/community/acknowledgements) page.

10
beta/src/pages/index.md

@ -7,7 +7,7 @@ permalink: index.html
<HomepageHero /> <HomepageHero />
## What is this site? ## What is this site? {#what-is-this-site}
We are rewriting the React documentation with a few differences: We are rewriting the React documentation with a few differences:
@ -17,21 +17,21 @@ We are rewriting the React documentation with a few differences:
This beta website contains the current draft of the new docs. This beta website contains the current draft of the new docs.
## This is a work in progress! ## This is a work in progress! {#this-is-a-work-in-progress}
This is a **beta website**. There will be bugs, performance issues, and missing content. This is a **beta website**. There will be bugs, performance issues, and missing content.
## How much content is ready? ## How much content is ready? {#how-much-content-is-ready}
* [Learn React](/learn): ~70% finished. * [Learn React](/learn): ~70% finished.
* [API Reference](/reference): ~5% finished. * [API Reference](/reference): ~5% finished.
You can track our progress [on GitHub](https://github.com/reactjs/reactjs.org/issues/3308). You can track our progress [on GitHub](https://github.com/reactjs/reactjs.org/issues/3308).
## How can I provide feedback? ## How can I provide feedback? {#how-can-i-provide-feedback}
Please use [this GitHub issue](https://github.com/reactjs/reactjs.org/issues/3308) or [this anonymous form](https://www.surveymonkey.co.uk/r/Y6GH986) for high-level feedback. Additionally, each page has a Feedback button in the corner. If you spot something that doesn't make sense, please tell us! Please use [this GitHub issue](https://github.com/reactjs/reactjs.org/issues/3308) or [this anonymous form](https://www.surveymonkey.co.uk/r/Y6GH986) for high-level feedback. Additionally, each page has a Feedback button in the corner. If you spot something that doesn't make sense, please tell us!
## Will this site replace the main site? ## Will this site replace the main site? {#will-this-site-replace-the-main-site}
We aim to switch this site to be the main one once we reach content parity with the [existing React documentation](https://reactjs.org/). The old React website will be archived at a subdomain so you'll still be able to access it. Old content links will redirect to the archived subdomain, which will have a notice about outdated content. We aim to switch this site to be the main one once we reach content parity with the [existing React documentation](https://reactjs.org/). The old React website will be archived at a subdomain so you'll still be able to access it. Old content links will redirect to the archived subdomain, which will have a notice about outdated content.

22
beta/src/pages/learn/add-react-to-a-website.md

@ -9,11 +9,11 @@ React has been designed from the start for gradual adoption, and you can use as
</Intro> </Intro>
## Add React in one minute ## Add React in one minute {#add-react-in-one-minute}
You can add a React component to an existing HTML page in under a minute. Try this out with your own website or [an empty HTML file](https://gist.github.com/rachelnabors/7b33305bf33776354797a2e3c1445186/archive/859eac2f7079c9e1f0a6eb818a9684a464064d80.zip)—all you need is an internet connection and a text editor like Notepad (or VSCode—check out our guide on [how to set yours up](/learn/editor-setup/))! You can add a React component to an existing HTML page in under a minute. Try this out with your own website or [an empty HTML file](https://gist.github.com/rachelnabors/7b33305bf33776354797a2e3c1445186/archive/859eac2f7079c9e1f0a6eb818a9684a464064d80.zip)—all you need is an internet connection and a text editor like Notepad (or VSCode—check out our guide on [how to set yours up](/learn/editor-setup/))!
### Step 1: Add an element to the HTML ### Step 1: Add an element to the HTML {#step-1-add-an-element-to-the-html}
In the HTML page you want to edit, add an HTML element like an empty `<div>` tag with a unique `id` to mark the spot where you want to display something with React. In the HTML page you want to edit, add an HTML element like an empty `<div>` tag with a unique `id` to mark the spot where you want to display something with React.
@ -27,7 +27,7 @@ You can place a "container" element like this `<div>` anywhere inside the `<body
<!-- ... existing HTML ... --> <!-- ... existing HTML ... -->
``` ```
### Step 2: Add the Script Tags ### Step 2: Add the Script Tags {#step-2-add-the-script-tags}
In the HTML page, right before the closing `</body>` tag, add three `<script>` tags for the following files: In the HTML page, right before the closing `</body>` tag, add three `<script>` tags for the following files:
@ -49,7 +49,7 @@ When deploying, replace "development.js" with "production.min.js".
</body> </body>
``` ```
### Step 3: Create a React component ### Step 3: Create a React component {#step-3-create-a-react-component}
Create a file called **like_button.js** next to your HTML page, add this code snippet, and save the file. This code defines a React component called `LikeButton`. [You can learn more about making components in our guides.](/learn/your-first-component) Create a file called **like_button.js** next to your HTML page, add this code snippet, and save the file. This code defines a React component called `LikeButton`. [You can learn more about making components in our guides.](/learn/your-first-component)
@ -73,7 +73,7 @@ function LikeButton() {
} }
``` ```
### Step 4: Add your React Component to the page ### Step 4: Add your React Component to the page {#step-4-add-your-react-component-to-the-page}
Lastly, add two lines to the bottom of **like_button.js**. These two lines of code find the `<div>` you added to your HTML in the first step and then display the "Like" button React component inside of it. Lastly, add two lines to the bottom of **like_button.js**. These two lines of code find the `<div>` you added to your HTML in the first step and then display the "Like" button React component inside of it.
@ -87,7 +87,7 @@ ReactDOM.render(React.createElement(LikeButton), domContainer);
- [View the full example source code](https://gist.github.com/rachelnabors/c64b3aeace8a191cf5ea6fb5202e66c9) - [View the full example source code](https://gist.github.com/rachelnabors/c64b3aeace8a191cf5ea6fb5202e66c9)
- [Download the full example (2KB zipped)](https://gist.github.com/rachelnabors/c64b3aeace8a191cf5ea6fb5202e66c9/archive/7b41a88cb1027c9b5d8c6aff5212ecd3d0493504.zip) - [Download the full example (2KB zipped)](https://gist.github.com/rachelnabors/c64b3aeace8a191cf5ea6fb5202e66c9/archive/7b41a88cb1027c9b5d8c6aff5212ecd3d0493504.zip)
#### You can reuse components! #### You can reuse components! {#you-can-reuse-components}
You might want to display a React component in multiple places on the same HTML page. This is most useful while React-powered parts of the page are isolated from each other. You can do this by calling `ReactDOM.render()` multiple times with multiple container elements. You might want to display a React component in multiple places on the same HTML page. This is most useful while React-powered parts of the page are isolated from each other. You can do this by calling `ReactDOM.render()` multiple times with multiple container elements.
@ -108,7 +108,7 @@ ReactDOM.render(
Check out [an example that displays the "Like" button three times and passes some data to it](https://gist.github.com/rachelnabors/c0ea05cc33fbe75ad9bbf78e9044d7f8)! Check out [an example that displays the "Like" button three times and passes some data to it](https://gist.github.com/rachelnabors/c0ea05cc33fbe75ad9bbf78e9044d7f8)!
### Step 5: Minify JavaScript for production ### Step 5: Minify JavaScript for production {#step-5-minify-javascript-for-production}
Unminified JavaScript can significantly slow down page load times for your users. Before deploying your website to production, it's a good idea to minify its scripts. Unminified JavaScript can significantly slow down page load times for your users. Before deploying your website to production, it's a good idea to minify its scripts.
@ -120,7 +120,7 @@ Unminified JavaScript can significantly slow down page load times for your users
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script> <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
``` ```
## Try React with JSX ## Try React with JSX {#try-react-with-jsx}
The examples above rely on features that are natively supported by browsers. This is why **like_button.js** uses a JavaScript function call to tell React what to display: The examples above rely on features that are natively supported by browsers. This is why **like_button.js** uses a JavaScript function call to tell React what to display:
@ -138,7 +138,7 @@ These two code snippets are equivalent. JSX is popular syntax for describing mar
> You can play with transforming HTML markup into JSX using [this online converter](https://babeljs.io/en/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=DwIwrgLhD2B2AEcDCAbAlgYwNYF4DeAFAJTw4B88EAFmgM4B0tAphAMoQCGETBe86WJgBMAXJQBOYJvAC-RGWQBQ8FfAAyaQYuAB6cFDhkgA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.4.3). > You can play with transforming HTML markup into JSX using [this online converter](https://babeljs.io/en/repl#?babili=false&browsers=&build=&builtIns=false&spec=false&loose=false&code_lz=DwIwrgLhD2B2AEcDCAbAlgYwNYF4DeAFAJTw4B88EAFmgM4B0tAphAMoQCGETBe86WJgBMAXJQBOYJvAC-RGWQBQ8FfAAyaQYuAB6cFDhkgA&debug=false&forceAllTransforms=false&shippedProposals=false&circleciRepo=&evaluate=false&fileSize=false&timeTravel=false&sourceType=module&lineWrap=true&presets=es2015%2Creact%2Cstage-2&prettier=false&targets=&version=7.4.3).
### Try JSX ### Try JSX {#try-jsx}
The quickest way to try JSX in your project is to add the Babel compiler to your page's `<head>` along with React and ReactDOM like so: The quickest way to try JSX in your project is to add the Babel compiler to your page's `<head>` along with React and ReactDOM like so:
@ -193,7 +193,7 @@ Here is [an example HTML file with JSX](https://raw.githubusercontent.com/reactj
This approach is fine for learning and creating simple demos. However, it makes your website slow and **isn't suitable for production**. When you're ready to move forward, remove this new `<script>` tag and the `type="text/babel"` attributes you've added. Instead, in the next section you will set up a JSX preprocessor to convert all your `<script>` tags automatically. This approach is fine for learning and creating simple demos. However, it makes your website slow and **isn't suitable for production**. When you're ready to move forward, remove this new `<script>` tag and the `type="text/babel"` attributes you've added. Instead, in the next section you will set up a JSX preprocessor to convert all your `<script>` tags automatically.
### Add JSX to a project ### Add JSX to a project {#add-jsx-to-a-project}
Adding JSX to a project doesn't require complicated tools like a [bundler](/learn/start-a-new-react-project#custom-toolchains) or a development server. Adding a JSX preprocessor is a lot like adding a CSS preprocessor. Adding JSX to a project doesn't require complicated tools like a [bundler](/learn/start-a-new-react-project#custom-toolchains) or a development server. Adding a JSX preprocessor is a lot like adding a CSS preprocessor.
@ -206,7 +206,7 @@ You only need npm to install the JSX preprocessor. You won't need it for anythin
Congratulations! You just added a **production-ready JSX setup** to your project. Congratulations! You just added a **production-ready JSX setup** to your project.
### Run the JSX Preprocessor ### Run the JSX Preprocessor {#run-the-jsx-preprocessor}
You can preprocess JSX so that every time you save a file with JSX in it, the transform will be re-run, converting the JSX file into a new, plain JavaScript file. You can preprocess JSX so that every time you save a file with JSX in it, the transform will be re-run, converting the JSX file into a new, plain JavaScript file.

16
beta/src/pages/learn/adding-interactivity.md

@ -21,7 +21,7 @@ Some things on the screen update in response to user input. For example, clickin
</YouWillLearn> </YouWillLearn>
## Responding to events ## Responding to events {#responding-to-events}
React lets you add event handlers to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on. React lets you add event handlers to your JSX. Event handlers are your own functions that will be triggered in response to user interactions like clicking, hovering, focusing on form inputs, and so on.
@ -73,7 +73,7 @@ Read **[Responding to Events](/learn/responding-to-events)** to learn how to add
</LearnMore> </LearnMore>
## State: a component's memory ## State: a component's memory {#state-a-components-memory}
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called state. Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" puts a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called state.
@ -229,7 +229,7 @@ Read **[State: A Component's Memory](/learn/state-a-components-memory)** to lear
</LearnMore> </LearnMore>
## Render and commit ## Render and commit {#render-and-commit}
Before your components are displayed on the screen, they must be rendered by React. Understanding the steps in this process will help you think about how your code executes and explain its behavior. Before your components are displayed on the screen, they must be rendered by React. Understanding the steps in this process will help you think about how your code executes and explain its behavior.
@ -251,7 +251,7 @@ Read **[Render and Commit](/learn/render-and-commit)** to learn the lifecycle of
</LearnMore> </LearnMore>
## State as a snapshot ## State as a snapshot {#state-as-a-snapshot}
Unlike regular JavaScript variables, React state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render. This can be surprising at first! Unlike regular JavaScript variables, React state behaves more like a snapshot. Setting it does not change the state variable you already have, but instead triggers a re-render. This can be surprising at first!
@ -314,7 +314,7 @@ Read **[State as a Snapshot](/learn/state-as-a-snapshot)** to learn why state ap
</LearnMore> </LearnMore>
## Queueing a series of state changes ## Queueing a series of state changes {#queueing-a-series-of-state-changes}
This component is buggy: clicking "+3" increments the score only once. This component is buggy: clicking "+3" increments the score only once.
@ -402,7 +402,7 @@ Read **[Queueing a Series of State Changes](/learn/queueing-a-series-of-state-ch
</LearnMore> </LearnMore>
## Updating objects in state ## Updating objects in state {#updating-objects-in-state}
State can hold any kind of JavaScript value, including objects. But you shouldn't change objects and arrays that you hold in the React state directly. Instead, when you want to update an object and array, you need to create a new one (or make a copy of an existing one), and then update the state to use that copy. State can hold any kind of JavaScript value, including objects. But you shouldn't change objects and arrays that you hold in the React state directly. Instead, when you want to update an object and array, you need to create a new one (or make a copy of an existing one), and then update the state to use that copy.
@ -633,7 +633,7 @@ Read **[Updating Objects in State](/learn/updating-objects-in-state)** to learn
</LearnMore> </LearnMore>
## Updating arrays in state ## Updating arrays in state {#updating-arrays-in-state}
Arrays are another type of mutable JavaScript objects you can store in state and should treat as read-only. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array: Arrays are another type of mutable JavaScript objects you can store in state and should treat as read-only. Just like with objects, when you want to update an array stored in state, you need to create a new one (or make a copy of an existing one), and then set state to use the new array:
@ -793,7 +793,7 @@ Read **[Updating Arrays in State](/learn/updating-arrays-in-state)** to learn ho
</LearnMore> </LearnMore>
## What's next? ## What's next? {#whats-next}
Head over to [Responding to Events](/learn/responding-to-events) to start reading this chapter page by page! Head over to [Responding to Events](/learn/responding-to-events) to start reading this chapter page by page!

20
beta/src/pages/learn/choosing-the-state-structure.md

@ -17,7 +17,7 @@ Structuring state well can make a difference between a component that is pleasan
</YouWillLearn> </YouWillLearn>
## Principles for structuring state ## Principles for structuring state {#principles-for-structuring-state}
When you write a component that holds some state, you'll have to make choices about how many state variables to use and what the shape of their data should be. While it's possible to write correct programs even with a suboptimal state structure, there are a few principles that can guide you to make better choices: When you write a component that holds some state, you'll have to make choices about how many state variables to use and what the shape of their data should be. While it's possible to write correct programs even with a suboptimal state structure, there are a few principles that can guide you to make better choices:
@ -31,7 +31,7 @@ The goal behind these principles is to *make state easy to update without introd
Now let's see how these principles apply in action. Now let's see how these principles apply in action.
## Group related state ## Group related state {#group-related-state}
You might sometimes be unsure between using a single or multiple state variables. You might sometimes be unsure between using a single or multiple state variables.
@ -101,7 +101,7 @@ If your state variable is an object, remember that [you can't update only one fi
</Gotcha> </Gotcha>
## Avoid contradictions in state ## Avoid contradictions in state {#avoid-contradictions-in-state}
Here is a hotel feedback form with `isSending` and `isSent` state variables: Here is a hotel feedback form with `isSending` and `isSent` state variables:
@ -223,7 +223,7 @@ const isSent = status === 'sent';
But they're not state variables, so you don't need to worry about them getting out of sync with each other. But they're not state variables, so you don't need to worry about them getting out of sync with each other.
## Avoid redundant state ## Avoid redundant state {#avoid-redundant-state}
If you can calculate some information from the component's props or its existing state variables during rendering, you **should not** put that information into that component's state. If you can calculate some information from the component's props or its existing state variables during rendering, you **should not** put that information into that component's state.
@ -373,7 +373,7 @@ function Message({ initialColor }) {
</DeepDive> </DeepDive>
## Avoid duplication in state ## Avoid duplication in state {#avoid-duplication-in-state}
This menu list component lets you choose a single travel snack out of several: This menu list component lets you choose a single travel snack out of several:
@ -568,7 +568,7 @@ The duplication is gone, and you only keep the essential state!
Now if you edit the *selected* item, the message below will update immediately. This is because `setItems` triggers a re-render, and `items.find(...)` would find the item with the updated title. You didn't need to hold *the selected item* in state, because only the *selected ID* is essential. The rest could be calculated during render. Now if you edit the *selected* item, the message below will update immediately. This is because `setItems` triggers a re-render, and `items.find(...)` would find the item with the updated title. You didn't need to hold *the selected item* in state, because only the *selected ID* is essential. The rest could be calculated during render.
## Avoid deeply nested state ## Avoid deeply nested state {#avoid-deeply-nested-state}
Imagine a travel plan consisting of planets, continents, and countries. You might be tempted to structure its state using nested objects and arrays, like in this example: Imagine a travel plan consisting of planets, continents, and countries. You might be tempted to structure its state using nested objects and arrays, like in this example:
@ -1854,7 +1854,7 @@ Sometimes, you can also reduce state nesting by moving some of the nested state
<Challenges> <Challenges>
### Fix a component that's not updating ### Fix a component that's not updating {#fix-a-component-thats-not-updating}
This `Clock` component receives two props: `color` and `time`. When you select a different color in the select box, the `Clock` component receives a different `color` prop from its parent component. However, for some reason, the displayed color doesn't update. Why? Fix the problem. This `Clock` component receives two props: `color` and `time`. When you select a different color in the select box, the `Clock` component receives a different `color` prop from its parent component. However, for some reason, the displayed color doesn't update. Why? Fix the problem.
@ -2017,7 +2017,7 @@ export default function App() {
</Solution> </Solution>
### Fix a broken packing list ### Fix a broken packing list {#fix-a-broken-packing-list}
This packing list has a footer that shows how many items are packed, and how many items there are overall. It seems to work at first, but it is buggy. For example, if you mark a place as completed and then delete it, the counter will not be updated correctly. Fix the counter so that it's always correct. This packing list has a footer that shows how many items are packed, and how many items there are overall. It seems to work at first, but it is buggy. For example, if you mark a place as completed and then delete it, the counter will not be updated correctly. Fix the counter so that it's always correct.
@ -2303,7 +2303,7 @@ Notice how the event handlers are only concerned with calling `setItems` after t
</Solution> </Solution>
### Fix the disappearing selection ### Fix the disappearing selection {#fix-the-disappearing-selection}
There is a list of `letters` in state. When you hover or focus a particular letter, it gets highlighted. The currently highlighted letter is stored in the `highlightedLetter` state variable. You can "star" and "unstar" invidual letters, which updates the `letters` array in state. There is a list of `letters` in state. When you hover or focus a particular letter, it gets highlighted. The currently highlighted letter is stored in the `highlightedLetter` state variable. You can "star" and "unstar" invidual letters, which updates the `letters` array in state.
@ -2523,7 +2523,7 @@ li { border-radius: 5px; }
</Solution> </Solution>
### Implement multiple selection ### Implement multiple selection {#implement-multiple-selection}
In this example, each `Letter` has an `isSelected` prop and an `onToggle` handler that marks it as selected. This works, but the state is stored as a `selectedId` (either `null` or an ID), so only one letter can get selected at any given time. In this example, each `Letter` has an `isSelected` prop and an `onToggle` handler that marks it as selected. This works, but the state is stored as a `selectedId` (either `null` or an ID), so only one letter can get selected at any given time.

18
beta/src/pages/learn/conditional-rendering.md

@ -17,7 +17,7 @@ Your components will often need to display different things depending on differe
</YouWillLearn> </YouWillLearn>
## Conditionally returning JSX ## Conditionally returning JSX {#conditionally-returning-jsx}
Let’s say you have a `PackingList` component rendering several `Item`s, which can be marked as packed or not: Let’s say you have a `PackingList` component rendering several `Item`s, which can be marked as packed or not:
@ -105,7 +105,7 @@ Try editing what gets returned in either case, and see how the result changes!
Notice how you're creating branching logic with JavaScript's `if` and `return` statements. In React, control flow (like conditions) is handled by JavaScript. Notice how you're creating branching logic with JavaScript's `if` and `return` statements. In React, control flow (like conditions) is handled by JavaScript.
### Conditionally returning nothing with `null` ### Conditionally returning nothing with `null` {#conditionally-returning-nothing-with-null}
In some situations, you won't want to render anything at all. For example, say you don't want to show packed items at all. A component must return something. In this case, you can return `null`: In some situations, you won't want to render anything at all. For example, say you don't want to show packed items at all. A component must return something. In this case, you can return `null`:
@ -155,7 +155,7 @@ export default function PackingList() {
In practice, returning `null` from a component isn't common because it might surprise a developer trying to render it. More often, you would conditionally include or exclude the component in the parent component's JSX. Here's how to do that! In practice, returning `null` from a component isn't common because it might surprise a developer trying to render it. More often, you would conditionally include or exclude the component in the parent component's JSX. Here's how to do that!
## Conditionally including JSX ## Conditionally including JSX {#conditionally-including-jsx}
In the previous example, you controlled which (if any!) JSX tree would be returned by the component. You may already have noticed some duplication in the render output: In the previous example, you controlled which (if any!) JSX tree would be returned by the component. You may already have noticed some duplication in the render output:
@ -180,7 +180,7 @@ return <li className="item">{name}</li>;
While this duplication isn't harmful, it could make your code harder to maintain. What if you want to change the `className`? You'd have to do it in two places in your code! In such a situation, you could conditionally include a little JSX to make your code more [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself). While this duplication isn't harmful, it could make your code harder to maintain. What if you want to change the `className`? You'd have to do it in two places in your code! In such a situation, you could conditionally include a little JSX to make your code more [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself).
### Conditional (ternary) operator (`? :`) ### Conditional (ternary) operator (`? :`) {#conditional-ternary-operator--}
JavaScript has a compact syntax for writing a conditional expression -- the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) or "ternary operator." JavaScript has a compact syntax for writing a conditional expression -- the [conditional operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) or "ternary operator."
@ -257,7 +257,7 @@ export default function PackingList() {
This style works well for simple conditions, but use it in moderation. If your components get messy with too much nested conditional markup, consider extracting child components to clean things up. In React, markup is a part of your code, so you can use tools like variables and functions to tidy up complex expressions. This style works well for simple conditions, but use it in moderation. If your components get messy with too much nested conditional markup, consider extracting child components to clean things up. In React, markup is a part of your code, so you can use tools like variables and functions to tidy up complex expressions.
### Logical AND operator (`&&`) ### Logical AND operator (`&&`) {#logical-and-operator-}
Another common shortcut you'll encounter is the [JavaScript logical AND (`&&`) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20(%20%26%26%20)%20operator,it%20returns%20a%20Boolean%20value.). Inside React components, it often comes up when you want to render some JSX when the condition is true, **or render nothing otherwise.** With `&&`, you could conditionally render the checkmark only if `isPacked` is `true`: Another common shortcut you'll encounter is the [JavaScript logical AND (`&&`) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#:~:text=The%20logical%20AND%20(%20%26%26%20)%20operator,it%20returns%20a%20Boolean%20value.). Inside React components, it often comes up when you want to render some JSX when the condition is true, **or render nothing otherwise.** With `&&`, you could conditionally render the checkmark only if `isPacked` is `true`:
@ -324,7 +324,7 @@ To fix it, make the left side a boolean: `messageCount > 0 && <p>New messages</p
</Gotcha> </Gotcha>
### Conditionally assigning JSX to a variable ### Conditionally assigning JSX to a variable {#conditionally-assigning-jsx-to-a-variable}
When the shortcuts get in the way of writing plain code, try using an `if` statement and a variable. You can reassign variables defined with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), so start by providing the default content you want to display, the name: When the shortcuts get in the way of writing plain code, try using an `if` statement and a variable. You can reassign variables defined with [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let), so start by providing the default content you want to display, the name:
@ -453,7 +453,7 @@ If you're not familiar with JavaScript, this variety of styles might seem overwh
<Challenges> <Challenges>
### Show an icon for incomplete items with `? :` ### Show an icon for incomplete items with `? :` {#show-an-icon-for-incomplete-items-with--}
Use the conditional operator (`cond ? a : b`) to render a ❌ if `isPacked` isn’t `true`. Use the conditional operator (`cond ? a : b`) to render a ❌ if `isPacked` isn’t `true`.
@ -533,7 +533,7 @@ export default function PackingList() {
</Solution> </Solution>
### Show the item importance with `&&` ### Show the item importance with `&&` {#show-the-item-importance-with-}
In this example, each `Item` receives a numerical `importance` prop. Use the `&&` operator to render "_(Importance: X)_" in italics, but only for items that have non-zero difficulty. Your item list should end up looking like this: In this example, each `Item` receives a numerical `importance` prop. Use the `&&` operator to render "_(Importance: X)_" in italics, but only for items that have non-zero difficulty. Your item list should end up looking like this:
@ -629,7 +629,7 @@ In this solution, two separate conditions are used to insert a space between the
</Solution> </Solution>
### Refactor a series of `? :` to `if` and variables ### Refactor a series of `? :` to `if` and variables {#refactor-a-series-of---to-if-and-variables}
This `Drink` component uses a series of `? :` conditions to show different information depending on whether the `name` prop is `"tea"` or `"coffee"`. The problem is that the information about each drink is spread across multiple conditions. Refactor this code to use a single `if` statement instead of three `? :` conditions. This `Drink` component uses a series of `? :` conditions to show different information depending on whether the `name` prop is `"tea"` or `"coffee"`. The problem is that the information about each drink is spread across multiple conditions. Refactor this code to use a single `if` statement instead of three `? :` conditions.

18
beta/src/pages/learn/describing-the-ui.md

@ -22,7 +22,7 @@ React is a JavaScript library for rendering user interfaces (UI). UI is built fr
</YouWillLearn> </YouWillLearn>
## Your first component ## Your first component {#your-first-component}
React applications are built from isolated pieces of UI called "components". A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a `Gallery` component rendering three `Profile` components: React applications are built from isolated pieces of UI called "components". A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here is a `Gallery` component rendering three `Profile` components:
@ -62,7 +62,7 @@ Read **[Your First Component](/learn/your-first-component)** to learn how to dec
</LearnMore> </LearnMore>
## Importing and exporting components ## Importing and exporting components {#importing-and-exporting-components}
You can declare many components in one file, but large files can get difficult to navigate. To solve this, you can *export* a component into its own file, and then *import* that component from another file: You can declare many components in one file, but large files can get difficult to navigate. To solve this, you can *export* a component into its own file, and then *import* that component from another file:
@ -117,7 +117,7 @@ Read **[Importing and Exporting Components](/learn/importing-and-exporting-compo
</LearnMore> </LearnMore>
## Writing markup with JSX ## Writing markup with JSX {#writing-markup-with-jsx}
Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information. Each React component is a JavaScript function that may contain some markup that React renders into the browser. React components use a syntax extension called JSX to represent that markup. JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information.
@ -186,7 +186,7 @@ Read **[Writing Markup with JSX](/learn/writing-markup-with-jsx)** to learn how
</LearnMore> </LearnMore>
## JavaScript in JSX with curly braces ## JavaScript in JSX with curly braces {#javascript-in-jsx-with-curly-braces}
JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to "open a window" to JavaScript: JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place. Sometimes you will want to add a little JavaScript logic or reference a dynamic property inside that markup. In this situation, you can use curly braces in your JSX to "open a window" to JavaScript:
@ -234,7 +234,7 @@ Read **[JavaScript in JSX with Curly Braces](/learn/javascript-in-jsx-with-curly
</LearnMore> </LearnMore>
## Passing props to a component ## Passing props to a component {#passing-props-to-a-component}
React components use *props* to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, functions, and even JSX! React components use *props* to communicate with each other. Every parent component can pass some information to its child components by giving them props. Props might remind you of HTML attributes, but you can pass any JavaScript value through them, including objects, arrays, functions, and even JSX!
@ -315,7 +315,7 @@ Read **[Passing Props to a Component](/learn/passing-props-to-a-component)** to
</LearnMore> </LearnMore>
## Conditional rendering ## Conditional rendering {#conditional-rendering}
Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like `if` statements, `&&`, and `? :` operators. Your components will often need to display different things depending on different conditions. In React, you can conditionally render JSX using JavaScript syntax like `if` statements, `&&`, and `? :` operators.
@ -363,7 +363,7 @@ Read **[Conditional Rendering](/learn/conditional-rendering)** to learn the diff
</LearnMore> </LearnMore>
## Rendering lists ## Rendering lists {#rendering-lists}
You will often want to display multiple similar components from a collection of data. You can use JavaScript's `filter()` and `map()` with React to filter and transform your array of data into an array of components. You will often want to display multiple similar components from a collection of data. You can use JavaScript's `filter()` and `map()` with React to filter and transform your array of data into an array of components.
@ -463,7 +463,7 @@ Read **[Rendering Lists](/learn/rendering-lists)** to learn how to render a list
</LearnMore> </LearnMore>
## Keeping components pure ## Keeping components pure {#keeping-components-pure}
Some JavaScript functions are “pure.” A pure function: Some JavaScript functions are “pure.” A pure function:
@ -524,7 +524,7 @@ Read **[Keeping Components Pure](/learn/keeping-components-pure)** to learn how
</LearnMore> </LearnMore>
## What's next? ## What's next? {#whats-next}
Head over to [Your First Component](/learn/your-first-component) to start reading this chapter page by page! Head over to [Your First Component](/learn/your-first-component) to start reading this chapter page by page!

10
beta/src/pages/learn/editor-setup.md

@ -9,7 +9,7 @@ A properly configured editor can make code clearer to read and faster to write.
</Intro> </Intro>
## Your editor ## Your editor {#your-editor}
[VS Code](https://code.visualstudio.com/) is one of the most popular editors in use today. It has a large marketplace of extensions and integrates well with popular services like GitHub. Most of the features listed below can be added to VS Code as extensions as well, making it highly configurable! [VS Code](https://code.visualstudio.com/) is one of the most popular editors in use today. It has a large marketplace of extensions and integrates well with popular services like GitHub. Most of the features listed below can be added to VS Code as extensions as well, making it highly configurable!
@ -19,18 +19,18 @@ Other popular text editors used in the React community include:
* [Sublime Text](https://www.sublimetext.com/)—has support for JSX and TypeScript, syntax highlighting and autocomplete built in. * [Sublime Text](https://www.sublimetext.com/)—has support for JSX and TypeScript, syntax highlighting and autocomplete built in.
* [Vim](https://www.vim.org/)—a highly configurable text editor built to make creating and changing any kind of text very efficient. It is included as "vi" with most UNIX systems and with Apple OS X. * [Vim](https://www.vim.org/)—a highly configurable text editor built to make creating and changing any kind of text very efficient. It is included as "vi" with most UNIX systems and with Apple OS X.
## Recommended text editor features ## Recommended text editor features {#recommended-text-editor-features}
Some editors come with these features built in, but others might require adding an extension. Check to see what support your editor of choice provides to be sure! Some editors come with these features built in, but others might require adding an extension. Check to see what support your editor of choice provides to be sure!
### Linting ### Linting {#linting}
Code linters find problems in your code as you write, helping you fix them early. [ESLint](https://eslint.org/) is a popular, open source linter for JavaScript. Code linters find problems in your code as you write, helping you fix them early. [ESLint](https://eslint.org/) is a popular, open source linter for JavaScript.
* [Install ESLint with the recommended configuration for React](https://www.npmjs.com/package/eslint-config-react-app) (be sure you have [Node installed!](https://nodejs.org/en/download/current/)) * [Install ESLint with the recommended configuration for React](https://www.npmjs.com/package/eslint-config-react-app) (be sure you have [Node installed!](https://nodejs.org/en/download/current/))
* [Integrate ESLint in VSCode with the official extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) * [Integrate ESLint in VSCode with the official extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint)
### Formatting ### Formatting {#formatting}
The last thing you want to do when sharing your code with another contributor is get into an discussion about [tabs vs spaces](https://www.google.com/search?q=tabs+vs+spaces)! Fortunately, [Prettier](https://prettier.io/) will clean up your code by reformatting it to conform to preset, configurable rules. Run Prettier, and all your tabs will be converted to spaces—and your indentation, quotes, etc will also all be changed to conform to the configuration. In the ideal setup, Prettier will run when you save your file, quickly making these edits for you. The last thing you want to do when sharing your code with another contributor is get into an discussion about [tabs vs spaces](https://www.google.com/search?q=tabs+vs+spaces)! Fortunately, [Prettier](https://prettier.io/) will clean up your code by reformatting it to conform to preset, configurable rules. Run Prettier, and all your tabs will be converted to spaces—and your indentation, quotes, etc will also all be changed to conform to the configuration. In the ideal setup, Prettier will run when you save your file, quickly making these edits for you.
@ -41,7 +41,7 @@ You can install the [Prettier extension in VSCode](https://marketplace.visualstu
3. Paste in `ext install esbenp.prettier-vscode` 3. Paste in `ext install esbenp.prettier-vscode`
4. Press enter 4. Press enter
#### Formatting on save #### Formatting on save {#formatting-on-save}
Ideally, you should format your code on every save. VS Code has settings for this! Ideally, you should format your code on every save. VS Code has settings for this!

22
beta/src/pages/learn/extracting-state-logic-into-a-reducer.md

@ -18,7 +18,7 @@ Components with many state updates spread across many event handlers can get ove
</YouWillLearn> </YouWillLearn>
## Consolidate state logic with a reducer ## Consolidate state logic with a reducer {#consolidate-state-logic-with-a-reducer}
As your components grow in complexity, it can get harder to see all the different ways that a component's state gets updated at a glance. For example, the `TaskBoard` component below holds an array of `tasks` in state and uses three different event handlers to add, remove, and edit tasks: As your components grow in complexity, it can get harder to see all the different ways that a component's state gets updated at a glance. For example, the `TaskBoard` component below holds an array of `tasks` in state and uses three different event handlers to add, remove, and edit tasks:
@ -189,7 +189,7 @@ Reducers are a different way to handle state. You can migrate from `useState` to
2. **Write** a reducer function. 2. **Write** a reducer function.
3. **Use** the reducer from your component. 3. **Use** the reducer from your component.
### Step 1: Move from setting state to dispatching actions ### Step 1: Move from setting state to dispatching actions {#step-1-move-from-setting-state-to-dispatching-actions}
Your event handlers currently specify *what to do* by setting state: Your event handlers currently specify *what to do* by setting state:
@ -281,7 +281,7 @@ dispatch({
</Convention> </Convention>
### Step 2: Write a reducer function ### Step 2: Write a reducer function {#step-2-write-a-reducer-function}
A reducer function is where you will put your state logic. It takes two arguments, the current state and the action object, and it returns the next state: A reducer function is where you will put your state logic. It takes two arguments, the current state and the action object, and it returns the next state:
@ -452,7 +452,7 @@ You probably won't need to do this yourself, but this is similar to what React d
</DeepDive> </DeepDive>
### Step 3: Use the reducer from your component ### Step 3: Use the reducer from your component {#step-3-use-the-reducer-from-your-component}
Finally, you need to hook up the `tasksReducer` to your component. Make sure to import the `useReducer` Hook from React: Finally, you need to hook up the `tasksReducer` to your component. Make sure to import the `useReducer` Hook from React:
@ -870,7 +870,7 @@ ul, li { margin: 0; padding: 0; }
Component logic can be easier to read when you separate concerns like this. Now the event handlers only specify *what happened* by dispatching actions, and the reducer function determines *how the state updates* in response to them. Component logic can be easier to read when you separate concerns like this. Now the event handlers only specify *what happened* by dispatching actions, and the reducer function determines *how the state updates* in response to them.
## Comparing `useState` and `useReducer` ## Comparing `useState` and `useReducer` {#comparing-usestate-and-usereducer}
Reducers are not without downsides! Here's a few ways you can compare them: Reducers are not without downsides! Here's a few ways you can compare them:
@ -882,14 +882,14 @@ Reducers are not without downsides! Here's a few ways you can compare them:
We recommend using a reducer if you often encounter bugs due to incorrect state updates in some component, and want to introduce more structure to its code. You don't have to use reducers for everything: feel free to mix and match! You can even `useState` and `useReducer` in the same component. We recommend using a reducer if you often encounter bugs due to incorrect state updates in some component, and want to introduce more structure to its code. You don't have to use reducers for everything: feel free to mix and match! You can even `useState` and `useReducer` in the same component.
## Writing reducers well ## Writing reducers well {#writing-reducers-well}
Keep these two tips in mind when writing reducers: Keep these two tips in mind when writing reducers:
* **Reducers must be pure.** Similar to [state updater functions](/learn/queueing-a-series-of-state-updates), reducers run during rendering! (Actions are queued until the next render.) This means that reducers [must be pure](/learn/keeping-components-pure)—same inputs always result in the same output. They should not send requests, schedule timeouts, or perform any side effects (operations that impact things outside the component). They should update [objects](/learn/updating-objects-in-state) and [arrays](/learn/updating-arrays-in-state) without mutations. * **Reducers must be pure.** Similar to [state updater functions](/learn/queueing-a-series-of-state-updates), reducers run during rendering! (Actions are queued until the next render.) This means that reducers [must be pure](/learn/keeping-components-pure)—same inputs always result in the same output. They should not send requests, schedule timeouts, or perform any side effects (operations that impact things outside the component). They should update [objects](/learn/updating-objects-in-state) and [arrays](/learn/updating-arrays-in-state) without mutations.
* **Actions describe "what happened," not "what to do."** For example, if a user presses "Reset" on a form with five fields managed by a reducer, it makes more sense to dispatch one `reset_form` action rather than five separate `set_field` actions. If you log every action in a reducer, that log should be clear enough for you to reconstruct what interactions or responses happened in what order. This helps with debugging! * **Actions describe "what happened," not "what to do."** For example, if a user presses "Reset" on a form with five fields managed by a reducer, it makes more sense to dispatch one `reset_form` action rather than five separate `set_field` actions. If you log every action in a reducer, that log should be clear enough for you to reconstruct what interactions or responses happened in what order. This helps with debugging!
## Writing concise reducers with Immer ## Writing concise reducers with Immer {#writing-concise-reducers-with-immer}
Just like with [updating objects](/learn/updating-objects-in-state#write-concise-update-logic-with-immer) and [arrays](/learn/updating-arrays-in-state#write-concise-update-logic-with-immer) in regular state, you can use the Immer library to make reducers more concise. Here, [`useImmerReducer`](https://github.com/immerjs/use-immer#useimmerreducer) lets you mutate the state with `push` or `arr[i] =` assignment: Just like with [updating objects](/learn/updating-objects-in-state#write-concise-update-logic-with-immer) and [arrays](/learn/updating-arrays-in-state#write-concise-update-logic-with-immer) in regular state, you can use the Immer library to make reducers more concise. Here, [`useImmerReducer`](https://github.com/immerjs/use-immer#useimmerreducer) lets you mutate the state with `push` or `arr[i] =` assignment:
@ -1116,7 +1116,7 @@ Reducers must be pure, so they shouldn't mutate state. But Immer provides you wi
<Challenges> <Challenges>
### Dispatch actions from event handlers ### Dispatch actions from event handlers {#dispatch-actions-from-event-handlers}
Currently, the event handlers in `ContactList.js` and `Chat.js` have `// TODO` comments. This is why typing into the input doesn't work, and clicking on the buttons doesn't change the selected recipient. Currently, the event handlers in `ContactList.js` and `Chat.js` have `// TODO` comments. This is why typing into the input doesn't work, and clicking on the buttons doesn't change the selected recipient.
@ -1468,7 +1468,7 @@ textarea {
</Solution> </Solution>
### Clear the input on sending a message ### Clear the input on sending a message {#clear-the-input-on-sending-a-message}
Currently, pressing "Send" doesn't do anything. Add an event handler to the "Send" button that will: Currently, pressing "Send" doesn't do anything. Add an event handler to the "Send" button that will:
@ -1971,7 +1971,7 @@ With either solution, it's important that you **don't** place the `alert` inside
</Solution> </Solution>
### Restore input values when switching between tabs ### Restore input values when switching between tabs {#restore-input-values-when-switching-between-tabs}
In this example, switching between different recipients always clears the text input: In this example, switching between different recipients always clears the text input:
@ -2386,7 +2386,7 @@ Notably, you didn't need to change any of the event handlers to implement this d
</Solution> </Solution>
### Implement `useReducer` from scratch ### Implement `useReducer` from scratch {#implement-usereducer-from-scratch}
In the earlier examples, you imported the `useReducer` Hook from React. This time, you will implement *the `useReducer` Hook itself!* Here is a stub to get your started. It shouldn't take more than 10 lines of code. In the earlier examples, you imported the `useReducer` Hook from React. This time, you will implement *the `useReducer` Hook itself!* Here is a stub to get your started. It shouldn't take more than 10 lines of code.

8
beta/src/pages/learn/importing-and-exporting-components.md

@ -19,7 +19,7 @@ The magic of components lies in their reusability: you can create components tha
</YouWillLearn> </YouWillLearn>
## The root component file ## The root component file {#the-root-component-file}
In [Your First Component](/learn/your-first-component), you made a `Profile` component and a `Gallery` component that renders it: In [Your First Component](/learn/your-first-component), you made a `Profile` component and a `Gallery` component that renders it:
@ -55,7 +55,7 @@ img { margin: 0 10px 10px 0; height: 90px; }
These currently live in a **root component file,** named `App.js` in this example. In [Create React App](https://create-react-app.dev/), your app lives in `src/App.js`. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page. These currently live in a **root component file,** named `App.js` in this example. In [Create React App](https://create-react-app.dev/), your app lives in `src/App.js`. Depending on your setup, your root component could be in another file, though. If you use a framework with file-based routing, such as Next.js, your root component will be different for every page.
## Exporting and importing a component ## Exporting and importing a component {#exporting-and-importing-a-component}
What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery` and `Profile` out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps: What if you want to change the landing screen in the future and put a list of science books there? Or place all the profiles somewhere else? It makes sense to move `Gallery` and `Profile` out of the root component file. This will make them more modular and reusable in other files. You can move a component in three steps:
@ -146,7 +146,7 @@ When you write a _default_ import, you can put any name you want after `import`.
</DeepDive> </DeepDive>
## Exporting and importing multiple components from the same file ## Exporting and importing multiple components from the same file {#exporting-and-importing-multiple-components-from-the-same-file}
What if you want to show just one `Profile` instead of a gallery? You can export the `Profile` component, too. But `Gallery.js` already has a *default* export, and you can't have _two_ default exports. You could create a new file with a default export, or you could add a *named* export for `Profile`. **A file can only have one default export, but it can have numerous named exports!** What if you want to show just one `Profile` instead of a gallery? You can export the `Profile` component, too. But `Gallery.js` already has a *default* export, and you can't have _two_ default exports. You could create a new file with a default export, or you could add a *named* export for `Profile`. **A file can only have one default export, but it can have numerous named exports!**
@ -242,7 +242,7 @@ On this page you learned:
<Challenges> <Challenges>
### Split the components further ### Split the components further {#split-the-components-further}
Currently, `Gallery.js` exports both `Profile` and `Gallery`, which is a bit confusing. Currently, `Gallery.js` exports both `Profile` and `Gallery`, which is a bit confusing.

18
beta/src/pages/learn/index.md

@ -20,7 +20,7 @@ Welcome to the React documentation! Here is an overview of what you can find on
</YouWillLearn> </YouWillLearn>
## Introduction ## Introduction {#introduction}
This is a tiny React app. To get your first taste of React, **edit the code below** and make it display your name: This is a tiny React app. To get your first taste of React, **edit the code below** and make it display your name:
@ -44,7 +44,7 @@ export default function App() {
</Sandpack> </Sandpack>
### What is React? ### What is React? {#what-is-react}
React is a JavaScript library for building user interfaces. React is a JavaScript library for building user interfaces.
@ -52,13 +52,13 @@ React stands at the intersection of design and programming. **It lets you take a
React does not prescribe how you build your entire application. It helps you define and compose components, but stays out of your way in other questions. This means that you will either pick one of the ecosystem solutions for problems like routing, styling, and data fetching, or [use a framework](/learn/start-a-new-react-project#building-with-react-and-a-framework) that provides great defaults. React does not prescribe how you build your entire application. It helps you define and compose components, but stays out of your way in other questions. This means that you will either pick one of the ecosystem solutions for problems like routing, styling, and data fetching, or [use a framework](/learn/start-a-new-react-project#building-with-react-and-a-framework) that provides great defaults.
### What can you do with React? ### What can you do with React? {#what-can-you-do-with-react}
Quite a lot, really! People use React to create all kinds of user interfaces--from small controls like buttons and dropdowns to entire apps. **These docs will teach you to use React on the web.** However, most of what you'll learn here applies equally for [React Native](https://reactnative.dev/) which lets you build apps for Android, iOS, and even [Windows and macOS](https://microsoft.github.io/react-native-windows/). Quite a lot, really! People use React to create all kinds of user interfaces--from small controls like buttons and dropdowns to entire apps. **These docs will teach you to use React on the web.** However, most of what you'll learn here applies equally for [React Native](https://reactnative.dev/) which lets you build apps for Android, iOS, and even [Windows and macOS](https://microsoft.github.io/react-native-windows/).
If you're curious which products you use everyday are built with React, you can install the [React Developer Tools](/learn/react-developer-tools). Whenever you visit an app or a website built with React (like this one!), its icon will light up in the toolbar. If you're curious which products you use everyday are built with React, you can install the [React Developer Tools](/learn/react-developer-tools). Whenever you visit an app or a website built with React (like this one!), its icon will light up in the toolbar.
### React uses JavaScript ### React uses JavaScript {#react-uses-javascript}
With React, you will describe your visual logic in JavaScript. This takes some practice. If you're learning JavaScript and React at the same time, you're not alone--but at times, it will be a little bit more challenging! On the upside, **much of learning React is really learning JavaScript,** which means you will take your learnings far beyond React. With React, you will describe your visual logic in JavaScript. This takes some practice. If you're learning JavaScript and React at the same time, you're not alone--but at times, it will be a little bit more challenging! On the upside, **much of learning React is really learning JavaScript,** which means you will take your learnings far beyond React.
@ -86,7 +86,7 @@ When you're ready to start a project, there are several options. You can write R
</DeepDive> </DeepDive>
## Learn React ## Learn React {#learn-react}
There are a few ways to get started: There are a few ways to get started:
@ -96,7 +96,7 @@ There are a few ways to get started:
To save you time, we provide **a brief overview of each chapter** below. To save you time, we provide **a brief overview of each chapter** below.
### Chapter 1 overview: Describing the UI ### Chapter 1 overview: Describing the UI {#chapter-1-overview-describing-the-ui}
React applications are built from isolated pieces of UI called ["components"](/learn/your-first-component). A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here, a *parent* `Gallery` component renders three *child* `Profile` components: React applications are built from isolated pieces of UI called ["components"](/learn/your-first-component). A React component is a JavaScript function that you can sprinkle with markup. Components can be as small as a button, or as large as an entire page. Here, a *parent* `Gallery` component renders three *child* `Profile` components:
@ -257,7 +257,7 @@ Read **[Describing the UI](/learn/describing-the-ui)** to learn how to make thin
</LearnMore> </LearnMore>
### Chapter 2 overview: Adding interactivity ### Chapter 2 overview: Adding interactivity {#chapter-2-overview-adding-interactivity}
Components often need to change what’s on the screen as a result of an interaction. Typing into the form should update the input field, clicking “next” on an image carousel should change which image is displayed, clicking “buy” puts a product in the shopping cart. Components need to “remember” things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called [*state*](/learn/state-a-components-memory). Components often need to change what’s on the screen as a result of an interaction. Typing into the form should update the input field, clicking “next” on an image carousel should change which image is displayed, clicking “buy” puts a product in the shopping cart. Components need to “remember” things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called [*state*](/learn/state-a-components-memory).
@ -529,7 +529,7 @@ Read **[Adding Interactivity](/learn/adding-interactivity)** to learn how to upd
</LearnMore> </LearnMore>
### Chapter 3 overview: Managing state ### Chapter 3 overview: Managing state {#chapter-3-overview-managing-state}
You'll often face a choice of _what exactly_ to put into state. Should you use one state variable or many? An object or an array? How should you [structure your state](/learn/choosing-the-state-structure)? The most important principle is to **avoid redundant state**. If some information never changes, it shouldn't be in state. If some information is received from parent by props, it shouldn't be in state. And if you can compute something from other props or state, it shouldn't be in state either! You'll often face a choice of _what exactly_ to put into state. Should you use one state variable or many? An object or an array? How should you [structure your state](/learn/choosing-the-state-structure)? The most important principle is to **avoid redundant state**. If some information never changes, it shouldn't be in state. If some information is received from parent by props, it shouldn't be in state. And if you can compute something from other props or state, it shouldn't be in state either!
@ -707,7 +707,7 @@ Read **[Managing State](/learn/managing-state)** to learn how to keep your compo
</LearnMore> </LearnMore>
## Next steps ## Next steps {#next-steps}
This page was fast-paced! If you've read this far, you have already seen 80% of React you will use on daily basis. This page was fast-paced! If you've read this far, you have already seen 80% of React you will use on daily basis.

10
beta/src/pages/learn/installation.md

@ -18,7 +18,7 @@ React has been designed from the start for gradual adoption, and you can use as
</YouWillLearn> </YouWillLearn>
## Try React ## Try React {#try-react}
You don't need to install anything to play with React. Try editing this sandbox! You don't need to install anything to play with React. Try editing this sandbox!
@ -39,18 +39,18 @@ export default function App() {
We use sandboxes throughout these docs as teaching aids. Sandboxes can help familiarize you with how React works and help you decide if React is right for you. Outside of the React documentation, there are many online sandboxes that support React: for example, [CodeSandbox](https://codesandbox.io/s/new), [Stackblitz](https://stackblitz.com/fork/react), or [CodePen]( We use sandboxes throughout these docs as teaching aids. Sandboxes can help familiarize you with how React works and help you decide if React is right for you. Outside of the React documentation, there are many online sandboxes that support React: for example, [CodeSandbox](https://codesandbox.io/s/new), [Stackblitz](https://stackblitz.com/fork/react), or [CodePen](
https://codepen.io/pen/?template=wvdqJJm). https://codepen.io/pen/?template=wvdqJJm).
### Try React locally ### Try React locally {#try-react-locally}
To try React locally on your computer, [download this HTML page](https://raw.githubusercontent.com/reactjs/reactjs.org/main/static/html/single-file-example.html). Open it in your editor and in your browser! To try React locally on your computer, [download this HTML page](https://raw.githubusercontent.com/reactjs/reactjs.org/main/static/html/single-file-example.html). Open it in your editor and in your browser!
## Add React to a page ## Add React to a page {#add-react-to-a-page}
If you're working with an existing site and just need to add a little bit of React, you can [add React with a script tag.](/learn/add-react-to-a-website) If you're working with an existing site and just need to add a little bit of React, you can [add React with a script tag.](/learn/add-react-to-a-website)
## Start a React project ## Start a React project {#start-a-react-project}
If you're ready to [start a standalone project](/learn/start-a-new-react-project) with React, you can set up a minimal toolchain for a pleasant developer experience. You can also start with a framework that makes a lot of decisions for you out of the box. If you're ready to [start a standalone project](/learn/start-a-new-react-project) with React, you can set up a minimal toolchain for a pleasant developer experience. You can also start with a framework that makes a lot of decisions for you out of the box.
## Next steps ## Next steps {#next-steps}
Where you start depends on how you like to learn, what you need to accomplish, and where you want to go next! Why not read [Thinking in React](/learn/thinking-in-react)--our introductory tutorial? Or you can jump to [Describing the UI](/learn/describing-the-ui) to play with more examples and learn each topic step by step. There is no wrong way to learn React! Where you start depends on how you like to learn, what you need to accomplish, and where you want to go next! Why not read [Thinking in React](/learn/thinking-in-react)--our introductory tutorial? Or you can jump to [Describing the UI](/learn/describing-the-ui) to play with more examples and learn each topic step by step. There is no wrong way to learn React!

16
beta/src/pages/learn/javascript-in-jsx-with-curly-braces.md

@ -18,7 +18,7 @@ JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering
</YouWillLearn> </YouWillLearn>
## Passing strings with quotes ## Passing strings with quotes {#passing-strings-with-quotes}
When you want to pass a string attribute to JSX, you put it in single or double quotes: When you want to pass a string attribute to JSX, you put it in single or double quotes:
@ -70,7 +70,7 @@ export default function Avatar() {
Notice the difference between `className="avatar"`, which specifies an `"avatar"` CSS class name that makes the image round, and `src={avatar}` that reads the value of the JavaScript variable called `avatar`. That's because curly braces let you work with JavaScript right there in your markup! Notice the difference between `className="avatar"`, which specifies an `"avatar"` CSS class name that makes the image round, and `src={avatar}` that reads the value of the JavaScript variable called `avatar`. That's because curly braces let you work with JavaScript right there in your markup!
## Using curly braces: A window into the JavaScript world ## Using curly braces: A window into the JavaScript world {#using-curly-braces-a-window-into-the-javascript-world}
JSX is a special way of writing JavaScript. That means it’s possible to use JavaScript inside it—with curly braces `{ }`. The example below first declares a name for the scientist, `name`, then embeds it with curly braces inside the `<h1>`: JSX is a special way of writing JavaScript. That means it’s possible to use JavaScript inside it—with curly braces `{ }`. The example below first declares a name for the scientist, `name`, then embeds it with curly braces inside the `<h1>`:
@ -112,14 +112,14 @@ export default function TodoList() {
</Sandpack> </Sandpack>
### Where to use curly braces ### Where to use curly braces {#where-to-use-curly-braces}
You can only use curly braces in two ways inside JSX: You can only use curly braces in two ways inside JSX:
1. **As text** directly inside a JSX tag: `<h1>{name}'s To Do List</h1>` works, but `<{tag}>Gregorio Y. Zara's To Do List</{tag}>` will not. 1. **As text** directly inside a JSX tag: `<h1>{name}'s To Do List</h1>` works, but `<{tag}>Gregorio Y. Zara's To Do List</{tag}>` will not.
2. **As attributes** immediately following the `=` sign: `src={avatar}` will read the `avatar` variable, but `src="{avatar}"` will pass the string `{avatar}`. 2. **As attributes** immediately following the `=` sign: `src={avatar}` will read the `avatar` variable, but `src="{avatar}"` will pass the string `{avatar}`.
## Using "double curlies": CSS and other objects in JSX ## Using "double curlies": CSS and other objects in JSX {#using-double-curlies-css-and-other-objects-in-jsx}
In addition to strings, numbers, and other JavaScript expressions, you can even pass objects in JSX. Objects are also denoted with curly braces, like `{ name: "Hedy Lamarr", inventions: 5 }`. Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces: `person={{ name: "Hedy Lamarr", inventions: 5 }}`. In addition to strings, numbers, and other JavaScript expressions, you can even pass objects in JSX. Objects are also denoted with curly braces, like `{ name: "Hedy Lamarr", inventions: 5 }`. Therefore, to pass a JS object in JSX, you must wrap the object in another pair of curly braces: `person={{ name: "Hedy Lamarr", inventions: 5 }}`.
@ -170,7 +170,7 @@ Inline `style` properties are written in camelCase. For example, HTML `<ul style
</Gotcha> </Gotcha>
## More fun with JavaScript objects and curly braces ## More fun with JavaScript objects and curly braces {#more-fun-with-javascript-objects-and-curly-braces}
You can move several expressions into one object, and reference them in your JSX inside curly braces: You can move several expressions into one object, and reference them in your JSX inside curly braces:
@ -246,7 +246,7 @@ Now you know almost everything about JSX:
<Challenges> <Challenges>
### Fix the mistake ### Fix the mistake {#fix-the-mistake}
This code crashes with an error saying `Objects are not valid as a React child`: This code crashes with an error saying `Objects are not valid as a React child`:
@ -338,7 +338,7 @@ body > div > div { padding: 20px; }
</Solution> </Solution>
### Extract information into an object ### Extract information into an object {#extract-information-into-an-object}
Extract the image URL into the `person` object. Extract the image URL into the `person` object.
@ -425,7 +425,7 @@ body > div > div { padding: 20px; }
</Solution> </Solution>
### Write an expression inside JSX curly braces ### Write an expression inside JSX curly braces {#write-an-expression-inside-jsx-curly-braces}
In the object below, the full image URL is split into four parts: base URL, `imageId`, `imageSize`, and file extension. In the object below, the full image URL is split into four parts: base URL, `imageId`, `imageSize`, and file extension.

14
beta/src/pages/learn/keeping-components-pure.md

@ -17,7 +17,7 @@ Some JavaScript functions are "pure." Pure functions only perform a calculation
</YouWillLearn> </YouWillLearn>
## Purity: Components as formulas ## Purity: Components as formulas {#purity-components-as-formulas}
In computer science (and especially the world of functional programming), [a pure function](https://wikipedia.org/wiki/Pure_function) is a function with the following characteristics: In computer science (and especially the world of functional programming), [a pure function](https://wikipedia.org/wiki/Pure_function) is a function with the following characteristics:
@ -86,7 +86,7 @@ You could think of your components as recipes: if you follow them and don't intr
<Illustration src="/images/docs/illustrations/i_puritea-recipe.png" alt="A tea recipe for x people: take x cups of water, add 2x spoons of spices, and x spoons of tea!" /> <Illustration src="/images/docs/illustrations/i_puritea-recipe.png" alt="A tea recipe for x people: take x cups of water, add 2x spoons of spices, and x spoons of tea!" />
## Side Effects: (un)intended consequences ## Side Effects: (un)intended consequences {#side-effects-unintended-consequences}
React's rendering process must always be pure. Components should only *return* their JSX, and not *change* any objects or variables that existed before rendering—that would make them impure! React's rendering process must always be pure. Components should only *return* their JSX, and not *change* any objects or variables that existed before rendering—that would make them impure!
@ -160,7 +160,7 @@ Strict Mode has no effect in production, so it won't slow down the app for your
</DeepDive> </DeepDive>
### Local mutation: Your component's little secret ### Local mutation: Your component's little secret {#local-mutation-your-components-little-secret}
In the above example, the problem was that the component changed a *preexisting* variable while rendering. This is often called a **"mutation"** to make it sound a bit scarier. Pure functions don't mutate variables outside of the function's scope or objects that were created before the call—that makes them impure! In the above example, the problem was that the component changed a *preexisting* variable while rendering. This is often called a **"mutation"** to make it sound a bit scarier. Pure functions don't mutate variables outside of the function's scope or objects that were created before the call—that makes them impure!
@ -188,7 +188,7 @@ If the `cups` variable or the `[]` array were created outside the `TeaGathering`
However, it's fine because you've created them *during the same render*, inside `TeaGathering`. No code outside of `TeaGathering` will ever know that this happened. This is called **"local mutation"**—it's like your component's little secret. However, it's fine because you've created them *during the same render*, inside `TeaGathering`. No code outside of `TeaGathering` will ever know that this happened. This is called **"local mutation"**—it's like your component's little secret.
## Where you _can_ cause side effects ## Where you _can_ cause side effects {#where-you-_can_-cause-side-effects}
While functional programming relies heavily on purity, at some point, somewhere, _something_ has to change. That's kind of the point of programming! These changes—updating the screen, starting an animation, changing the data—are called **side effects**. They're things that happen _"on the side,"_ not during rendering. While functional programming relies heavily on purity, at some point, somewhere, _something_ has to change. That's kind of the point of programming! These changes—updating the screen, starting an animation, changing the data—are called **side effects**. They're things that happen _"on the side,"_ not during rendering.
@ -226,7 +226,7 @@ Every new React feature we're building takes advantage of purity. From data fetc
<Challenges> <Challenges>
### Fix a broken clock ### Fix a broken clock {#fix-a-broken-clock}
This component tries to set the `<h1>`'s CSS class to `"night"` during the time from midnight to six hours in the morning, and `"day"` at all other times. However, it doesn't work. Can you fix this component? This component tries to set the `<h1>`'s CSS class to `"night"` during the time from midnight to six hours in the morning, and `"day"` at all other times. However, it doesn't work. Can you fix this component?
@ -363,7 +363,7 @@ In this example, the side effect (modifying the DOM) was not necessary at all. Y
</Solution> </Solution>
### Fix a broken profile ### Fix a broken profile {#fix-a-broken-profile}
Two `Profile` components are rendered side by side with different data. Press "Collapse" on the first profile, and then "Expand" it. You'll notice that both profiles now show the same person. This is a bug. Two `Profile` components are rendered side by side with different data. Press "Collapse" on the first profile, and then "Expand" it. You'll notice that both profiles now show the same person. This is a bug.
@ -572,7 +572,7 @@ Remember that React does not guarantee that component functions will execute in
</Solution> </Solution>
### Fix a broken story tray ### Fix a broken story tray {#fix-a-broken-story-tray}
The CEO of your company is asking you to add "stories" to your online clock app, and you can't say no. You've written a `StoryTray` component that accepts a list of `stories`, followed by a "Create Story" placeholder. The CEO of your company is asking you to add "stories" to your online clock app, and you can't say no. You've written a `StoryTray` component that accepts a list of `stories`, followed by a "Create Story" placeholder.

16
beta/src/pages/learn/managing-state.md

@ -21,7 +21,7 @@ As your application grows, it helps to be more intentional about how your state
</YouWillLearn> </YouWillLearn>
## Reacting to input with state ## Reacting to input with state {#reacting-to-input-with-state}
With React, you won't modify the UI from code directly. For example, you won't write commands like "disable the button", "enable the button", "show the success message", etc. Instead, you will describe the UI you want to see for the different visual states of your component ("initial state", "typing state", "success state"), and then trigger the state changes in response to user input. This is similar to how designers think about UI. With React, you won't modify the UI from code directly. For example, you won't write commands like "disable the button", "enable the button", "show the success message", etc. Instead, you will describe the UI you want to see for the different visual states of your component ("initial state", "typing state", "success state"), and then trigger the state changes in response to user input. This is similar to how designers think about UI.
@ -113,7 +113,7 @@ Read **[Reacting to Input with State](/learn/reacting-to-input-with-state)** to
</LearnMore> </LearnMore>
## Choosing the state structure ## Choosing the state structure {#choosing-the-state-structure}
Structuring state well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. The most important principle is that state shouldn't contain redundant or duplicated information. If there's some unnecessary state, it's easy to forget to update it, and introduce bugs! Structuring state well can make a difference between a component that is pleasant to modify and debug, and one that is a constant source of bugs. The most important principle is that state shouldn't contain redundant or duplicated information. If there's some unnecessary state, it's easy to forget to update it, and introduce bugs!
@ -230,7 +230,7 @@ Read **[Choosing the State Structure](/learn/choosing-the-state-structure)** to
</LearnMore> </LearnMore>
## Sharing state between components ## Sharing state between components {#sharing-state-between-components}
Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as "lifting state up", and it's one of the most common things you will do writing React code. Sometimes, you want the state of two components to always change together. To do it, remove state from both of them, move it to their closest common parent, and then pass it down to them via props. This is known as "lifting state up", and it's one of the most common things you will do writing React code.
@ -301,7 +301,7 @@ Read **[Sharing State Between Components](/learn/sharing-state-between-component
</LearnMore> </LearnMore>
## Preserving and resetting state ## Preserving and resetting state {#preserving-and-resetting-state}
When you re-render a component, React needs to decide which parts of the tree to keep (and update), and which parts to discard or re-create from scratch. In most cases, React's automatic behavior works well enough. By default, React preserves the parts of the tree that "match up" with the previously rendered component tree. When you re-render a component, React needs to decide which parts of the tree to keep (and update), and which parts to discard or re-create from scratch. In most cases, React's automatic behavior works well enough. By default, React preserves the parts of the tree that "match up" with the previously rendered component tree.
@ -501,7 +501,7 @@ Read **[Preserving and Resetting State](/learn/preserving-and-resetting-state)**
</LearnMore> </LearnMore>
## Extracting state logic into a reducer ## Extracting state logic into a reducer {#extracting-state-logic-into-a-reducer}
Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called "reducer." Your event handlers become concise because they only specify the user "actions." At the bottom of the file, the reducer function specifies how the state should update in response to each action! Components with many state updates spread across many event handlers can get overwhelming. For these cases, you can consolidate all the state update logic outside your component in a single function, called "reducer." Your event handlers become concise because they only specify the user "actions." At the bottom of the file, the reducer function specifies how the state should update in response to each action!
@ -698,7 +698,7 @@ Read **[Extracting State Logic into a Reducer](/learn/extracting-state-logic-int
</LearnMore> </LearnMore>
## Passing data deeply with context ## Passing data deeply with context {#passing-data-deeply-with-context}
Usually, you will pass information from a parent component to a child component via props. But passing props can become inconvenient if you need to pass some prop through many components, or if many components need the same information. Context lets the parent component make some information available to any component in the tree below it—no matter how deep it is—without passing it explicitly through props. Usually, you will pass information from a parent component to a child component via props. But passing props can become inconvenient if you need to pass some prop through many components, or if many components need the same information. Context lets the parent component make some information available to any component in the tree below it—no matter how deep it is—without passing it explicitly through props.
@ -800,7 +800,7 @@ Read **[Passing Data Deeply with Context](/learn/passing-data-deeply-with-contex
</LearnMore> </LearnMore>
## Scaling up with reducer and context ## Scaling up with reducer and context {#scaling-up-with-reducer-and-context}
Reducers let you consolidate a component’s state update logic. Context lets you pass information deep down to other components. You can combine reducers and context together to manage state of a complex screen. Reducers let you consolidate a component’s state update logic. Context lets you pass information deep down to other components. You can combine reducers and context together to manage state of a complex screen.
@ -1011,7 +1011,7 @@ Read **[Scaling Up with Reducer and Context](/learn/scaling-up-with-reducer-and-
</LearnMore> </LearnMore>
## What's next? ## What's next? {#whats-next}
Head over to [Reacting to Input with State](/learn/reacting-to-input-with-state) to start reading this chapter page by page! Head over to [Reacting to Input with State](/learn/reacting-to-input-with-state) to start reading this chapter page by page!

20
beta/src/pages/learn/manipulating-the-dom-with-refs.md

@ -18,7 +18,7 @@ Because React handles updating the [DOM](https://developer.mozilla.org/docs/Web/
</YouWillLearn> </YouWillLearn>
## Getting a ref to the node ## Getting a ref to the node {#getting-a-ref-to-the-node}
To access a DOM node managed by React, first, import the `useRef` Hook: To access a DOM node managed by React, first, import the `useRef` Hook:
@ -45,7 +45,7 @@ The `useRef` Hook returns an object with a single property called `current`. Ini
myRef.current.scrollIntoView(); myRef.current.scrollIntoView();
``` ```
### Example: Focusing a text input ### Example: Focusing a text input {#example-focusing-a-text-input}
In this example, clicking the button will focus the input: In this example, clicking the button will focus the input:
@ -83,7 +83,7 @@ To implement this:
While DOM manipulation is the most common use case for refs, the `useRef` Hook can be used for storing other things outside React, like timer IDs. Similarly to state, refs remain between renders. You can even think of refs as state variables that don't trigger re-renders when you set them! You can learn more about refs in [Referencing Values with Refs](/learn/referencing-values-with-refs). While DOM manipulation is the most common use case for refs, the `useRef` Hook can be used for storing other things outside React, like timer IDs. Similarly to state, refs remain between renders. You can even think of refs as state variables that don't trigger re-renders when you set them! You can learn more about refs in [Referencing Values with Refs](/learn/referencing-values-with-refs).
### Example: Scrolling to an element ### Example: Scrolling to an element {#example-scrolling-to-an-element}
You can have more than a single ref in a component. In this example, there is a carousel of three images and three buttons to center them in the view port by calling the browser [`scrollIntoView()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) method the corresponding DOM node: You can have more than a single ref in a component. In this example, there is a carousel of three images and three buttons to center them in the view port by calling the browser [`scrollIntoView()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) method the corresponding DOM node:
@ -337,7 +337,7 @@ This lets you read individual DOM nodes from the Map later.
</DeepDive> </DeepDive>
## Accessing another component's DOM nodes ## Accessing another component's DOM nodes {#accessing-another-components-dom-nodes}
When you put a ref on a built-in component that outputs a browser element like `<input />`, React will set that ref's `current` property to the corresponding DOM node (such as the actual `<input />` in the browser). When you put a ref on a built-in component that outputs a browser element like `<input />`, React will set that ref's `current` property to the corresponding DOM node (such as the actual `<input />` in the browser).
@ -473,7 +473,7 @@ Here, `realInputRef` inside `MyInput` holds the actual input DOM node. However,
</DeepDive> </DeepDive>
## When React attaches the refs ## When React attaches the refs {#when-react-attaches-the-refs}
In React, every update is split in [two phases](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom): In React, every update is split in [two phases](/learn/render-and-commit#step-3-react-commits-changes-to-the-dom):
@ -619,7 +619,7 @@ for (let i = 0; i < 20; i++) {
</DeepDive> </DeepDive>
## Best practices for DOM manipulation with refs ## Best practices for DOM manipulation with refs {#best-practices-for-dom-manipulation-with-refs}
Refs are an escape hatch. You should only use them when you have to "step outside React." Common examples of this include managing focus, scroll position, or calling browser APIs that React does not expose. Refs are an escape hatch. You should only use them when you have to "step outside React." Common examples of this include managing focus, scroll position, or calling browser APIs that React does not expose.
@ -689,7 +689,7 @@ However, this doesn't mean that you can't do it at all. It requires caution. **Y
<Challenges> <Challenges>
### Play and pause the video ### Play and pause the video {#play-and-pause-the-video}
In this example, the button toggles a state variable to switch between a playing and a paused state. However, in order to actually play or pause the video, toggling state is not enough. You also need to call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on the DOM element for the `<video>`. Add a ref to it, and make the button work. In this example, the button toggles a state variable to switch between a playing and a paused state. However, in order to actually play or pause the video, toggling state is not enough. You also need to call [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) on the DOM element for the `<video>`. Add a ref to it, and make the button work.
@ -776,7 +776,7 @@ button { display: block }
</Solution> </Solution>
### Focus the search field ### Focus the search field {#focus-the-search-field}
Make it so that clicking the "Search" button puts focus into the field. Make it so that clicking the "Search" button puts focus into the field.
@ -840,7 +840,7 @@ button { display: block; margin-bottom: 10px; }
</Solution> </Solution>
### Scrolling an image carousel ### Scrolling an image carousel {#scrolling-an-image-carousel}
This image carousel has a "Next" button that switches the active image. Make the gallery scroll horizontally to the active image on click. You will want to call [`scrollIntoView()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) on the DOM node of the active image: This image carousel has a "Next" button that switches the active image. Make the gallery scroll horizontally to the active image on click. You will want to call [`scrollIntoView()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) on the DOM node of the active image:
@ -1066,7 +1066,7 @@ img {
</Solution> </Solution>
### Focus the search field with separate components ### Focus the search field with separate components {#focus-the-search-field-with-separate-components}
Make it so that clicking the "Search" button puts focus into the field. Note that each component is defined in a separate file and shouldn't be moved out of it. How do you connect them together? Make it so that clicking the "Search" button puts focus into the field. Note that each component is defined in a separate file and shouldn't be moved out of it. How do you connect them together?

20
beta/src/pages/learn/passing-data-deeply-with-context.md

@ -18,7 +18,7 @@ Usually, you will pass information from a parent component to a child component
</YouWillLearn> </YouWillLearn>
## The problem with passing props ## The problem with passing props {#the-problem-with-passing-props}
[Passing props](/learn/passing-props-to-a-component) is a great way to explicitly pipe data through your UI tree to the components that use it. But it can become verbose and inconvenient when you need to pass some prop deeply through the tree, or if many components need the same prop. The nearest common ancestor could be far removed from the components that need data, and [lifting state up](/learn/sharing-state-between-components) that high can lead to a situation sometimes called "prop drilling." [Passing props](/learn/passing-props-to-a-component) is a great way to explicitly pipe data through your UI tree to the components that use it. But it can become verbose and inconvenient when you need to pass some prop deeply through the tree, or if many components need the same prop. The nearest common ancestor could be far removed from the components that need data, and [lifting state up](/learn/sharing-state-between-components) that high can lead to a situation sometimes called "prop drilling."
@ -26,7 +26,7 @@ Usually, you will pass information from a parent component to a child component
Wouldn't it be great if there were a way to "teleport" data to the components in the tree that need it without passing props? With React's context feature, there is! Wouldn't it be great if there were a way to "teleport" data to the components in the tree that need it without passing props? With React's context feature, there is!
## Context: an alternative to passing props ## Context: an alternative to passing props {#context-an-alternative-to-passing-props}
Context lets a parent component provide data to the entire tree below it. There are many uses for context. Here is one example. Consider this `Heading` component that accepts a `level` for its size: Context lets a parent component provide data to the entire tree below it. There are many uses for context. Here is one example. Consider this `Heading` component that accepts a `level` for its size:
@ -198,7 +198,7 @@ Context lets a parent--even a distant one!--provide some data to the entire tree
<img alt="Context provides data to the entire tree" src="/images/docs/sketches/s_providing-context.png" /> <img alt="Context provides data to the entire tree" src="/images/docs/sketches/s_providing-context.png" />
### Step 1: Create the context ### Step 1: Create the context {#step-1-create-the-context}
First, you need to create the context. You'll need to **export it from a file** so that your components can use it: First, you need to create the context. You'll need to **export it from a file** so that your components can use it:
@ -282,7 +282,7 @@ export const LevelContext = createContext(1);
The only argument to `createContext` is the _default_ value. Here, `1` refers to the biggest heading level, but you could pass any kind of value (even an object). You will see the significance of the default value in the next step. The only argument to `createContext` is the _default_ value. Here, `1` refers to the biggest heading level, but you could pass any kind of value (even an object). You will see the significance of the default value in the next step.
### Step 2: Use the context ### Step 2: Use the context {#step-2-use-the-context}
Import the `useContext` Hook from React and your context: Import the `useContext` Hook from React and your context:
@ -418,7 +418,7 @@ Notice this example doesn't quite work, yet! All the headers have the same size
If you don't provide the context, React will use the default value you've specified in the previous step. In this example, you specified `1` as the argument to `createContext`, so `useContext(LevelContext)` returns `1`, setting all those headings to `<h1>`. Let's fix this problem by having each `Section` provide its own context. If you don't provide the context, React will use the default value you've specified in the previous step. In this example, you specified `1` as the argument to `createContext`, so `useContext(LevelContext)` returns `1`, setting all those headings to `<h1>`. Let's fix this problem by having each `Section` provide its own context.
### Step 3: Provide the context ### Step 3: Provide the context {#step-3-provide-the-context}
The `Section` component currently renders its children: The `Section` component currently renders its children:
@ -542,7 +542,7 @@ It's the same result as the original code, but you did not need to pass the `lev
2. `Section` wraps its children into `<LevelContext.Provider value={level}>`. 2. `Section` wraps its children into `<LevelContext.Provider value={level}>`.
3. `Header` asks the closest value of `LevelContext` above with `useContext(LevelContext)`. 3. `Header` asks the closest value of `LevelContext` above with `useContext(LevelContext)`.
## Using and providing context from the same component ## Using and providing context from the same component {#using-and-providing-context-from-the-same-component}
Currently, you still have to specify each section's `level` manually: Currently, you still have to specify each section's `level` manually:
@ -671,7 +671,7 @@ Now both `Heading` and `Section` read the `LevelContext` to figure out how "deep
>This example uses heading levels because they show visually how nested components can override context. But context is useful for many other use cases too. You can use it to pass down any information needed by the entire subtree: the current color theme, the currently logged in user, and so on. >This example uses heading levels because they show visually how nested components can override context. But context is useful for many other use cases too. You can use it to pass down any information needed by the entire subtree: the current color theme, the currently logged in user, and so on.
## Context passes through intermediate components ## Context passes through intermediate components {#context-passes-through-intermediate-components}
You can insert as many components as you like between the component that provides context and the one that uses it. This includes both built-in components like `<div>` and components you might build yourself. You can insert as many components as you like between the component that provides context and the one that uses it. This includes both built-in components like `<div>` and components you might build yourself.
@ -808,7 +808,7 @@ How context works might remind you of [CSS property inheritance](https://develop
In CSS, different properties like `color` and `background-color` don't override each other. You can set all `<div>`'s `color` to red without impacting `background-color`. Similarly, **different React contexts don't override each other**. Each context that you make with `createContext()` is completely separate from other ones, and ties together components using and providing *that particular* context. One component may use or provide many different contexts without a problem. In CSS, different properties like `color` and `background-color` don't override each other. You can set all `<div>`'s `color` to red without impacting `background-color`. Similarly, **different React contexts don't override each other**. Each context that you make with `createContext()` is completely separate from other ones, and ties together components using and providing *that particular* context. One component may use or provide many different contexts without a problem.
## Before you use context ## Before you use context {#before-you-use-context}
Context is very tempting to use! However, this also means it's too easy to overuse it. **Just because you need to pass some props several levels deep doesn't mean you should put that information into context.** Context is very tempting to use! However, this also means it's too easy to overuse it. **Just because you need to pass some props several levels deep doesn't mean you should put that information into context.**
@ -819,7 +819,7 @@ Here's a few alternatives you should consider before using context:
If neither of these approaches works well for you, consider context. If neither of these approaches works well for you, consider context.
## Use cases for context ## Use cases for context {#use-cases-for-context}
* **Theming:** If your app lets the user change its appearance (e.g. dark mode), you can put a context provider at the top of your app, and use that context in components that need to adjust their visual look. * **Theming:** If your app lets the user change its appearance (e.g. dark mode), you can put a context provider at the top of your app, and use that context in components that need to adjust their visual look.
* **Current account:** Many components might need to know the currently logged in user. Putting it in context makes it convenient to read it anywhere in the tree. Some apps also let you operate multiple accounts at the same time (e.g. to leave a comment as a different user). In those cases, it can be convenient to wrap a part of the UI into a nested provider with a different current account value. * **Current account:** Many components might need to know the currently logged in user. Putting it in context makes it convenient to read it anywhere in the tree. Some apps also let you operate multiple accounts at the same time (e.g. to leave a comment as a different user). In those cases, it can be convenient to wrap a part of the UI into a nested provider with a different current account value.
@ -847,7 +847,7 @@ In general, if some information is needed by distant components in different par
<Challenges> <Challenges>
### Replace prop drilling with context ### Replace prop drilling with context {#replace-prop-drilling-with-context}
In this example, toggling the checkbox changes the `imageSize` prop passed to each `<PlaceImage>`. The checkbox state is held in the top-level `App` component, but each `<PlaceImage>` needs to be aware of it. In this example, toggling the checkbox changes the `imageSize` prop passed to each `<PlaceImage>`. The checkbox state is held in the top-level `App` component, but each `<PlaceImage>` needs to be aware of it.

22
beta/src/pages/learn/passing-props-to-a-component.md

@ -19,7 +19,7 @@ React components use **props** to communicate with each other. Every parent comp
</YouWillLearn> </YouWillLearn>
## Familiar props ## Familiar props {#familiar-props}
Props are the information that you pass to a JSX tag. For example, `className`, `src`, `alt`, `width`, and `height` are some of the props you can pass to an `<img>`: Props are the information that you pass to a JSX tag. For example, `className`, `src`, `alt`, `width`, and `height` are some of the props you can pass to an `<img>`:
@ -54,7 +54,7 @@ body { min-height: 120px; }
The props you can pass to an `<img>` tag are predefined (ReactDOM conforms to [the HTML standard](https://www.w3.org/TR/html52/semantics-embedded-content.html#the-img-element)). But you can pass any props to *your own* components, such as `<Avatar>`, to customize them. Here's how! The props you can pass to an `<img>` tag are predefined (ReactDOM conforms to [the HTML standard](https://www.w3.org/TR/html52/semantics-embedded-content.html#the-img-element)). But you can pass any props to *your own* components, such as `<Avatar>`, to customize them. Here's how!
## Passing props to a component ## Passing props to a component {#passing-props-to-a-component}
In this code, the `Profile` component isn't passing any props to its child component, `Avatar`: In this code, the `Profile` component isn't passing any props to its child component, `Avatar`:
@ -68,7 +68,7 @@ export default function Profile() {
You can give `Avatar` some props in two steps. You can give `Avatar` some props in two steps.
### Step 1: Pass props to the child component ### Step 1: Pass props to the child component {#step-1-pass-props-to-the-child-component}
First, pass some props to `Avatar`. For example, let's pass two props: `person` (an object), and `size` (a number): First, pass some props to `Avatar`. For example, let's pass two props: `person` (an object), and `size` (a number):
@ -87,7 +87,7 @@ export default function Profile() {
Now you can read these props inside the `Avatar` component. Now you can read these props inside the `Avatar` component.
### Step 2: Read props inside the child component ### Step 2: Read props inside the child component {#step-2-read-props-inside-the-child-component}
You can read these props by listing their names `person, size` separated by the commas inside `({` and `})` directly after `function Avatar`. This lets you use them inside the `Avatar` code, like you would with a variable. You can read these props by listing their names `person, size` separated by the commas inside `({` and `})` directly after `function Avatar`. This lets you use them inside the `Avatar` code, like you would with a variable.
@ -201,7 +201,7 @@ function Avatar(props) {
</Gotcha> </Gotcha>
## Specifying a default value for a prop ## Specifying a default value for a prop {#specifying-a-default-value-for-a-prop}
If you want to give a prop a default value to fall back on when no value is specified, you can do it with the destructuring by putting `=` and the default value right after the parameter: If you want to give a prop a default value to fall back on when no value is specified, you can do it with the destructuring by putting `=` and the default value right after the parameter:
@ -215,7 +215,7 @@ Now, if `<Avatar person={...} />` is rendered with no `size` prop, the `size` wi
The default value is only used if the `size` prop is missing or if you pass `size={undefined}`. But if you pass `size={null}` or `size={0}`, the default value will **not** be used. The default value is only used if the `size` prop is missing or if you pass `size={undefined}`. But if you pass `size={null}` or `size={0}`, the default value will **not** be used.
## Forwarding props with the JSX spread syntax ## Forwarding props with the JSX spread syntax {#forwarding-props-with-the-jsx-spread-syntax}
Sometimes, passing props gets very repetitive: Sometimes, passing props gets very repetitive:
@ -250,7 +250,7 @@ This forwards all of `Profile`'s props to the `Avatar` without listing each of t
**Use spread syntax with restraint.** If you're using it in every other component, something is wrong. Often, it indicates that you should split your components and pass children as JSX. More on that next! **Use spread syntax with restraint.** If you're using it in every other component, something is wrong. Often, it indicates that you should split your components and pass children as JSX. More on that next!
## Passing JSX as children ## Passing JSX as children {#passing-jsx-as-children}
It is common to nest built-in browser tags: It is common to nest built-in browser tags:
@ -350,7 +350,7 @@ You can think of a component with a `children` prop as having a "hole" that can
<Illustration src="/images/docs/illustrations/i_children-prop.png" alt='A puzzle-like Card tile with a slot for "children" pieces like text and Avatar' /> <Illustration src="/images/docs/illustrations/i_children-prop.png" alt='A puzzle-like Card tile with a slot for "children" pieces like text and Avatar' />
## How props change over time ## How props change over time {#how-props-change-over-time}
The `Clock` component below receives two props from its parent component: `color` and `time`. (The parent component's code is omitted because it uses [state](/learn/state-a-components-memory), which we won't dive into just yet.) The `Clock` component below receives two props from its parent component: `color` and `time`. (The parent component's code is omitted because it uses [state](/learn/state-a-components-memory), which we won't dive into just yet.)
@ -426,7 +426,7 @@ However, props are [immutable](https://en.wikipedia.org/wiki/Immutable_object)
<Challenges> <Challenges>
### Extract a component ### Extract a component {#extract-a-component}
This `Gallery` component contains some very similar markup for two profiles. Extract a `Profile` component out of it to reduce the duplication. You'll need to choose what props to pass to it. This `Gallery` component contains some very similar markup for two profiles. Extract a `Profile` component out of it to reduce the duplication. You'll need to choose what props to pass to it.
@ -728,7 +728,7 @@ Although the syntax looks slightly different because you're describing propertie
</Solution> </Solution>
### Adjust the image size based on a prop ### Adjust the image size based on a prop {#adjust-the-image-size-based-on-a-prop}
In this example, `Avatar` receives a numeric `size` prop which determines the `<img>` width and height. The `size` prop is set to `40` in this example. However, if you open the image in a new tab, you'll notice that the image itself is larger (`160` pixels). The real image size is determined by which thumbnail size you're requesting. In this example, `Avatar` receives a numeric `size` prop which determines the `<img>` width and height. The `size` prop is set to `40` in this example. However, if you open the image in a new tab, you'll notice that the image itself is larger (`160` pixels). The real image size is determined by which thumbnail size you're requesting.
@ -920,7 +920,7 @@ Props let you encapsulate logic like this inside the `Avatar` component (and cha
</Solution> </Solution>
### Passing JSX in a `children` prop ### Passing JSX in a `children` prop {#passing-jsx-in-a-children-prop}
Extract a `Card` component from the markup below, and use the `children` prop to pass different JSX to it: Extract a `Card` component from the markup below, and use the `children` prop to pass different JSX to it:

26
beta/src/pages/learn/preserving-and-resetting-state.md

@ -18,7 +18,7 @@ State is isolated between components. React keeps track of which state belongs t
</YouWillLearn> </YouWillLearn>
## The UI tree ## The UI tree {#the-ui-tree}
Browsers use many tree structures to model UI. The [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) represents HTML elements, the [CSSOM](https://developer.mozilla.org/docs/Web/API/CSS_Object_Model) does the same for CSS. There's even an [Accessibility tree](https://developer.mozilla.org/docs/Glossary/Accessibility_tree)! Browsers use many tree structures to model UI. The [DOM](https://developer.mozilla.org/docs/Web/API/Document_Object_Model/Introduction) represents HTML elements, the [CSSOM](https://developer.mozilla.org/docs/Web/API/CSS_Object_Model) does the same for CSS. There's even an [Accessibility tree](https://developer.mozilla.org/docs/Glossary/Accessibility_tree)!
@ -26,7 +26,7 @@ React also uses tree structures to manage and model the UI you make. React makes
<img alt="React takes components, turns them into UI tree structures, and ReactDOM turns them into HTML in your browser using the DOM." src="/images/docs/sketches/s_react-dom-tree.png" /> <img alt="React takes components, turns them into UI tree structures, and ReactDOM turns them into HTML in your browser using the DOM." src="/images/docs/sketches/s_react-dom-tree.png" />
## State is tied to a position in the tree ## State is tied to a position in the tree {#state-is-tied-to-a-position-in-the-tree}
When you give a component state, you might think the state "lives" inside the component. But the state is actually held inside React. React associates each piece of state it's holding with the correct component by where that component sits in the UI tree. When you give a component state, you might think the state "lives" inside the component. But the state is actually held inside React. React associates each piece of state it's holding with the correct component by where that component sits in the UI tree.
@ -245,7 +245,7 @@ When you tick "Render the second counter," a second `Counter` and its state are
**React preserves a component's state for as long as it's being rendered at its position in the UI tree.** If it gets removed, or a different component gets rendered at the same position, React discards its state. **React preserves a component's state for as long as it's being rendered at its position in the UI tree.** If it gets removed, or a different component gets rendered at the same position, React discards its state.
## Same component at the same position preserves state ## Same component at the same position preserves state {#same-component-at-the-same-position-preserves-state}
In this example, there are two different `<Counter />` tags: In this example, there are two different `<Counter />` tags:
@ -447,7 +447,7 @@ You can think of them as having the same "address": the first child of the first
</Gotcha> </Gotcha>
## Different components at the same position reset state ## Different components at the same position reset state {#different-components-at-the-same-position-reset-state}
In this example, ticking the checkbox will replace `<Counter>` with a `<p>`: In this example, ticking the checkbox will replace `<Counter>` with a `<p>`:
@ -668,7 +668,7 @@ Every time you click the button, the input state disappears! This is because a *
</Gotcha> </Gotcha>
## Resetting state at the same position ## Resetting state at the same position {#resetting-state-at-the-same-position}
By default, React preserves state of a component while it stays at the same position. Usually, this is exactly what you want, so it makes sense as the default behavior. But sometimes, you may want to reset a component's state. Consider this app that lets two players keep track of their scores during each turn: By default, React preserves state of a component while it stays at the same position. Usually, this is exactly what you want, so it makes sense as the default behavior. But sometimes, you may want to reset a component's state. Consider this app that lets two players keep track of their scores during each turn:
@ -752,7 +752,7 @@ There are two ways to reset state when switching between them:
2. Give each component an explicit identity with `key` 2. Give each component an explicit identity with `key`
### Option 1: Rendering a component in different positions ### Option 1: Rendering a component in different positions {#option-1-rendering-a-component-in-different-positions}
If you want these two `Counter`s to be independent, you can render them in two different positions: If you want these two `Counter`s to be independent, you can render them in two different positions:
@ -834,7 +834,7 @@ h1 {
This solution is convenient when you only have a few independent components rendered in the same place. In this example, you only have two, so it's not a hassle to render both separately in the JSX. This solution is convenient when you only have a few independent components rendered in the same place. In this example, you only have two, so it's not a hassle to render both separately in the JSX.
### Option 2: Resetting state with a key ### Option 2: Resetting state with a key {#option-2-resetting-state-with-a-key}
There is also another, more generic, way to reset a component's state. There is also another, more generic, way to reset a component's state.
@ -926,7 +926,7 @@ Specifying a `key` tells React to use the `key` itself as part of the position,
> Remember that keys are not globally unique. They only specify the position *within the parent*. > Remember that keys are not globally unique. They only specify the position *within the parent*.
### Resetting a form with a key ### Resetting a form with a key {#resetting-a-form-with-a-key}
Resetting state with a key is particularly useful when dealing with forms. Resetting state with a key is particularly useful when dealing with forms.
@ -1155,7 +1155,7 @@ No matter which strategy you pick, a chat _with Alice_ is conceptually distinct
<Challenges> <Challenges>
### Fix disappearing input text ### Fix disappearing input text {#fix-disappearing-input-text}
This example shows a message when you press the button. However, pressing the button also accidentally resets the input. Why does this happen? Fix it so that pressing the button does not reset the input text. This example shows a message when you press the button. However, pressing the button also accidentally resets the input. Why does this happen? Fix it so that pressing the button does not reset the input text.
@ -1306,7 +1306,7 @@ This way, `Form` is always the second child, so it stays in the same position an
</Solution> </Solution>
### Swap two form fields ### Swap two form fields {#swap-two-form-fields}
This form lets you enter first and last name. It also has a checkbox controlling which field goes first. When you tick the checkbox, the "Last name" field will appear before the "First name" field. This form lets you enter first and last name. It also has a checkbox controlling which field goes first. When you tick the checkbox, the "Last name" field will appear before the "First name" field.
@ -1440,7 +1440,7 @@ label { display: block; margin: 10px 0; }
</Solution> </Solution>
### Reset a detail form ### Reset a detail form {#reset-a-detail-form}
This is an editable contact list. You can edit the selected contact's details and then either press "Save" to update it, or "Reset" to undo your changes. This is an editable contact list. You can edit the selected contact's details and then either press "Save" to update it, or "Reset" to undo your changes.
@ -1749,7 +1749,7 @@ button {
</Solution> </Solution>
### Clear an image while it's loading ### Clear an image while it's loading {#clear-an-image-while-its-loading}
When you press "Next", the browser starts loading the next image. However, because it's displayed in the same `<img>` tag, by default you would still see the previous image until the next one loads. This may be undesirable if it's important for the text to always match the image. Change it so that the moment you press "Next," the previous image immediately clears. When you press "Next", the browser starts loading the next image. However, because it's displayed in the same `<img>` tag, by default you would still see the previous image until the next one loads. This may be undesirable if it's important for the text to always match the image. Change it so that the moment you press "Next," the previous image immediately clears.
@ -1893,7 +1893,7 @@ img { width: 150px; height: 150px; }
</Solution> </Solution>
### Fix misplaced state in the list ### Fix misplaced state in the list {#fix-misplaced-state-in-the-list}
In this list, each `Contact` has state that determines whether "Show email" has been pressed for it. Press "Show email" for Alice, and then tick the "Show in reverse order" checkbox. You will notice that it's _Taylor's_ email that is expanded now, but Alice's--which has moved to the bottom--appears collapsed. In this list, each `Contact` has state that determines whether "Show email" has been pressed for it. Press "Show email" for Alice, and then tick the "Show in reverse order" checkbox. You will notice that it's _Taylor's_ email that is expanded now, but Alice's--which has moved to the bottom--appears collapsed.

14
beta/src/pages/learn/queueing-a-series-of-state-updates.md

@ -16,7 +16,7 @@ Setting a state variable will queue another render. But sometimes you might want
</YouWillLearn> </YouWillLearn>
## React batches state updates ## React batches state updates {#react-batches-state-updates}
You might expect that clicking the "+3" button will increment the counter three times because it calls `setNumber(number + 1)` three times: You might expect that clicking the "+3" button will increment the counter three times because it calls `setNumber(number + 1)` three times:
@ -66,7 +66,7 @@ This lets you update multiple state variables--even from multiple components--wi
**React does not batch across *multiple* intentional events like clicks**--each click is handled separately. Rest assured that React only does batching when it's generally safe to do. This ensures that, for example, if the first button click disables a form, the second click would not submit it again. **React does not batch across *multiple* intentional events like clicks**--each click is handled separately. Rest assured that React only does batching when it's generally safe to do. This ensures that, for example, if the first button click disables a form, the second click would not submit it again.
## Updating the same state variable multiple times before the next render ## Updating the same state variable multiple times before the next render {#updating-the-same-state-variable-multiple-times-before-the-next-render}
It is an uncommon use case, but if you would like to update the same state variable multiple times before the next render, instead of passing the *next state value* like `setNumber(number + 1)`, you can pass a *function* that calculates the next state based on the previous one in the queue, like `setNumber(n => n + 1)`. It is a way to tell React to "do something with the state value" instead of just replacing it. It is an uncommon use case, but if you would like to update the same state variable multiple times before the next render, instead of passing the *next state value* like `setNumber(number + 1)`, you can pass a *function* that calculates the next state based on the previous one in the queue, like `setNumber(n => n + 1)`. It is a way to tell React to "do something with the state value" instead of just replacing it.
@ -128,7 +128,7 @@ When you call `useState` during the next render, React goes through the queue. T
React stores `3` as the final result and returns it from `useState`. React stores `3` as the final result and returns it from `useState`.
This is why clicking "+3" in the above example correctly increments the value by 3. This is why clicking "+3" in the above example correctly increments the value by 3.
### What happens if you update state after replacing it ### What happens if you update state after replacing it {#what-happens-if-you-update-state-after-replacing-it}
What about this event handler? What do you think `number` will be in the next render? What about this event handler? What do you think `number` will be in the next render?
@ -182,7 +182,7 @@ React stores `6` as the final result and returns it from `useState`.
> You may have noticed that `setState(x)` actually works like `setState(n => x)`, but `n` is unused! > You may have noticed that `setState(x)` actually works like `setState(n => x)`, but `n` is unused!
### What happens if you replace state after updating it ### What happens if you replace state after updating it {#what-happens-if-you-replace-state-after-updating-it}
Let's try one more example. What do you think `number` will be in the next render? Let's try one more example. What do you think `number` will be in the next render?
@ -245,7 +245,7 @@ To summarize, here's how you can think of what you're passing to the `setNumber`
After the event handler completes, React will trigger a re-render. During the re-render, React will process the queue. Updater functions run during rendering, so **updater functions must be [pure](/learn/keeping-components-pure)** and only *return* the result. Don't try to set state from inside of them or run other side effects. In Strict Mode, React will run each updater function twice (but discard the second result) to help you find mistakes. After the event handler completes, React will trigger a re-render. During the re-render, React will process the queue. Updater functions run during rendering, so **updater functions must be [pure](/learn/keeping-components-pure)** and only *return* the result. Don't try to set state from inside of them or run other side effects. In Strict Mode, React will run each updater function twice (but discard the second result) to help you find mistakes.
### Naming conventions ### Naming conventions {#naming-conventions}
It's common to name the updater function argument by the first letters of the corresponding state variable: It's common to name the updater function argument by the first letters of the corresponding state variable:
@ -269,7 +269,7 @@ If you prefer more verbose code, another common convention is to repeat the full
<Challenges> <Challenges>
### Fix a request counter ### Fix a request counter {#fix-a-request-counter}
You're working on an art marketplace app that lets the user submit multiple orders for an art item at the same time. Each time the user presses the "Buy" button, the "Pending" counter should increase by one. After three seconds, the "Pending" counter should decrease, and the "Completed" counter should increase. You're working on an art marketplace app that lets the user submit multiple orders for an art item at the same time. Each time the user presses the "Buy" button, the "Pending" counter should increase by one. After three seconds, the "Pending" counter should decrease, and the "Completed" counter should increase.
@ -365,7 +365,7 @@ This ensures that when you increment or decrement a counter, you do it in relati
</Solution> </Solution>
### Implement the state queue yourself ### Implement the state queue yourself {#implement-the-state-queue-yourself}
In this challenge, you will reimplement a tiny part of React from scratch! It's not as hard as it sounds. In this challenge, you will reimplement a tiny part of React from scratch! It's not as hard as it sounds.

6
beta/src/pages/learn/react-developer-tools.md

@ -9,7 +9,7 @@ Use React Developer Tools to inspect React [components](/learn/your-first-compon
</Intro> </Intro>
## Browser extension ## Browser extension {#browser-extension}
The easiest way to debug websites built with React is to install the React Developer Tools browser extension. It is available for several popular browsers: The easiest way to debug websites built with React is to install the React Developer Tools browser extension. It is available for several popular browsers:
@ -21,7 +21,7 @@ Now, if you visit a website **built with React**, you will see the _Components_
![React Developer Tools extension](/images/docs/react-devtools-extension.png) ![React Developer Tools extension](/images/docs/react-devtools-extension.png)
### Safari and other browsers ### Safari and other browsers {#safari-and-other-browsers}
For other browsers (for example, Safari), install the [`react-devtools`](https://www.npmjs.com/package/react-devtools) npm package: For other browsers (for example, Safari), install the [`react-devtools`](https://www.npmjs.com/package/react-devtools) npm package:
```bash ```bash
# Yarn # Yarn
@ -47,7 +47,7 @@ Reload your website in the browser now to view it in developer tools.
![React Developer Tools standalone](/images/docs/react-devtools-standalone.png) ![React Developer Tools standalone](/images/docs/react-devtools-standalone.png)
## Mobile (React Native) ## Mobile (React Native) {#mobile-react-native}
React Developer Tools can be used to inspect apps built with [React Native](https://reactnative.dev/) as well. React Developer Tools can be used to inspect apps built with [React Native](https://reactnative.dev/) as well.
The easiest way to use React Developer Tools is to install it globally: The easiest way to use React Developer Tools is to install it globally:

20
beta/src/pages/learn/reacting-to-input-with-state.md

@ -17,7 +17,7 @@ React uses a declarative way to manipulate the UI. Instead of manipulating indiv
</YouWillLearn> </YouWillLearn>
## How declarative UI compares to imperative ## How declarative UI compares to imperative {#how-declarative-ui-compares-to-imperative}
When you design UI interactions, you probably think about how the UI *changes* in response to user actions. Consider a form that lets the user submit an answer: When you design UI interactions, you probably think about how the UI *changes* in response to user actions. Consider a form that lets the user submit an answer:
@ -140,7 +140,7 @@ In React, you don't directly manipulate the UI--meaning you don't enable, disabl
<Illustration src="/images/docs/illustrations/i_declarative-ui-programming.png" alt="In a car driven by React, a passenger asks to be taken to a specific place on the map. React figures out how to do that." /> <Illustration src="/images/docs/illustrations/i_declarative-ui-programming.png" alt="In a car driven by React, a passenger asks to be taken to a specific place on the map. React figures out how to do that." />
## Thinking about UI declaratively ## Thinking about UI declaratively {#thinking-about-ui-declaratively}
You've seen how to implement a form imperatively above. To better understand how to think in React, you'll walk through reimplementing this UI in React below: You've seen how to implement a form imperatively above. To better understand how to think in React, you'll walk through reimplementing this UI in React below:
@ -150,7 +150,7 @@ You've seen how to implement a form imperatively above. To better understand how
4. **Remove** any non-essential state variables 4. **Remove** any non-essential state variables
5. **Connect** the event handlers to set the state 5. **Connect** the event handlers to set the state
### Step 1: Identify your component's different visual states ### Step 1: Identify your component's different visual states {#step-1-identify-your-components-different-visual-states}
In computer science, you may hear about a ["state machine"](https://en.wikipedia.org/wiki/Finite-state_machine) being in one of several “states”. If you work with a designer, you may have seen mockups for different "visual states". React stands at the intersection of design and computer science, so both of these ideas are sources of inspiration. In computer science, you may hear about a ["state machine"](https://en.wikipedia.org/wiki/Finite-state_machine) being in one of several “states”. If you work with a designer, you may have seen mockups for different "visual states". React stands at the intersection of design and computer science, so both of these ideas are sources of inspiration.
@ -310,7 +310,7 @@ Pages like this are often called "living styleguides" or "storybooks."
</DeepDive> </DeepDive>
### Step 2: Determine what triggers those state changes ### Step 2: Determine what triggers those state changes {#step-2-determine-what-triggers-those-state-changes}
<IllustrationBlock title="Types of inputs"> <IllustrationBlock title="Types of inputs">
<Illustration caption="Human inputs" alt="A finger." src="/images/docs/illustrations/i_inputs1.png" /> <Illustration caption="Human inputs" alt="A finger." src="/images/docs/illustrations/i_inputs1.png" />
@ -335,7 +335,7 @@ To help visualize this flow, try drawing each state on paper as a labeled circle
<img alt="A flow chart showing states and transitions between them" src="/images/docs/sketches/s_flow-chart.jpg" /> <img alt="A flow chart showing states and transitions between them" src="/images/docs/sketches/s_flow-chart.jpg" />
### Step 3: Represent the state in memory with `useState` ### Step 3: Represent the state in memory with `useState` {#step-3-represent-the-state-in-memory-with-usestate}
Next you'll need to represent the visual states of your component in memory with [`useState`](/reference/usestate). Simplicity is key: each piece of state is a "moving piece", and **you want as few "moving pieces" as possible**. More complexity leads to more bugs! Next you'll need to represent the visual states of your component in memory with [`useState`](/reference/usestate). Simplicity is key: each piece of state is a "moving piece", and **you want as few "moving pieces" as possible**. More complexity leads to more bugs!
@ -360,7 +360,7 @@ const [isError, setIsError] = useState(false);
Your first idea likely won't be the best, but that's ok--refactoring state is a part of the process! Your first idea likely won't be the best, but that's ok--refactoring state is a part of the process!
### Step 4: Remove any non-essential state variables ### Step 4: Remove any non-essential state variables {#step-4-remove-any-non-essential-state-variables}
You want to avoid duplication in the state content so you're only tracking what is essential. Spending a little time on refactoring your state structure will make your components easier to understand, reduce duplication, and avoid unintended meanings. Your goal is to **prevent the cases where the state in memory doesn't represent any valid UI that you'd want a user to see.** (For example, you never want to show an error message and disable the input at the same time, or the user won't be able to correct the error!) You want to avoid duplication in the state content so you're only tracking what is essential. Spending a little time on refactoring your state structure will make your components easier to understand, reduce duplication, and avoid unintended meanings. Your goal is to **prevent the cases where the state in memory doesn't represent any valid UI that you'd want a user to see.** (For example, you never want to show an error message and disable the input at the same time, or the user won't be able to correct the error!)
@ -386,7 +386,7 @@ These three variables are a good enough representation of this form's state. How
</DeepDive> </DeepDive>
### Step 5: Connect the event handlers to set state ### Step 5: Connect the event handlers to set state {#step-5-connect-the-event-handlers-to-set-state}
Lastly, create event handlers to set the state variables. Below is the final form, with all event handlers wired up: Lastly, create event handlers to set the state variables. Below is the final form, with all event handlers wired up:
@ -488,7 +488,7 @@ Although this code is longer than the original imperative example, it is much le
<Challenges> <Challenges>
### Add and remove a CSS class ### Add and remove a CSS class {#add-and-remove-a-css-class}
Make it so that clicking on the picture *removes* the `background--active` CSS class from the outer `<div>`, but *adds* the `picture--active` class to the `<img>`. Clicking the background again should restore the original CSS classes. Make it so that clicking on the picture *removes* the `background--active` CSS class from the outer `<div>`, but *adds* the `picture--active` class to the `<img>`. Clicking the background again should restore the original CSS classes.
@ -686,7 +686,7 @@ Keep in mind that if two different JSX chunks describe the same tree, their nest
</Solution> </Solution>
### Profile editor ### Profile editor {#profile-editor}
Here is a small form implemented with plain JavaScript and DOM. Play with it to understand its behavior: Here is a small form implemented with plain JavaScript and DOM. Play with it to understand its behavior:
@ -888,7 +888,7 @@ Compare this solution to the original imperative code. How are they different?
</Solution> </Solution>
### Refactor the imperative solution without React ### Refactor the imperative solution without React {#refactor-the-imperative-solution-without-react}
Here is the original sandbox from the previous challenge, written imperatively without React: Here is the original sandbox from the previous challenge, written imperatively without React:

20
beta/src/pages/learn/referencing-values-with-refs.md

@ -18,7 +18,7 @@ When you want a component to "remember" some information, but you don't want tha
</YouWillLearn> </YouWillLearn>
## Adding a ref to your component ## Adding a ref to your component {#adding-a-ref-to-your-component}
You can add a ref to your component by importing the `useRef` Hook from React: You can add a ref to your component by importing the `useRef` Hook from React:
@ -74,7 +74,7 @@ The ref points to a number, but, like [state](/learn/state-a-components-memory),
Note that **the component doesn't re-render with every increment.** Like state, refs are retained by React between re-renders. However, setting state re-renders a component. Changing a ref does not! Note that **the component doesn't re-render with every increment.** Like state, refs are retained by React between re-renders. However, setting state re-renders a component. Changing a ref does not!
## Example: building a stopwatch ## Example: building a stopwatch {#example-building-a-stopwatch}
You can combine refs and state in a single component. For example, let's make a stopwatch that the user can start or stop by pressing a button. In order to display how much time has passed since the user pressed "Start," you will need to keep track of when the Start button was pressed and what the current time is. **This information is used for rendering, so you'll keep it in state:** You can combine refs and state in a single component. For example, let's make a stopwatch that the user can start or stop by pressing a button. In order to display how much time has passed since the user pressed "Start," you will need to keep track of when the Start button was pressed and what the current time is. **This information is used for rendering, so you'll keep it in state:**
@ -170,7 +170,7 @@ export default function Stopwatch() {
When a piece of information is used for rendering, keep it in state. When a piece of information is only needed by event handlers and changing it doesn't require a re-render, using a ref may be more efficient. When a piece of information is used for rendering, keep it in state. When a piece of information is only needed by event handlers and changing it doesn't require a re-render, using a ref may be more efficient.
## Differences between refs and state ## Differences between refs and state {#differences-between-refs-and-state}
Perhaps you're thinking refs seem less "strict" than state—you can mutate them instead of always having to use a state setting function, for instance. But in most cases, you'll want to use state. Refs are an "escape hatch" you won't need often. Here's how state and refs compare: Perhaps you're thinking refs seem less "strict" than state—you can mutate them instead of always having to use a state setting function, for instance. But in most cases, you'll want to use state. Refs are an "escape hatch" you won't need often. Here's how state and refs compare:
@ -252,7 +252,7 @@ React provides a built-in version of `useRef` because it is common enough in pra
</DeepDive> </DeepDive>
## When to use refs ## When to use refs {#when-to-use-refs}
Typically, you will use a ref when your component needs to "step outside" React and communicate with external APIs—often a browser API that won't impact the appearance of the component. Here are a few of these rare situations: Typically, you will use a ref when your component needs to "step outside" React and communicate with external APIs—often a browser API that won't impact the appearance of the component. Here are a few of these rare situations:
@ -262,7 +262,7 @@ Typically, you will use a ref when your component needs to "step outside" React
If your component needs to store some value, but it doesn't impact the rendering logic, choose refs. If your component needs to store some value, but it doesn't impact the rendering logic, choose refs.
## Best practices for refs ## Best practices for refs {#best-practices-for-refs}
Following these principles will make your components more predictable: Following these principles will make your components more predictable:
@ -280,7 +280,7 @@ This is because **the ref itself is a regular JavaScript object,** and so it beh
You also don't need to worry about [avoiding mutation](/learn/updating-objects-in-state) when you work with a ref. As long as the object you're mutating isn't used for rendering, React doesn't care what you do with the ref or its contents. You also don't need to worry about [avoiding mutation](/learn/updating-objects-in-state) when you work with a ref. As long as the object you're mutating isn't used for rendering, React doesn't care what you do with the ref or its contents.
## Refs and the DOM ## Refs and the DOM {#refs-and-the-dom}
You can point a ref to any value. However, the most common use case for a ref is to access a DOM element. For example, this is handy if you want to focus an input programmatically. When you pass a ref to a `ref` attribute in JSX, like `<div ref={myRef}>`, React will put the corresponding DOM element into `myRef.current`. You can read more about this in [Manipulating the DOM with Refs](/learn/manipulating-the-dom-with-refs). You can point a ref to any value. However, the most common use case for a ref is to access a DOM element. For example, this is handy if you want to focus an input programmatically. When you pass a ref to a `ref` attribute in JSX, like `<div ref={myRef}>`, React will put the corresponding DOM element into `myRef.current`. You can read more about this in [Manipulating the DOM with Refs](/learn/manipulating-the-dom-with-refs).
@ -299,7 +299,7 @@ You can point a ref to any value. However, the most common use case for a ref is
<Challenges> <Challenges>
### Fix a broken chat input ### Fix a broken chat input {#fix-a-broken-chat-input}
Type a message and click "Send". You will notice there is a three second delay before you see the "Sent!" alert. During this delay, you can see an "Undo" button. Click it. This "Undo" button is supposed to stop the "Sent!" message from appearing. It does this by calling [`clearTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) for the timeout ID saved during `handleSend`. However, even after "Undo" is clicked, the "Sent!" message still appears. Find why it doesn't work, and fix it. Type a message and click "Send". You will notice there is a three second delay before you see the "Sent!" alert. During this delay, you can see an "Undo" button. Click it. This "Undo" button is supposed to stop the "Sent!" message from appearing. It does this by calling [`clearTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) for the timeout ID saved during `handleSend`. However, even after "Undo" is clicked, the "Sent!" message still appears. Find why it doesn't work, and fix it.
@ -410,7 +410,7 @@ export default function Chat() {
</Solution> </Solution>
### Fix a component failing to re-render ### Fix a component failing to re-render {#fix-a-component-failing-to-re-render}
This button is supposed to toggle between showing "On" and "Off". However, it always shows "Off". What is wrong with this code? Fix it. This button is supposed to toggle between showing "On" and "Off". However, it always shows "Off". What is wrong with this code? Fix it.
@ -460,7 +460,7 @@ export default function Toggle() {
</Solution> </Solution>
### Fix debouncing ### Fix debouncing {#fix-debouncing}
In this example, all button click handlers are ["debounced"](https://redd.one/blog/debounce-vs-throttle). To see what this means, press one of the buttons. Notice how the message appears a second later. If you press the button while waiting for the message, the timer will reset. So if you keep clicking the same button fast many times, the message won't appear until a second *after* you stop clicking. Debouncing lets you delay some action until the user "stops doing things". In this example, all button click handlers are ["debounced"](https://redd.one/blog/debounce-vs-throttle). To see what this means, press one of the buttons. Notice how the message appears a second later. If you press the button while waiting for the message, the timer will reset. So if you keep clicking the same button fast many times, the message won't appear until a second *after* you stop clicking. Debouncing lets you delay some action until the user "stops doing things".
@ -577,7 +577,7 @@ button { display: block; margin: 10px; }
</Solution> </Solution>
### Read the latest state ### Read the latest state {#read-the-latest-state}
In this example, after you press "Send", there is a small delay before the message is shown. Type "hello", press Send, and then quickly edit the input again. Despite your edits, the alert would still show "hello" (which was the value of state [at the time](/learn/state-as-a-snapshot#state-over-time) the button was clicked). In this example, after you press "Send", there is a small delay before the message is shown. Type "hello", press Send, and then quickly edit the input again. Despite your edits, the alert would still show "hello" (which was the value of state [at the time](/learn/state-as-a-snapshot#state-over-time) the button was clicked).

12
beta/src/pages/learn/render-and-commit.md

@ -30,14 +30,14 @@ Imagine that your components are cooks in the kitchen, assembling tasty dishes f
<Illustration caption="Commit" alt="React delivers the Card to the user at their table." src="/images/docs/illustrations/i_render-and-commit3.png" /> <Illustration caption="Commit" alt="React delivers the Card to the user at their table." src="/images/docs/illustrations/i_render-and-commit3.png" />
</IllustrationBlock> </IllustrationBlock>
## Step 1: Trigger a render ## Step 1: Trigger a render {#step-1-trigger-a-render}
There are two reasons for a component to render: There are two reasons for a component to render:
1. It's the component's **initial render.** 1. It's the component's **initial render.**
2. The component's **state has been updated.** 2. The component's **state has been updated.**
### Initial render ### Initial render {#initial-render}
When your app starts, you need to trigger the initial render. Frameworks and sandboxes sometimes hide this code, but it's done by calling `ReactDOM.render` with your root component and the target DOM node: When your app starts, you need to trigger the initial render. Frameworks and sandboxes sometimes hide this code, but it's done by calling `ReactDOM.render` with your root component and the target DOM node:
@ -68,7 +68,7 @@ export default function Image() {
Try commenting out the `ReactDOM.render` call and see the component disappear! Try commenting out the `ReactDOM.render` call and see the component disappear!
### Re-renders when state updates ### Re-renders when state updates {#re-renders-when-state-updates}
Once the component has been initially rendered, you can trigger further renders by updating its state with [`setState`](reference/setstate). Updating your component's state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.) Once the component has been initially rendered, you can trigger further renders by updating its state with [`setState`](reference/setstate). Updating your component's state automatically queues a render. (You can imagine these as a restaurant guest ordering tea, dessert, and all sorts of things after putting in their first order, depending on the state of their thirst or hunger.)
@ -78,7 +78,7 @@ Once the component has been initially rendered, you can trigger further renders
<Illustration caption="...render!" alt="The Card Chef gives React the pink Card." src="/images/docs/illustrations/i_rerender3.png" /> <Illustration caption="...render!" alt="The Card Chef gives React the pink Card." src="/images/docs/illustrations/i_rerender3.png" />
</IllustrationBlock> </IllustrationBlock>
## Step 2: React renders your components ## Step 2: React renders your components {#step-2-react-renders-your-components}
After you trigger a render, React calls your components to figure out what to display on screen. **"Rendering" is React calling your components.** After you trigger a render, React calls your components to figure out what to display on screen. **"Rendering" is React calling your components.**
@ -149,7 +149,7 @@ The default behavior of rendering all components nested within the updated compo
</DeepDive> </DeepDive>
## Step 3: React commits changes to the DOM ## Step 3: React commits changes to the DOM {#step-3-react-commits-changes-to-the-dom}
After rendering (calling) your components, React will modify the DOM. After rendering (calling) your components, React will modify the DOM.
@ -197,7 +197,7 @@ export default function App() {
</Sandpack> </Sandpack>
This works because during this last step, React only updates the content of `<h1>` with the new `time`. It sees that the `<input>` appears in the JSX in the same place as last time, so React doesn't touch the `<input>`—or its `value`! This works because during this last step, React only updates the content of `<h1>` with the new `time`. It sees that the `<input>` appears in the JSX in the same place as last time, so React doesn't touch the `<input>`—or its `value`!
## Epilogue: Browser paint ## Epilogue: Browser paint {#epilogue-browser-paint}
After rendering is done and React updated the DOM, the browser will repaint the screen. Although this process is known as "browser rendering", we'll refer to it as "painting" to avoid confusion in the rest of these docs. After rendering is done and React updated the DOM, the browser will repaint the screen. Although this process is known as "browser rendering", we'll refer to it as "painting" to avoid confusion in the rest of these docs.

20
beta/src/pages/learn/rendering-lists.md

@ -17,7 +17,7 @@ You will often want to display multiple similar components from a collection of
</YouWillLearn> </YouWillLearn>
## Rendering data from arrays ## Rendering data from arrays {#rendering-data-from-arrays}
Say that you have a list of content. Say that you have a list of content.
@ -86,7 +86,7 @@ li { margin-bottom: 10px; }
</Sandpack> </Sandpack>
## Filtering arrays of items ## Filtering arrays of items {#filtering-arrays-of-items}
This data can be structured even more. This data can be structured even more.
@ -255,7 +255,7 @@ Arrow functions containing `=> {` are said to have a ["block body"](https://deve
</Gotcha> </Gotcha>
## Keeping list items in order with `key` ## Keeping list items in order with `key` {#keeping-list-items-in-order-with-key}
If you open any of the sandboxes above in a new tab, you'll see an error in the console: If you open any of the sandboxes above in a new tab, you'll see an error in the console:
@ -386,19 +386,19 @@ Fragments disappear from the DOM, so this will produce a flat list of `<h1>`, `<
</DeepDive> </DeepDive>
### Where to get your `key` ### Where to get your `key` {#where-to-get-your-key}
Different sources of data provide different sources of keys: Different sources of data provide different sources of keys:
* **Data from a database:** If your data is coming from a database, you can use the database keys/IDs, which are unique by nature. * **Data from a database:** If your data is coming from a database, you can use the database keys/IDs, which are unique by nature.
* **Locally generated data:** If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter or a package like [`uuid`](https://www.npmjs.com/package/uuid) when creating items. * **Locally generated data:** If your data is generated and persisted locally (e.g. notes in a note-taking app), use an incrementing counter or a package like [`uuid`](https://www.npmjs.com/package/uuid) when creating items.
### Rules of keys ### Rules of keys {#rules-of-keys}
* **Keys must be unique among siblings.** However, it’s okay to use the same keys for JSX nodes in _different_ arrays. * **Keys must be unique among siblings.** However, it’s okay to use the same keys for JSX nodes in _different_ arrays.
* **Keys must not change** or that defeats their purpose! Don't generate them while rendering. * **Keys must not change** or that defeats their purpose! Don't generate them while rendering.
### Why does React need keys? ### Why does React need keys? {#why-does-react-need-keys}
Imagine that files on your desktop didn't have names. Instead, you'd refer to them by their order -- the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on. Imagine that files on your desktop didn't have names. Instead, you'd refer to them by their order -- the first file, the second file, and so on. You could get used to it, but once you delete a file, it would get confusing. The second file would become the first file, the third file would be the second file, and so on.
@ -429,7 +429,7 @@ On this page you learned:
<Challenges> <Challenges>
### Splitting a list in two ### Splitting a list in two {#splitting-a-list-in-two}
This example shows a list of all people. This example shows a list of all people.
@ -871,7 +871,7 @@ img { width: 100px; height: 100px; border-radius: 50%; }
</Solution> </Solution>
### Nested lists in one component ### Nested lists in one component {#nested-lists-in-one-component}
Make a list of recipes from this array! For each recipe in the array, display its title as an `<h2>` and list its ingredients in a `<ul>`. Make a list of recipes from this array! For each recipe in the array, display its title as an `<h2>` and list its ingredients in a `<ul>`.
@ -965,7 +965,7 @@ Each of the `recipes` already includes an `id` field, so that's what the outer l
</Solution> </Solution>
### Extracting a list item component ### Extracting a list item component {#extracting-a-list-item-component}
This `RecipeList` component contains two nested `map` calls. To simplify it, extract a `Recipe` component from it which will accept `id`, `name`, and `ingredients` props. Where do you place the outer `key` and why? This `RecipeList` component contains two nested `map` calls. To simplify it, extract a `Recipe` component from it which will accept `id`, `name`, and `ingredients` props. Where do you place the outer `key` and why?
@ -1073,7 +1073,7 @@ Here, `<Recipe {...recipe} key={recipe.id} />` is a syntax shortcut saying "pass
</Solution> </Solution>
### List with a separator ### List with a separator {#list-with-a-separator}
This example renders a famous haiku by Katsushika Hokusai, with each line wrapped in a `<p>` tag. Your job is to insert an `<hr />` separator between each paragraph. Your resulting structure should look like this: This example renders a famous haiku by Katsushika Hokusai, with each line wrapped in a `<p>` tag. Your job is to insert an `<hr />` separator between each paragraph. Your resulting structure should look like this:

22
beta/src/pages/learn/responding-to-events.md

@ -17,7 +17,7 @@ React lets you add event handlers to your JSX. Event handlers are your own funct
</YouWillLearn> </YouWillLearn>
## Adding event handlers ## Adding event handlers {#adding-event-handlers}
To add an event handler, you will first define a function and then [pass it as a prop](/learn/passing-props-to-a-component) to the appropriate JSX tag. For example, here is a button that doesn't do anything yet: To add an event handler, you will first define a function and then [pass it as a prop](/learn/passing-props-to-a-component) to the appropriate JSX tag. For example, here is a button that doesn't do anything yet:
@ -131,7 +131,7 @@ In both cases, what you want to pass is a function:
</Gotcha> </Gotcha>
### Reading props in event handlers ### Reading props in event handlers {#reading-props-in-event-handlers}
Because event handlers are declared inside of a component, they have access to the component's props. Here is a button that, when clicked, shows an alert with its `message` prop: Because event handlers are declared inside of a component, they have access to the component's props. Here is a button that, when clicked, shows an alert with its `message` prop:
@ -168,7 +168,7 @@ button { margin-right: 10px; }
This lets these two buttons show different messages. Try changing the messages passed to them. This lets these two buttons show different messages. Try changing the messages passed to them.
### Passing event handlers as props ### Passing event handlers as props {#passing-event-handlers-as-props}
Often you'll want the parent component to specify a child's event handler. Consider buttons: depending on where you're using a `Button` component, you might want to execute a different function—perhaps one plays a movie and another uploads an image. Often you'll want the parent component to specify a child's event handler. Consider buttons: depending on where you're using a `Button` component, you might want to execute a different function—perhaps one plays a movie and another uploads an image.
@ -230,7 +230,7 @@ Finally, your `Button` component accepts a prop called `onClick`. It passes that
If you use a [design system](https://uxdesign.cc/everything-you-need-to-know-about-design-systems-54b109851969), it's common for components like buttons to contain styling but not specify behavior. Instead, components like `PlayButton` and `UploadButton` will pass event handlers down. If you use a [design system](https://uxdesign.cc/everything-you-need-to-know-about-design-systems-54b109851969), it's common for components like buttons to contain styling but not specify behavior. Instead, components like `PlayButton` and `UploadButton` will pass event handlers down.
### Naming event handler props ### Naming event handler props {#naming-event-handler-props}
Built-in components like `<button>` and `<div>` only support [browser event names](/reference/reactdom-api) like `onClick`. However, when you're building your own components, you can name their event handler props any way that you like. Built-in components like `<button>` and `<div>` only support [browser event names](/reference/reactdom-api) like `onClick`. However, when you're building your own components, you can name their event handler props any way that you like.
@ -315,7 +315,7 @@ button { margin-right: 10px; }
Notice how the `App` component does not need to know *what* `Toolbar` will do with `onPlayMovie` or `onUploadImage`. That's an implementation detail of the `Toobar`. Here, `Toolbar` passes them down as `onClick` handlers to its `Button`s, but it could later also trigger them on a keyboard shortcut. Naming props after app-specific interactions like `onPlayMovie` gives you the flexibility to change how they're used later. Notice how the `App` component does not need to know *what* `Toolbar` will do with `onPlayMovie` or `onUploadImage`. That's an implementation detail of the `Toobar`. Here, `Toolbar` passes them down as `onClick` handlers to its `Button`s, but it could later also trigger them on a keyboard shortcut. Naming props after app-specific interactions like `onPlayMovie` gives you the flexibility to change how they're used later.
## Event propagation ## Event propagation {#event-propagation}
<!-- <!--
// TODO illo // TODO illo
@ -362,7 +362,7 @@ All events propagate in React except `onScroll`, which only works on the JSX tag
</Gotcha> </Gotcha>
### Stopping propagation ### Stopping propagation {#stopping-propagation}
Event handlers receive an **event object** as their only argument. By convention, it's usually called `e`, which stands for "event." You can use this object to read information about the event. Event handlers receive an **event object** as their only argument. By convention, it's usually called `e`, which stands for "event." You can use this object to read information about the event.
@ -444,7 +444,7 @@ Capture events are useful for code like routers or analytics, but you probably w
</DeepDive> </DeepDive>
### Passing handlers as alternative to propagation ### Passing handlers as alternative to propagation {#passing-handlers-as-alternative-to-propagation}
Notice how this click handler runs a line of code _and then_ calls the `onClick` prop passed by the parent: Notice how this click handler runs a line of code _and then_ calls the `onClick` prop passed by the parent:
@ -465,7 +465,7 @@ You could add more code to this handler before calling the parent `onClick` even
If you rely on propagation and it's difficult to trace which handlers execute and why, try this approach instead. If you rely on propagation and it's difficult to trace which handlers execute and why, try this approach instead.
### Preventing default behavior ### Preventing default behavior {#preventing-default-behavior}
Some browser events have default behavior associated with them. For example, a `<form>` submit event, which happens when a button inside of it is clicked, will reload the whole page by default: Some browser events have default behavior associated with them. For example, a `<form>` submit event, which happens when a button inside of it is clicked, will reload the whole page by default:
@ -517,7 +517,7 @@ Don't confuse `e.stopPropagation()` and `e.preventDefault()`. They are both usef
* [`e.stopPropagation()`](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) stops the event handlers attached to the tags above from firing. * [`e.stopPropagation()`](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) stops the event handlers attached to the tags above from firing.
* [`e.preventDefault()` ](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) prevents the default browser behavior for the few events that have it. * [`e.preventDefault()` ](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) prevents the default browser behavior for the few events that have it.
## Can event handlers have side effects? ## Can event handlers have side effects? {#can-event-handlers-have-side-effects}
Absolutely! Event handlers are the best place for side effects. Absolutely! Event handlers are the best place for side effects.
@ -541,7 +541,7 @@ Unlike rendering functions, event handlers don't need to be [pure](/learn/keepin
<Challenges> <Challenges>
### Fix an event handler ### Fix an event handler {#fix-an-event-handler}
Clicking this button is supposed to switch the page background between white and black. However, nothing happens when you click it. Fix the problem. (Don't worry about the logic inside `handleClick`—that part is fine.) Clicking this button is supposed to switch the page background between white and black. However, nothing happens when you click it. Fix the problem. (Don't worry about the logic inside `handleClick`—that part is fine.)
@ -622,7 +622,7 @@ export default function LightSwitch() {
</Solution> </Solution>
### Wire up the events ### Wire up the events {#wire-up-the-events}
This `ColorSwitch` component renders a button. It's supposed to change the page color. Wire it up to the `onChangeColor` event handler prop it receives from the parent so that clicking the button changes the color. This `ColorSwitch` component renders a button. It's supposed to change the page color. Wire it up to the `onChangeColor` event handler prop it receives from the parent so that clicking the button changes the color.

10
beta/src/pages/learn/scaling-up-with-reducer-and-context.md

@ -17,7 +17,7 @@ Reducers let you consolidate a component's state update logic. Context lets you
</YouWillLearn> </YouWillLearn>
## Combining a reducer with context ## Combining a reducer with context {#combining-a-reducer-with-context}
In this example from [the introduction to reducers](/learn/extracting-state-logic-into-a-reducer), the state is managed by a reducer. The reducer function contains all of the state update logic and is declared at the bottom of this file: In this example from [the introduction to reducers](/learn/extracting-state-logic-into-a-reducer), the state is managed by a reducer. The reducer function contains all of the state update logic and is declared at the bottom of this file:
@ -244,7 +244,7 @@ Here is how you can combine a reducer with context:
2. **Put** state and dispatch into context. 2. **Put** state and dispatch into context.
3. **Use** context anywhere in the tree. 3. **Use** context anywhere in the tree.
### Step 1: Create the context ### Step 1: Create the context {#step-1-create-the-context}
The `useReducer` Hook returns the current `tasks` and the `dispatch` function that lets you update them: The `useReducer` Hook returns the current `tasks` and the `dispatch` function that lets you update them:
@ -455,7 +455,7 @@ ul, li { margin: 0; padding: 0; }
Here, you're passing `null` as the default value to both contexts. The actual values will be provided by the `TaskBoard` component. Here, you're passing `null` as the default value to both contexts. The actual values will be provided by the `TaskBoard` component.
### Step 2: Put state and dispatch into context ### Step 2: Put state and dispatch into context {#step-2-put-state-and-dispatch-into-context}
Now you can import both contexts in your `TaskBoard` component. Take the `tasks` and `dispatch` returned by `useReducer()` and [provide them](/learn/passing-data-deeply-with-context#step-3-provide-the-context) to the entire tree below: Now you can import both contexts in your `TaskBoard` component. Take the `tasks` and `dispatch` returned by `useReducer()` and [provide them](/learn/passing-data-deeply-with-context#step-3-provide-the-context) to the entire tree below:
@ -676,7 +676,7 @@ ul, li { margin: 0; padding: 0; }
In the next step, you will remove prop passing. In the next step, you will remove prop passing.
### Step 3: Use context anywhere in the tree ### Step 3: Use context anywhere in the tree {#step-3-use-context-anywhere-in-the-tree}
Now you don't need to pass the list of tasks or the event handlers down the tree: Now you don't need to pass the list of tasks or the event handlers down the tree:
@ -904,7 +904,7 @@ ul, li { margin: 0; padding: 0; }
**The state still "lives" in the top-level `TaskBoard` component, managed with `useReducer`.** But its `tasks` and `dispatch` are now available to every component below in the tree by importing and using these contexts. **The state still "lives" in the top-level `TaskBoard` component, managed with `useReducer`.** But its `tasks` and `dispatch` are now available to every component below in the tree by importing and using these contexts.
## Moving all wiring into a single file ## Moving all wiring into a single file {#moving-all-wiring-into-a-single-file}
You don't have to do this, but you could further declutter the components by moving both reducer and context into a single file. Currently, `TasksContext.js` contains only two context declarations: You don't have to do this, but you could further declutter the components by moving both reducer and context into a single file. Currently, `TasksContext.js` contains only two context declarations:

14
beta/src/pages/learn/sharing-state-between-components.md

@ -16,7 +16,7 @@ Sometimes, you want the state of two components to always change together. To do
</YouWillLearn> </YouWillLearn>
## Lifting state up by example ## Lifting state up by example {#lifting-state-up-by-example}
In this example, a parent `Accordion` component renders two separate `Panel`s: In this example, a parent `Accordion` component renders two separate `Panel`s:
@ -88,7 +88,7 @@ This will allow the `Accordion` component to coordinate both `Panel`s and only e
<img alt="On the left are two components each owning their own state values. On the right, they are the children of a parent component that owns both their state values." src="/images/docs/sketches/s_lifting-state-up.png" /> <img alt="On the left are two components each owning their own state values. On the right, they are the children of a parent component that owns both their state values." src="/images/docs/sketches/s_lifting-state-up.png" />
### Step 1: Remove state from the child components ### Step 1: Remove state from the child components {#step-1-remove-state-from-the-child-components}
You will give control of the `Panel`'s `isActive` to its parent component. This means that the parent component will pass `isActive` to `Panel` as a prop instead. Start by **removing this line** from the `Panel` component: You will give control of the `Panel`'s `isActive` to its parent component. This means that the parent component will pass `isActive` to `Panel` as a prop instead. Start by **removing this line** from the `Panel` component:
@ -104,7 +104,7 @@ function Panel({ title, children, isActive }) {
Now the `Panel`'s parent component can *control* `isActive` by [passing it down as a prop](/learn/passing-props-to-a-component). Conversely, the `Panel` component now has *no control* over the value of `isActive`--it's now up to the parent component! Now the `Panel`'s parent component can *control* `isActive` by [passing it down as a prop](/learn/passing-props-to-a-component). Conversely, the `Panel` component now has *no control* over the value of `isActive`--it's now up to the parent component!
### Step 2: Pass hardcoded data from the common parent ### Step 2: Pass hardcoded data from the common parent {#step-2-pass-hardcoded-data-from-the-common-parent}
To lift state up, you must locate the closest common parent component of *both* of the child components that you want to coordinate: To lift state up, you must locate the closest common parent component of *both* of the child components that you want to coordinate:
@ -161,7 +161,7 @@ h3, p { margin: 5px 0px; }
Try editing the hardcoded `isActive` values in the `Accordion` component and see the result on the screen. Try editing the hardcoded `isActive` values in the `Accordion` component and see the result on the screen.
### Step 3: Add state to the common parent ### Step 3: Add state to the common parent {#step-3-add-state-to-the-common-parent}
Lifting state up often changes the nature of what you're storing as state. Lifting state up often changes the nature of what you're storing as state.
@ -271,7 +271,7 @@ When writing a component, consider which information in it should be controlled
</DeepDive> </DeepDive>
## A single source of truth for each state ## A single source of truth for each state {#a-single-source-of-truth-for-each-state}
In a React application, many components will have their own state. Some state may "live" close to the leaf components (components at the bottom of the tree) like inputs. Other state may "live" closer to the top of the app. For example, even client-side routing libraries are usually implemented by storing the current route in the React state, and passing it down by props! In a React application, many components will have their own state. Some state may "live" close to the leaf components (components at the bottom of the tree) like inputs. Other state may "live" closer to the top of the app. For example, even client-side routing libraries are usually implemented by storing the current route in the React state, and passing it down by props!
@ -292,7 +292,7 @@ To see what this feels like in practice with a few more components, read [Thinki
<Challenges> <Challenges>
### Synced inputs ### Synced inputs {#synced-inputs}
These two inputs are independent. Make them stay in sync: editing one input should update the other input with the same text, and vice versa. These two inputs are independent. Make them stay in sync: editing one input should update the other input with the same text, and vice versa.
@ -398,7 +398,7 @@ label { display: block; }
</Solution> </Solution>
### Filtering a list ### Filtering a list {#filtering-a-list}
In this example, the `SearchBar` has its own `query` state that controls the text input. Its parent `FilterableList` component displays a `List` of items, but it doesn't take the search query into account. In this example, the `SearchBar` has its own `query` state that controls the text input. Its parent `FilterableList` component displays a `List` of items, but it doesn't take the search query into account.

12
beta/src/pages/learn/start-a-new-react-project.md

@ -9,7 +9,7 @@ If you're learning React or considering adding it to an existing project, you ca
</Intro> </Intro>
## Choose your own adventure ## Choose your own adventure {#choose-your-own-adventure}
React is a library that lets you organize UI code by breaking it apart into pieces called components. React doesn't take care of routing or data management. For these features, you'll want to use third-party libraries or write your own solutions. This means there are several ways to start a new React project: React is a library that lets you organize UI code by breaking it apart into pieces called components. React doesn't take care of routing or data management. For these features, you'll want to use third-party libraries or write your own solutions. This means there are several ways to start a new React project:
@ -18,7 +18,7 @@ React is a library that lets you organize UI code by breaking it apart into piec
Whether you're just getting started, looking to build something big, or want to set up your own toolchain, this guide will set you on the right path. Whether you're just getting started, looking to build something big, or want to set up your own toolchain, this guide will set you on the right path.
## Getting started with a React toolchain ## Getting started with a React toolchain {#getting-started-with-a-react-toolchain}
If you're just getting started with React, we recommend [Create React App](https://create-react-app.dev/), the most popular way to try out React's features and a great way to build a new single-page, client-side application. Create React App is an unopinionated toolchain configured just for React. Toolchains help with things like: If you're just getting started with React, we recommend [Create React App](https://create-react-app.dev/), the most popular way to try out React's features and a great way to build a new single-page, client-side application. Create React App is an unopinionated toolchain configured just for React. Toolchains help with things like:
@ -49,7 +49,7 @@ For more information, [check out the official guide](https://create-react-app.de
> Create React App doesn't handle backend logic or databases; it just creates a frontend build pipeline. This means you can use it with any backend you want. But if you're looking for more features like routing and server-side logic, read on! > Create React App doesn't handle backend logic or databases; it just creates a frontend build pipeline. This means you can use it with any backend you want. But if you're looking for more features like routing and server-side logic, read on!
### Other options ### Other options {#other-options}
Create React App is great to get started working with React, but if you'd like an even lighter toolchain, you might try one of these other popular toolchains: Create React App is great to get started working with React, but if you'd like an even lighter toolchain, you might try one of these other popular toolchains:
@ -57,18 +57,18 @@ Create React App is great to get started working with React, but if you'd like a
* [Parcel](https://parceljs.org/) * [Parcel](https://parceljs.org/)
* [Snowpack](https://www.snowpack.dev/tutorials/react) * [Snowpack](https://www.snowpack.dev/tutorials/react)
## Building with React and a framework ## Building with React and a framework {#building-with-react-and-a-framework}
If you're looking to start a bigger, production-ready project, [Next.js](https://nextjs.org/) is a great place to start. Next.js is a popular, lightweight framework for static and server‑rendered applications built with React. It comes pre-packaged with features like routing, styling, and server-side rendering, getting your project up and running quickly. If you're looking to start a bigger, production-ready project, [Next.js](https://nextjs.org/) is a great place to start. Next.js is a popular, lightweight framework for static and server‑rendered applications built with React. It comes pre-packaged with features like routing, styling, and server-side rendering, getting your project up and running quickly.
[Get started building with Next.js](https://nextjs.org/docs/getting-started) with the official guide. [Get started building with Next.js](https://nextjs.org/docs/getting-started) with the official guide.
### Other options ### Other options {#other-options-1}
* [Gatsby](https://www.gatsbyjs.org/) lets you generate static websites with React with GraphQL. * [Gatsby](https://www.gatsbyjs.org/) lets you generate static websites with React with GraphQL.
* [Razzle](https://razzlejs.org/) is a server-rendering framework that doesn't require any configuration, but offers more flexibility than Next.js. * [Razzle](https://razzlejs.org/) is a server-rendering framework that doesn't require any configuration, but offers more flexibility than Next.js.
## Custom toolchains ## Custom toolchains {#custom-toolchains}
You may prefer to create and configure your own toolchain. A JavaScript build toolchain typically consists of: You may prefer to create and configure your own toolchain. A JavaScript build toolchain typically consists of:

20
beta/src/pages/learn/state-a-components-memory.md

@ -18,7 +18,7 @@ Components often need to change what's on the screen as a result of an interacti
</YouWillLearn> </YouWillLearn>
## When a regular variable isn’t enough ## When a regular variable isn’t enough {#when-a-regular-variable-isnt-enough}
Here's a component that renders a sculpture image. Clicking the "Next" button should show the next sculpture by changing the `index` to `1`, then `2`, and so on. However, this **won't work** (you can try it!): Here's a component that renders a sculpture image. Clicking the "Next" button should show the next sculpture by changing the `index` to `1`, then `2`, and so on. However, this **won't work** (you can try it!):
@ -167,7 +167,7 @@ The [`useState`](/reference/usestate) Hook provides those two things:
1. A **state variable** to retain the data between renders. 1. A **state variable** to retain the data between renders.
2. A **state setter function** to update the variable and trigger React to render the component again. 2. A **state setter function** to update the variable and trigger React to render the component again.
## Adding a state variable ## Adding a state variable {#adding-a-state-variable}
To add a state variable, import `useState` from React at the top of the file: To add a state variable, import `useState` from React at the top of the file:
@ -332,7 +332,7 @@ button {
</Sandpack> </Sandpack>
### Meet your first Hook ### Meet your first Hook {#meet-your-first-hook}
In React, `useState`, as well as any other function starting with "`use`," is called a **Hook**. In React, `useState`, as well as any other function starting with "`use`," is called a **Hook**.
@ -346,7 +346,7 @@ State is just one of those features, but you will meet the other Hooks later.
</Gotcha> </Gotcha>
### Anatomy of `useState` ### Anatomy of `useState` {#anatomy-of-usestate}
When you call [`useState`](/reference/usestate), you are telling React that you want this component to remember something: When you call [`useState`](/reference/usestate), you are telling React that you want this component to remember something:
@ -376,7 +376,7 @@ const [index, setIndex] = useState(0);
3. **Your component's second render.** React still sees `useState(0)`, but because React *remembers* that you set `index` to `1`, it returns `[1, setIndex]` instead. 3. **Your component's second render.** React still sees `useState(0)`, but because React *remembers* that you set `index` to `1`, it returns `[1, setIndex]` instead.
4. And so on! 4. And so on!
## Giving a component multiple state variables ## Giving a component multiple state variables {#giving-a-component-multiple-state-variables}
You can have as many state variables of as many types as you like in one component. This component has two state variables, a number `index` and a boolean `showMore` that's toggled when you click "Show details": You can have as many state variables of as many types as you like in one component. This component has two state variables, a number `index` and a boolean `showMore` that's toggled when you click "Show details":
@ -723,7 +723,7 @@ You don't have to understand it to use React, but you might find this a helpful
</DeepDive> </DeepDive>
## State is isolated and private ## State is isolated and private {#state-is-isolated-and-private}
State is local to a component instance on the screen. In other words, **if you render the same component twice, each copy will have completely isolated state!** Changing one of them will not affect the other. State is local to a component instance on the screen. In other words, **if you render the same component twice, each copy will have completely isolated state!** Changing one of them will not affect the other.
@ -908,7 +908,7 @@ What if you wanted both galleries to keep their states in sync? The right way to
<Challenges> <Challenges>
### Complete the gallery ### Complete the gallery {#complete-the-gallery}
When you press "Next" on the last sculpture, the code crashes. Fix the logic to prevent the crash. You may do this by adding extra logic to event handler or by disabling the button when the action is not possible. When you press "Next" on the last sculpture, the code crashes. Fix the logic to prevent the crash. You may do this by adding extra logic to event handler or by disabling the button when the action is not possible.
@ -1218,7 +1218,7 @@ Notice how `hasPrev` and `hasNext` are used *both* for the returned JSX and insi
</Solution> </Solution>
### Fix stuck form inputs ### Fix stuck form inputs {#fix-stuck-form-inputs}
When you type into the input fields, nothing appears. It's like the input values are "stuck" with empty strings. The `value` of the first `<input>` is set to always match the `firstName` variable, and the `value` for the second `<input>` is set to always match the `lastName` variable. This is correct. Both inputs have `onChange` event handlers, which try to update the variables based on the latest user input (`e.target.value`). However, the variables don't seem to "remember" their values between re-renders. Fix this by using state variables instead. When you type into the input fields, nothing appears. It's like the input values are "stuck" with empty strings. The `value` of the first `<input>` is set to always match the `firstName` variable, and the `value` for the second `<input>` is set to always match the `lastName` variable. This is correct. Both inputs have `onChange` event handlers, which try to update the variables based on the latest user input (`e.target.value`). However, the variables don't seem to "remember" their values between re-renders. Fix this by using state variables instead.
@ -1320,7 +1320,7 @@ h1 { margin-top: 10px; }
</Solution> </Solution>
### Fix a crash ### Fix a crash {#fix-a-crash}
Here is a small form that is supposed to let the user leave some feedback. When the feedback is submitted, it's supposed to display a thank-you message. However, it crashes with an error message saying "Rendered fewer hooks than expected". Can you spot the mistake and fix it? Here is a small form that is supposed to let the user leave some feedback. When the feedback is submitted, it's supposed to display a thank-you message. However, it crashes with an error message saying "Rendered fewer hooks than expected". Can you spot the mistake and fix it?
@ -1442,7 +1442,7 @@ In general, these types of mistakes are caught by the [`eslint-plugin-react-hook
</Solution> </Solution>
### Remove unnecessary state ### Remove unnecessary state {#remove-unnecessary-state}
When the button is clicked, this example should ask for the user's name and then display an alert gretting them. You tried to use state to keep the name, but for some reason it always shows "Hello, !". When the button is clicked, this example should ask for the user's name and then display an alert gretting them. You tried to use state to keep the name, but for some reason it always shows "Hello, !".

8
beta/src/pages/learn/state-as-a-snapshot.md

@ -18,7 +18,7 @@ State variables might look like regular JavaScript variables that you can read a
</YouWillLearn> </YouWillLearn>
## Setting state triggers renders ## Setting state triggers renders {#setting-state-triggers-renders}
You might think of your user interface as changing directly in response to the user input like a click. This may feel intuitive if you've been [storyboarding](https://wikipedia.org/wiki/Storyboard) your designs and interactions: You might think of your user interface as changing directly in response to the user input like a click. This may feel intuitive if you've been [storyboarding](https://wikipedia.org/wiki/Storyboard) your designs and interactions:
@ -78,7 +78,7 @@ Let's take a closer look at the relationship between state and rendering.
<Illustration alt="State living in React; React gets a setUpdate; in the re-render, React passes a snapshot of the state value into the component." src="/images/docs/illustrations/i_ui-snapshot.png" /> <Illustration alt="State living in React; React gets a setUpdate; in the re-render, React passes a snapshot of the state value into the component." src="/images/docs/illustrations/i_ui-snapshot.png" />
## Rendering takes a snapshot in time ## Rendering takes a snapshot in time {#rendering-takes-a-snapshot-in-time}
["Rendering"](/learn/render-and-commit#step-2-react-renders-your-components) means that React is calling your component, which is a function. The JSX you return from that function is like a snapshot of the UI in time. Its props, event handlers, and local variables were all calculated **using its state at the time of the render.** ["Rendering"](/learn/render-and-commit#step-2-react-renders-your-components) means that React is calling your component, which is a function. The JSX you return from that function is like a snapshot of the UI in time. Its props, event handlers, and local variables were all calculated **using its state at the time of the render.**
@ -181,7 +181,7 @@ For the next render, `number` is `1`, so *that render's* click handler looks lik
This is why clicking the button again will set the counter to `2`, then to `3` on the next click, and so on. This is why clicking the button again will set the counter to `2`, then to `3` on the next click, and so on.
## State over time ## State over time {#state-over-time}
Well, that was fun. Try to guess what clicking this button will alert: Well, that was fun. Try to guess what clicking this button will alert:
@ -334,7 +334,7 @@ But what if you wanted to read the latest state before a re-render? You'll want
<Challenges> <Challenges>
### Implement a traffic light ### Implement a traffic light {#implement-a-traffic-light}
Here is a crosswalk light component that toggles on when the button is pressed: Here is a crosswalk light component that toggles on when the button is pressed:

14
beta/src/pages/learn/thinking-in-react.md

@ -9,7 +9,7 @@ React can change how you think about the designs you look at and the apps you bu
</Intro> </Intro>
## Start with the mockup ## Start with the mockup {#start-with-the-mockup}
Imagine that you already have a JSON API and a mockup from a designer. Imagine that you already have a JSON API and a mockup from a designer.
@ -32,7 +32,7 @@ The mockup looks like this:
To implement a UI in React, you will usually follow the same five steps. To implement a UI in React, you will usually follow the same five steps.
## Step 1: Break the UI into a component hierarchy ## Step 1: Break the UI into a component hierarchy {#step-1-break-the-ui-into-a-component-hierarchy}
Start by drawing boxes around every component and subcomponent in the mockup and naming them. If you work with a designer, they may have already named these components in their design tool. Check in with them! Start by drawing boxes around every component and subcomponent in the mockup and naming them. If you work with a designer, they may have already named these components in their design tool. Check in with them!
@ -72,7 +72,7 @@ Now that you've identified the components in the mockup, arrange them into a hie
* `ProductCategoryRow` * `ProductCategoryRow`
* `ProductRow` * `ProductRow`
## Step 2: Build a static version in React ## Step 2: Build a static version in React {#step-2-build-a-static-version-in-react}
Now that you have your component hierarchy, it's time to implement your app. The most straightforward approach is to build a version that renders the UI from your data model without adding any interactivity... yet! It's often easier to build the static version first and then add interactivity separately. Building a static version requires a lot of typing and no thinking, but adding interactivity requires a lot of thinking and not a lot of typing. Now that you have your component hierarchy, it's time to implement your app. The most straightforward approach is to build a version that renders the UI from your data model without adding any interactivity... yet! It's often easier to build the static version first and then add interactivity separately. Building a static version requires a lot of typing and no thinking, but adding interactivity requires a lot of thinking and not a lot of typing.
@ -206,7 +206,7 @@ At this point, you should not be using any state values. That’s for the next s
</Gotcha> </Gotcha>
## Step 3: Find the minimal but complete representation of UI state ## Step 3: Find the minimal but complete representation of UI state {#step-3-find-the-minimal-but-complete-representation-of-ui-state}
To make the UI interactive, you need to let users change your underlying data model. You will use *state* for this. To make the UI interactive, you need to let users change your underlying data model. You will use *state* for this.
@ -247,7 +247,7 @@ Props and state are different, but they work together. A parent component will o
</DeepDive> </DeepDive>
## Step 4: Identify where your state should live ## Step 4: Identify where your state should live {#step-4-identify-where-your-state-should-live}
After identifying your app’s minimal state data, you need to identify which component is responsible for changing this state, or *owns* the state. Remember: React uses one-way data flow, passing data down the component hierarchy from parent to child component. It may not be immediately clear which component should own what state. This can be challenging if you’re new to this concept, but you can figure it out by following these steps! After identifying your app’s minimal state data, you need to identify which component is responsible for changing this state, or *owns* the state. Remember: React uses one-way data flow, passing data down the component hierarchy from parent to child component. It may not be immediately clear which component should own what state. This can be challenging if you’re new to this concept, but you can figure it out by following these steps!
@ -451,7 +451,7 @@ function SearchBar({ filterText, inStockOnly }) {
Refer to the [Managing State](/learn/managing-state) to dive deeper into how React uses state and how you can organize your app with it. Refer to the [Managing State](/learn/managing-state) to dive deeper into how React uses state and how you can organize your app with it.
## Step 5: Add inverse data flow ## Step 5: Add inverse data flow {#step-5-add-inverse-data-flow}
Currently your app renders correctly with props and state flowing down the hierarchy. But to change the state according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`. Currently your app renders correctly with props and state flowing down the hierarchy. But to change the state according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
@ -635,6 +635,6 @@ td {
You can learn all about handling events and updating state in the [Adding Interactivity](/learn/adding-interactivity) section. You can learn all about handling events and updating state in the [Adding Interactivity](/learn/adding-interactivity) section.
## Where to go from here ## Where to go from here {#where-to-go-from-here}
This was a very brief introduction to how to think about building components and applications with React. You can [start a React project](/learn/installation) right now or [dive deeper on all the syntax](/learn/describing-the-ui) used in this tutorial. This was a very brief introduction to how to think about building components and applications with React. You can [start a React project](/learn/installation) right now or [dive deeper on all the syntax](/learn/describing-the-ui) used in this tutorial.

26
beta/src/pages/learn/updating-arrays-in-state.md

@ -17,7 +17,7 @@ Arrays are another type of mutable JavaScript objects you can store in state and
</YouWillLearn> </YouWillLearn>
## Updating arrays without mutation ## Updating arrays without mutation {#updating-arrays-without-mutation}
In JavaScript, arrays are just another kind of object. [Like with objects](/learn/updating-objects-in-state), **you should treat arrays in React state as read-only**. This means that you shouldn't reassign items inside an array like `arr[0] = 'bird'`, and you also shouldn't use methods that mutate the array, such as `push()` and `pop()`. In JavaScript, arrays are just another kind of object. [Like with objects](/learn/updating-objects-in-state), **you should treat arrays in React state as read-only**. This means that you shouldn't reassign items inside an array like `arr[0] = 'bird'`, and you also shouldn't use methods that mutate the array, such as `push()` and `pop()`.
@ -45,7 +45,7 @@ In React, you will be using `slice` (no `p`!) a lot more often because you don't
</Gotcha> </Gotcha>
### Adding to an array ### Adding to an array {#adding-to-an-array}
`push()` will mutate an array, which you don't want: `push()` will mutate an array, which you don't want:
@ -155,7 +155,7 @@ setArtists([
In this way, spread can do the job of both `push()` by adding to the end of an array and `unshift()` by adding to the beginning of an array. Try it in the sandbox above! In this way, spread can do the job of both `push()` by adding to the end of an array and `unshift()` by adding to the beginning of an array. Try it in the sandbox above!
### Removing from an array ### Removing from an array {#removing-from-an-array}
The easiest way to remove an item from an array is to *filter it out*. In other words, you will produce a new array that will not contain that item. To do this, use the `filter` method, for example: The easiest way to remove an item from an array is to *filter it out*. In other words, you will produce a new array that will not contain that item. To do this, use the `filter` method, for example:
@ -211,7 +211,7 @@ setArtists(
Here, `artists.filter(s => s.id !== artist.id)` means "create an array that consists of those `artists` whose IDs are different from `artist.id`." In other words, each artist's "Delete" button will filter _that_ artist out of the array, and then request a re-render with the resulting array. Note that `filter` does not modify the original array. Here, `artists.filter(s => s.id !== artist.id)` means "create an array that consists of those `artists` whose IDs are different from `artist.id`." In other words, each artist's "Delete" button will filter _that_ artist out of the array, and then request a re-render with the resulting array. Note that `filter` does not modify the original array.
### Transforming an array ### Transforming an array {#transforming-an-array}
If you want to change some or all items of the array, you can use `map()` to create a **new** array. The function you will pass to `map` can decide what to do with each item, based on its data or its index (or both). If you want to change some or all items of the array, you can use `map()` to create a **new** array. The function you will pass to `map` can decide what to do with each item, based on its data or its index (or both).
@ -279,7 +279,7 @@ body { height: 300px; }
</Sandpack> </Sandpack>
### Replacing items in an array ### Replacing items in an array {#replacing-items-in-an-array}
It is particularly common to want to replace one or more items in an array. Assignments like `arr[0] = 'bird'` are mutating the original array, so instead you'll want to use `map` for this as well. It is particularly common to want to replace one or more items in an array. Assignments like `arr[0] = 'bird'` are mutating the original array, so instead you'll want to use `map` for this as well.
@ -333,7 +333,7 @@ button { margin: 5px; }
</Sandpack> </Sandpack>
### Inserting into an array ### Inserting into an array {#inserting-into-an-array}
Sometimes, you may want to insert an item at a particular position that's neither at the beginning nor at the end. To do this, you can use the `...` array spread operator together with the `slice()` method. The `slice()` method lets you cut a "slice" of the array. To insert an item, you will create an array that spreads the slice _before_ the insertion point, then the new item, and then the rest of the original array. Sometimes, you may want to insert an item at a particular position that's neither at the beginning nor at the end. To do this, you can use the `...` array spread operator together with the `slice()` method. The `slice()` method lets you cut a "slice" of the array. To insert an item, you will create an array that spreads the slice _before_ the insertion point, then the new item, and then the rest of the original array.
@ -397,7 +397,7 @@ button { margin-left: 5px; }
</Sandpack> </Sandpack>
### Making other changes to an array ### Making other changes to an array {#making-other-changes-to-an-array}
There are some things you can't do with the spread operator and non-mutating methods like `map()` and `filter()` alone. For example, you may want to reverse or sort an array. The JavaScript `reverse()` and `sort()` methods are mutating the original array, so you can't use them directly. There are some things you can't do with the spread operator and non-mutating methods like `map()` and `filter()` alone. For example, you may want to reverse or sort an array. The JavaScript `reverse()` and `sort()` methods are mutating the original array, so you can't use them directly.
@ -455,7 +455,7 @@ setList(nextList);
Although `nextList` and `list` are two different arrays, **`nextList[0]` and `list[0]` point to the same object**. So by changing `nextList[0].seen`, you are also changing `list[0].seen`. This is a state mutation, which you should avoid! You can solve this issue in a similar way to [updating nested JavaScript objects](docs/updating-objects-in-state#updating-a-nested-object)--by copying individual items you want to change instead of mutating them. Here's how. Although `nextList` and `list` are two different arrays, **`nextList[0]` and `list[0]` point to the same object**. So by changing `nextList[0].seen`, you are also changing `list[0].seen`. This is a state mutation, which you should avoid! You can solve this issue in a similar way to [updating nested JavaScript objects](docs/updating-objects-in-state#updating-a-nested-object)--by copying individual items you want to change instead of mutating them. Here's how.
## Updating objects inside arrays ## Updating objects inside arrays {#updating-objects-inside-arrays}
Objects are not _really_ located "inside" arrays. They might appear to be "inside" in code, but each object in an array is a separate value, to which the array "points". This is why you need to be careful when changing nested fields like `list[0]`. Another person's artwork list may point to the same element of the array! Objects are not _really_ located "inside" arrays. They might appear to be "inside" in code, but each object in an array is a separate value, to which the array "points". This is why you need to be careful when changing nested fields like `list[0]`. Another person's artwork list may point to the same element of the array!
@ -658,7 +658,7 @@ function ItemList({ artworks, onToggle }) {
In general, **you should only mutate objects that you have just created.** If you were inserting a *new* artwork, you could mutate it, but if you're dealing with something that's already in state, you need to make a copy. In general, **you should only mutate objects that you have just created.** If you were inserting a *new* artwork, you could mutate it, but if you're dealing with something that's already in state, you need to make a copy.
### Write concise update logic with Immer ### Write concise update logic with Immer {#write-concise-update-logic-with-immer}
Updating nested arrays without mutation can get a little bit repetitive. [Just as with objects](/learn/updating-objects-in-state#write-concise-update-logic-with-immer): Updating nested arrays without mutation can get a little bit repetitive. [Just as with objects](/learn/updating-objects-in-state#write-concise-update-logic-with-immer):
@ -793,7 +793,7 @@ Behind the scenes, Immer always constructs the next state from scratch according
<Challenges> <Challenges>
### Update an item in the shopping cart ### Update an item in the shopping cart {#update-an-item-in-the-shopping-cart}
Fill in the `handleIncreaseClick` logic so that pressing "+" increases the corresponding number: Fill in the `handleIncreaseClick` logic so that pressing "+" increases the corresponding number:
@ -920,7 +920,7 @@ button { margin: 5px; }
</Solution> </Solution>
### Remove an item from the shopping cart ### Remove an item from the shopping cart {#remove-an-item-from-the-shopping-cart}
This shopping cart has a working "+" button, but the "–" button doesn't do anything. You need to add an event handler to it so that pressing it decreases the `count` of the corresponding product. If you press "–" when the count is 1, the product should automatically get removed from the cart. Make sure it never shows 0. This shopping cart has a working "+" button, but the "–" button doesn't do anything. You need to add an event handler to it so that pressing it decreases the `count` of the corresponding product. If you press "–" when the count is 1, the product should automatically get removed from the cart. Make sure it never shows 0.
@ -1081,7 +1081,7 @@ button { margin: 5px; }
</Solution> </Solution>
### Fix the mutations using non-mutative methods ### Fix the mutations using non-mutative methods {#fix-the-mutations-using-non-mutative-methods}
In this example, all of the event handlers in `App.js` use mutation. As a result, editing and deleting todos doesn't work. Rewrite `handleAddTodo`, `handleChangeTodo`, and `handleDeleteTodo` to use the non-mutative methods: In this example, all of the event handlers in `App.js` use mutation. As a result, editing and deleting todos doesn't work. Rewrite `handleAddTodo`, `handleChangeTodo`, and `handleDeleteTodo` to use the non-mutative methods:
@ -1414,7 +1414,7 @@ ul, li { margin: 0; padding: 0; }
</Solution> </Solution>
### Fix the mutations using Immer ### Fix the mutations using Immer {#fix-the-mutations-using-immer}
This is the same example as in the previous challenge. This time, fix the mutations by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `todos` state variable to use it. This is the same example as in the previous challenge. This time, fix the mutations by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `todos` state variable to use it.

16
beta/src/pages/learn/updating-objects-in-state.md

@ -18,7 +18,7 @@ State can hold any kind of JavaScript value, including objects. But you shouldn'
</YouWillLearn> </YouWillLearn>
## What's a mutation? ## What's a mutation? {#whats-a-mutation}
You can store any kind of JavaScript value in state. You can store any kind of JavaScript value in state.
@ -48,7 +48,7 @@ position.x = 5;
However, although objects in React state are technically mutable, you should treat them **as if** they were immutable--like numbers, booleans, and strings. Instead of mutating them, you should always replace them. However, although objects in React state are technically mutable, you should treat them **as if** they were immutable--like numbers, booleans, and strings. Instead of mutating them, you should always replace them.
## Treat state as read-only ## Treat state as read-only {#treat-state-as-read-only}
In other words, you should **treat any JavaScript object that you put into state as read-only.** In other words, you should **treat any JavaScript object that you put into state as read-only.**
@ -198,7 +198,7 @@ Mutation is only a problem when you change *existing* objects that are already i
</DeepDive> </DeepDive>
## Copying objects with the spread syntax ## Copying objects with the spread syntax {#copying-objects-with-the-spread-syntax}
In the previous example, the `position` object is always created fresh from the current cursor position. But often, you will want to include *existing* data as a part of the new object you're creating. For example, you may want to update *only one* field in a form, but keep the previous values for all other fields. In the previous example, the `position` object is always created fresh from the current cursor position. But often, you will want to include *existing* data as a part of the new object you're creating. For example, you may want to update *only one* field in a form, but keep the previous values for all other fields.
@ -442,7 +442,7 @@ Here, `e.target.name` refers to the `name` property given to the `<input>` DOM e
</DeepDive> </DeepDive>
## Updating a nested object ## Updating a nested object {#updating-a-nested-object}
Consider a nested object structure like this: Consider a nested object structure like this:
@ -645,7 +645,7 @@ If you were to mutate `obj3.artwork.city`, it would affect both `obj2.artwork.ci
</DeepDive> </DeepDive>
### Write concise update logic with Immer ### Write concise update logic with Immer {#write-concise-update-logic-with-immer}
If your state is deeply nested, you might want to consider [flattening it](/learn/choosing-the-state-structure#avoid-deeply-nested-state). But, if you don't want to change your state structure, you might prefer a shortcut to nested spreads. [Immer](https://github.com/immerjs/use-immer) is a popular library that lets you write using the convenient but mutating syntax and takes care of producing the copies for you. With Immer, the code you write looks like you are "breaking the rules" and mutating an object: If your state is deeply nested, you might want to consider [flattening it](/learn/choosing-the-state-structure#avoid-deeply-nested-state). But, if you don't want to change your state structure, you might prefer a shortcut to nested spreads. [Immer](https://github.com/immerjs/use-immer) is a popular library that lets you write using the convenient but mutating syntax and takes care of producing the copies for you. With Immer, the code you write looks like you are "breaking the rules" and mutating an object:
@ -814,7 +814,7 @@ In practice, you can often "get away" with mutating state in React, but we stron
<Challenges> <Challenges>
### Fix incorrect state updates ### Fix incorrect state updates {#fix-incorrect-state-updates}
This form has a few bugs. Click the button that increases the score a few times. Notice that it does not increase. Then edit the first name, and notice that the score has suddenly "caught up" with your changes. Finally, edit the last name, and notice that the score has disappeared completely. This form has a few bugs. Click the button that increases the score a few times. Notice that it does not increase. Then edit the first name, and notice that the score has suddenly "caught up" with your changes. Finally, edit the last name, and notice that the score has disappeared completely.
@ -962,7 +962,7 @@ The problem with `handleLastNameChange` was that it did not copy the existing `.
</Solution> </Solution>
### Find and fix the mutation ### Find and fix the mutation {#find-and-fix-the-mutation}
There is a draggable box on a static background. You can change the box's color using the select input. There is a draggable box on a static background. You can change the box's color using the select input.
@ -1277,7 +1277,7 @@ select { margin-bottom: 10px; }
</Solution> </Solution>
### Update an object with Immer ### Update an object with Immer {#update-an-object-with-immer}
This is the same buggy example as in the previous challenge. This time, fix the mutation by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `shape` state variable to use it. This is the same buggy example as in the previous challenge. This time, fix the mutation by using Immer. For your convenience, `useImmer` is already imported, so you need to change the `shape` state variable to use it.

16
beta/src/pages/learn/writing-markup-with-jsx.md

@ -17,7 +17,7 @@ JSX is a syntax extension for JavaScript that lets you write HTML-like markup in
</YouWillLearn> </YouWillLearn>
## JSX: Putting markup into JavaScript ## JSX: Putting markup into JavaScript {#jsx-putting-markup-into-javascript}
The Web has been built on HTML, CSS, and JavaScript. For many years, web developers kept content in HTML, design in CSS, and logic in JavaScript—often in separate files! Content was marked up inside HTML while the page's logic lived separately in JavaScript: The Web has been built on HTML, CSS, and JavaScript. For many years, web developers kept content in HTML, design in CSS, and logic in JavaScript—often in separate files! Content was marked up inside HTML while the page's logic lived separately in JavaScript:
@ -37,7 +37,7 @@ Each React component is a JavaScript function that may contain some markup that
</Note> </Note>
## Converting HTML to JSX ## Converting HTML to JSX {#converting-html-to-jsx}
Suppose that you have some (perfectly valid) HTML: Suppose that you have some (perfectly valid) HTML:
@ -103,9 +103,9 @@ Most of the times, React's on-screen error messages will help you find where the
</Note> </Note>
## The Rules of JSX ## The Rules of JSX {#the-rules-of-jsx}
### 1. Return a single root element ### 1. Return a single root element {#1-return-a-single-root-element}
To return multiple elements from a component, **wrap them with a single parent tag**. To return multiple elements from a component, **wrap them with a single parent tag**.
@ -150,7 +150,7 @@ JSX looks like HTML, but under the hood it is transformed into plain JavaScript
</DeepDive> </DeepDive>
### 2. Close all the tags ### 2. Close all the tags {#2-close-all-the-tags}
JSX requires tags to be explicitly closed: self-closing tags like `<img>` must become `<img />`, and wrapping tags like `<li>oranges` must be written as `<li>oranges</li>`. JSX requires tags to be explicitly closed: self-closing tags like `<img>` must become `<img />`, and wrapping tags like `<li>oranges` must be written as `<li>oranges</li>`.
@ -171,7 +171,7 @@ This is how Hedy Lamarr's image and list items look closed:
</> </>
``` ```
### 3. camelCase <s>all</s> most of the things! ### 3. camelCase <s>all</s> most of the things! {#3-camelcase-salls-most-of-the-things}
JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects. In your own components, you will often want to read those attributes into variables. But JavaScript has limitations on variable names. For example, their names can't contain dashes or be reserved words like `class`. JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects. In your own components, you will often want to read those attributes into variables. But JavaScript has limitations on variable names. For example, their names can't contain dashes or be reserved words like `class`.
@ -193,7 +193,7 @@ For historical reasons, [`aria-*`](https://developer.mozilla.org/docs/Web/Access
</Gotcha> </Gotcha>
### Pro-tip: Use a JSX Converter ### Pro-tip: Use a JSX Converter {#pro-tip-use-a-jsx-converter}
Converting all these attributes in existing markup can be tedious! We recommend using a [converter](https://transform.tools/html-to-jsx) to translate your existing HTML and SVG to JSX. Converters are very useful in practice, but it's still worth understanding what is going on so that you can comfortably write JSX on your own. Converting all these attributes in existing markup can be tedious! We recommend using a [converter](https://transform.tools/html-to-jsx) to translate your existing HTML and SVG to JSX. Converters are very useful in practice, but it's still worth understanding what is going on so that you can comfortably write JSX on your own.
@ -241,7 +241,7 @@ Now you know why JSX exists and how to use it in components:
<Challenges> <Challenges>
### Convert some HTML to JSX ### Convert some HTML to JSX {#convert-some-html-to-jsx}
This HTML was pasted into a component, but it's not valid JSX. Fix it: This HTML was pasted into a component, but it's not valid JSX. Fix it:

24
beta/src/pages/learn/your-first-component.md

@ -17,7 +17,7 @@ Components are one of the core concepts of React. They are the foundation upon w
</YouWillLearn> </YouWillLearn>
## Components: UI building blocks ## Components: UI building blocks {#components-ui-building-blocks}
On the Web, HTML lets us create rich structured documents with its built-in set of tags like `<h1>` and `<li>`: On the Web, HTML lets us create rich structured documents with its built-in set of tags like `<h1>` and `<li>`:
@ -54,7 +54,7 @@ Just like with HTML tags, you can compose, order and nest components to design w
As your project grows, you will notice that many of your designs can be composed by reusing components you already wrote, speeding up your development. Our table of contents above could be added to any screen with `<TableOfContents />`! You can even jumpstart your project with the thousands of components shared by the React open source community like [Chakra UI](https://chakra-ui.com/) and [Material UI](https://material-ui.com/). As your project grows, you will notice that many of your designs can be composed by reusing components you already wrote, speeding up your development. Our table of contents above could be added to any screen with `<TableOfContents />`! You can even jumpstart your project with the thousands of components shared by the React open source community like [Chakra UI](https://chakra-ui.com/) and [Material UI](https://material-ui.com/).
## Defining a component ## Defining a component {#defining-a-component}
Traditionally when creating web pages, web developers marked up their content and then added interaction by sprinkling on some JavaScript. This worked great when interaction was a nice-to-have on the web. Now it is expected for many sites and all apps. React puts interactivity first while still using the same technology: **a React component is a JavaScript function that you can _sprinkle with markup_**. Here's what that looks like (you can edit the example below): Traditionally when creating web pages, web developers marked up their content and then added interaction by sprinkling on some JavaScript. This worked great when interaction was a nice-to-have on the web. Now it is expected for many sites and all apps. React puts interactivity first while still using the same technology: **a React component is a JavaScript function that you can _sprinkle with markup_**. Here's what that looks like (you can edit the example below):
@ -79,11 +79,11 @@ img { height: 200px; }
And here's how to build a component: And here's how to build a component:
### Step 1: Export the component ### Step 1: Export the component {#step-1-export-the-component}
The `export default` prefix is a [standard JavaScript syntax](https://developer.mozilla.org/docs/web/javascript/reference/statements/export) (not specific to React). It lets you mark the main function in a file so that you can later import it from other files. (More on importing in [Importing and Exporting Components](/learn/importing-and-exporting-components)!) The `export default` prefix is a [standard JavaScript syntax](https://developer.mozilla.org/docs/web/javascript/reference/statements/export) (not specific to React). It lets you mark the main function in a file so that you can later import it from other files. (More on importing in [Importing and Exporting Components](/learn/importing-and-exporting-components)!)
### Step 2: Define the function ### Step 2: Define the function {#step-2-define-the-function}
With `function Profile() { }` you define a JavaScript function with the name `Profile`. With `function Profile() { }` you define a JavaScript function with the name `Profile`.
@ -93,7 +93,7 @@ React components are regular JavaScript functions, but **their names must start
</Gotcha> </Gotcha>
### Step 3: Add markup ### Step 3: Add markup {#step-3-add-markup}
The component returns an `<img />` tag with `src` and `alt` attributes. `<img />` is written like HTML, but it is actually JavaScript under the hood! This syntax is called [JSX](/learn/writing-markup-with-jsx), and it lets you embed markup inside JavaScript. The component returns an `<img />` tag with `src` and `alt` attributes. `<img />` is written like HTML, but it is actually JavaScript under the hood! This syntax is called [JSX](/learn/writing-markup-with-jsx), and it lets you embed markup inside JavaScript.
@ -119,7 +119,7 @@ Without parentheses, any code on the lines after `return` [will be ignored](http
</Gotcha> </Gotcha>
## Using a component ## Using a component {#using-a-component}
Now that you've defined your `Profile` component, you can nest it inside other components. For example, you can export a `Gallery` component that uses multiple `Profile` components: Now that you've defined your `Profile` component, you can nest it inside other components. For example, you can export a `Gallery` component that uses multiple `Profile` components:
@ -153,7 +153,7 @@ img { margin: 0 10px 10px 0; height: 90px; }
</Sandpack> </Sandpack>
### What the browser sees ### What the browser sees {#what-the-browser-sees}
Notice the difference in casing: Notice the difference in casing:
@ -171,7 +171,7 @@ And `Profile` contains even more HTML: `<img />`. In the end, this is what the b
</section> </section>
``` ```
### Nesting and organizing components ### Nesting and organizing components {#nesting-and-organizing-components}
Components are regular JavaScript functions, so you can keep multiple components in the same file. This is convenient when components are relatively small or tightly related to each other. If this file gets crowded, you can always move `Profile` to a separate file. You will learn how to do this shortly on the [page about imports](/learn/importing-and-exporting-components). Components are regular JavaScript functions, so you can keep multiple components in the same file. This is convenient when components are relatively small or tightly related to each other. If this file gets crowded, you can always move `Profile` to a separate file. You will learn how to do this shortly on the [page about imports](/learn/importing-and-exporting-components).
@ -206,7 +206,7 @@ You've just gotten your first taste of React! Let's recap some key points.
<Challenges> <Challenges>
### Export the component ### Export the component {#export-the-component}
This sandbox doesn't work because the root component is not exported: This sandbox doesn't work because the root component is not exported:
@ -258,7 +258,7 @@ You might be wondering why writing `export` alone is not enough to fix this exam
</Solution> </Solution>
### Fix the return statement ### Fix the return statement {#fix-the-return-statement}
Something isn't right about this `return` statement. Can you fix it? Something isn't right about this `return` statement. Can you fix it?
@ -325,7 +325,7 @@ img { height: 180px; }
</Solution> </Solution>
### Spot the mistake ### Spot the mistake {#spot-the-mistake}
Something's wrong with how the `Profile` component is declared and used. Can you spot the mistake? (Try to remember how React distinguishes components from the regular HTML tags!) Something's wrong with how the `Profile` component is declared and used. Can you spot the mistake? (Try to remember how React distinguishes components from the regular HTML tags!)
@ -397,7 +397,7 @@ img { margin: 0 10px 10px 0; }
</Solution> </Solution>
### Your own component ### Your own component {#your-own-component}
Write a component from scratch. You can give it any valid name and return any markup. If you're out of ideas, you can write a `Congratulations` component thats shows `<h1>Good job!</h1>`. Don't forget to export it! Write a component from scratch. You can give it any valid name and return any markup. If you're out of ideas, you can write a `Congratulations` component thats shows `<h1>Good job!</h1>`. Don't forget to export it!

4
beta/src/pages/reference/index.md

@ -9,7 +9,7 @@ The React package contains all the APIs necessary to define and use [components]
</Intro> </Intro>
## Installation ## Installation {#installation}
It is available as [`react`](https://www.npmjs.com/package/react) on npm. You can also [add React to the page as a `<script>` tag](/learn/add-react-to-a-website). It is available as [`react`](https://www.npmjs.com/package/react) on npm. You can also [add React to the page as a `<script>` tag](/learn/add-react-to-a-website).
@ -33,7 +33,7 @@ import * as React from 'react';
If you use React on the web, you'll also need the same version of [ReactDOM](/api/reactdom). If you use React on the web, you'll also need the same version of [ReactDOM](/api/reactdom).
## Exports ## Exports {#exports}
<YouWillLearnCard title="useState" path="/reference/usestate"> <YouWillLearnCard title="useState" path="/reference/usestate">

6
beta/src/pages/reference/reactdom.md

@ -11,7 +11,7 @@ The ReactDOM package lets you render React components on a webpage.
Typically, you will use ReactDOM at the top level of your app to display your components. You will either use it directly or a [framework](/learn/start-a-new-react-project#building-with-react-and-a-framework) may do it for you. Most of your components should *not* need to import this module. Typically, you will use ReactDOM at the top level of your app to display your components. You will either use it directly or a [framework](/learn/start-a-new-react-project#building-with-react-and-a-framework) may do it for you. Most of your components should *not* need to import this module.
## Installation ## Installation {#installation}
<PackageImport> <PackageImport>
@ -33,11 +33,11 @@ import * as ReactDOM from 'react';
You'll also need to install the same version of [React](/api/). You'll also need to install the same version of [React](/api/).
## Browser Support ## Browser Support {#browser-support}
ReactDOM supports all popular browsers, including Internet Explorer 9 and above. [Some polyfills are required](http://todo%20link%20to%20js%20environment%20requirements/) for older browsers such as IE 9 and IE 10. ReactDOM supports all popular browsers, including Internet Explorer 9 and above. [Some polyfills are required](http://todo%20link%20to%20js%20environment%20requirements/) for older browsers such as IE 9 and IE 10.
## Exports ## Exports {#exports}
<YouWillLearnCard title="render" path="/reference/render"> <YouWillLearnCard title="render" path="/reference/render">

10
beta/src/pages/reference/render.md

@ -14,7 +14,7 @@ render(<App />, container, callback);
</Intro> </Intro>
## Rendering the root component ## Rendering the root component {#rendering-the-root-component}
To call `render`, you need a piece of JSX and a DOM container: To call `render`, you need a piece of JSX and a DOM container:
@ -61,7 +61,7 @@ export default function App() {
<br /> <br />
## Rendering multiple roots ## Rendering multiple roots {#rendering-multiple-roots}
If you use ["sprinkles"](/learn/add-react-to-a-website) of React here and there, call `render` for each top-level piece of UI managed by React. If you use ["sprinkles"](/learn/add-react-to-a-website) of React here and there, call `render` for each top-level piece of UI managed by React.
@ -135,7 +135,7 @@ nav ul li { display: inline-block; margin-right: 20px; }
<br /> <br />
## Updating the rendered tree ## Updating the rendered tree {#updating-the-rendered-tree}
You can call `render` more than once on the same DOM node. As long as the component tree structure matches up with what was previously rendered, React will [preserve the state](/learn/preserving-and-resetting-state). Notice how you can type in the input: You can call `render` more than once on the same DOM node. As long as the component tree structure matches up with what was previously rendered, React will [preserve the state](/learn/preserving-and-resetting-state). Notice how you can type in the input:
@ -172,7 +172,7 @@ You can destroy the rendered tree with [`unmountComponentAtNode()`](TODO).
<br /> <br />
## When not to use it ## When not to use it {#when-not-to-use-it}
* If your app uses server rendering and generates HTML on the server, use [`hydrate`](TODO) instead of `render`. * If your app uses server rendering and generates HTML on the server, use [`hydrate`](TODO) instead of `render`.
* If your app is fully built with React, you shouldn't need to use `render` more than once. If you want to render something in a different part of the DOM tree (for example, a modal or a tooltip), use [`createPortal`](TODO) instead. * If your app is fully built with React, you shouldn't need to use `render` more than once. If you want to render something in a different part of the DOM tree (for example, a modal or a tooltip), use [`createPortal`](TODO) instead.
@ -180,7 +180,7 @@ You can destroy the rendered tree with [`unmountComponentAtNode()`](TODO).
<br /> <br />
## Behavior in detail ## Behavior in detail {#behavior-in-detail}
The first time you call `render`, any existing DOM elements inside `container` are replaced. If you call `render` again, React will update the DOM as necessary to reflect the latest JSX. React will decide which parts of the DOM can be reused and which need to be recreated by ["matching it up"](/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` repeatedly is similar to calling `setState`--in both cases, React avoids unnecessary DOM updates. The first time you call `render`, any existing DOM elements inside `container` are replaced. If you call `render` again, React will update the DOM as necessary to reflect the latest JSX. React will decide which parts of the DOM can be reused and which need to be recreated by ["matching it up"](/learn/preserving-and-resetting-state) with the previously rendered tree. Calling `render` repeatedly is similar to calling `setState`--in both cases, React avoids unnecessary DOM updates.

24
beta/src/pages/reference/usestate.md

@ -13,7 +13,7 @@ const [state, setState] = useState(initialState);
</Intro> </Intro>
## Using state ## Using state {#using-state}
You can add state to your component in three steps: You can add state to your component in three steps:
@ -83,7 +83,7 @@ export default function Counter() {
<br /> <br />
## Declaring a state variable ## Declaring a state variable {#declaring-a-state-variable}
You can declare multiple state variables in a component. You must declare them **at the top level of your component,** outside of any conditions or loops. This component declares state variables called `name` and `age`: You can declare multiple state variables in a component. You must declare them **at the top level of your component,** outside of any conditions or loops. This component declares state variables called `name` and `age`:
@ -166,14 +166,14 @@ function handleClick() {
<br /> <br />
## When not to use it ## When not to use it {#when-not-to-use-it}
* Don't use state when a regular variable works. State is only used to [persist information between re-renders](/learn/state-a-components-memory). * Don't use state when a regular variable works. State is only used to [persist information between re-renders](/learn/state-a-components-memory).
* Don't add [redundant state](/learn/choosing-the-state-structure#avoid-redundant-state). If you can calculate something during render, you don't need state for it. * Don't add [redundant state](/learn/choosing-the-state-structure#avoid-redundant-state). If you can calculate something during render, you don't need state for it.
<br /> <br />
## Updating objects and arrays in state ## Updating objects and arrays in state {#updating-objects-and-arrays-in-state}
You can hold objects and arrays in state, too. However, you should always *replace* objects in state rather than modify the existing ones. [Updating objects](/learn/updating-objects-in-state) and [updating arrays](/learn/updating-arrays-in-state) describe common patterns that help avoid bugs. You can hold objects and arrays in state, too. However, you should always *replace* objects in state rather than modify the existing ones. [Updating objects](/learn/updating-objects-in-state) and [updating arrays](/learn/updating-arrays-in-state) describe common patterns that help avoid bugs.
@ -224,7 +224,7 @@ body { margin: 0; padding: 0; height: 250px; }
<Recipes> <Recipes>
### Image gallery ### Image gallery {#image-gallery}
<Sandpack> <Sandpack>
@ -386,7 +386,7 @@ img { width: 120px; height: 120px; }
<Solution /> <Solution />
### Form with multiple fields ### Form with multiple fields {#form-with-multiple-fields}
<Sandpack> <Sandpack>
@ -452,7 +452,7 @@ input { margin-left: 5px; }
<Solution /> <Solution />
### Todo list ### Todo list {#todo-list}
<Sandpack> <Sandpack>
@ -619,7 +619,7 @@ ul, li { margin: 0; padding: 0; }
<Solution /> <Solution />
### Multiple selection ### Multiple selection {#multiple-selection}
<Sandpack> <Sandpack>
@ -724,9 +724,9 @@ label { width: 100%; padding: 5px; display: inline-block; }
</Recipes> </Recipes>
## Special cases ## Special cases {#special-cases}
### Passing the same value to `setState` ### Passing the same value to `setState` {#passing-the-same-value-to-setstate}
If you pass the current state to `setState`, React **will skip re-rendering the component**: If you pass the current state to `setState`, React **will skip re-rendering the component**:
@ -738,7 +738,7 @@ This is a performance optimization. React uses the [`Object.is()`](https://devel
<br /> <br />
### Passing an updater function to `setState` ### Passing an updater function to `setState` {#passing-an-updater-function-to-setstate}
Instead of passing the next state itself, **you may pass a function to `setState`.** Such a function, like `c => c + 1` in this example, is called an "updater". React will call your updater during the next render to calculate the final state. Instead of passing the next state itself, **you may pass a function to `setState`.** Such a function, like `c => c + 1` in this example, is called an "updater". React will call your updater during the next render to calculate the final state.
@ -885,7 +885,7 @@ setState(() => myFunction);
<br /> <br />
### Passing an initializer function to `useState` ### Passing an initializer function to `useState` {#passing-an-initializer-function-to-usestate}
The initial state that you pass to `useState` as an argument is only used for the initial render. For next renders, this argument is ignored. If creating the initial state is expensive, it is wasteful to create and throw it away many times. **You can pass a function to `useState` to calculate the initial state.** React will only run it during the initialization. The initial state that you pass to `useState` as an argument is only used for the initial render. For next renders, this argument is ignored. If creating the initial state is expensive, it is wasteful to create and throw it away many times. **You can pass a function to `useState` to calculate the initial state.** React will only run it during the initialization.

17
beta/yarn.lock

@ -1593,6 +1593,11 @@ ci-info@^2.0.0:
resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46" resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46"
integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ== integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==
ci-info@^3.2.0:
version "3.2.0"
resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-3.2.0.tgz#2876cb948a498797b5236f0095bc057d0dca38b6"
integrity sha512-dVqRX7fLUm8J6FgHJ418XuIgDLZDkYcDFTeL6TA2gt5WlIZUQrrH6EZrNClwT/H0FateUsZkGIOPRrLbP+PR9A==
cipher-base@^1.0.0, cipher-base@^1.0.1, cipher-base@^1.0.3: cipher-base@^1.0.0, cipher-base@^1.0.1, cipher-base@^1.0.3:
version "1.0.4" version "1.0.4"
resolved "https://registry.yarnpkg.com/cipher-base/-/cipher-base-1.0.4.tgz#8760e4ecc272f4c363532f926d874aae2c1397de" resolved "https://registry.yarnpkg.com/cipher-base/-/cipher-base-1.0.4.tgz#8760e4ecc272f4c363532f926d874aae2c1397de"
@ -2909,6 +2914,11 @@ https-browserify@1.0.0:
resolved "https://registry.yarnpkg.com/https-browserify/-/https-browserify-1.0.0.tgz#ec06c10e0a34c0f2faf199f7fd7fc78fffd03c73" resolved "https://registry.yarnpkg.com/https-browserify/-/https-browserify-1.0.0.tgz#ec06c10e0a34c0f2faf199f7fd7fc78fffd03c73"
integrity sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM= integrity sha1-7AbBDgo0wPL68Zn3/X/Hj//QPHM=
husky@^7.0.4:
version "7.0.4"
resolved "https://registry.yarnpkg.com/husky/-/husky-7.0.4.tgz#242048245dc49c8fb1bf0cc7cfb98dd722531535"
integrity sha512-vbaCKN2QLtP/vD4yvs6iz6hBEo6wkSzs8HpRah1Z6aGmF2KW5PdYuAd7uX5a+OyBZHBhd+TFLqgjUgytQr4RvQ==
iconv-lite@0.4.24, iconv-lite@^0.4.24: iconv-lite@0.4.24, iconv-lite@^0.4.24:
version "0.4.24" version "0.4.24"
resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b"
@ -3103,6 +3113,13 @@ is-ci@^2.0.0:
dependencies: dependencies:
ci-info "^2.0.0" ci-info "^2.0.0"
is-ci@^3.0.1:
version "3.0.1"
resolved "https://registry.yarnpkg.com/is-ci/-/is-ci-3.0.1.tgz#db6ecbed1bd659c43dac0f45661e7674103d1867"
integrity sha512-ZYvCgrefwqoQ6yTyYUbQu64HsITZ3NfKX1lzaEYdkTDcfKzzCI/wthRRYKkdjHKFVgNiXKAKm65Zo1pk2as/QQ==
dependencies:
ci-info "^3.2.0"
is-color-stop@^1.1.0: is-color-stop@^1.1.0:
version "1.1.0" version "1.1.0"
resolved "https://registry.yarnpkg.com/is-color-stop/-/is-color-stop-1.1.0.tgz#cfff471aee4dd5c9e158598fbe12967b5cdad345" resolved "https://registry.yarnpkg.com/is-color-stop/-/is-color-stop-1.1.0.tgz#cfff471aee4dd5c9e158598fbe12967b5cdad345"

Loading…
Cancel
Save