├── README.md
└── audio-visuals
├── .gitignore
├── README.md
├── package.json
├── public
├── favicon.ico
└── index.html
├── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
└── logo.svg
└── yarn.lock
/README.md:
--------------------------------------------------------------------------------
1 | # react-audio-visualization
2 |
3 | This tutorial is for creating an audio visualization in React with the web audio API.
4 |
5 | ### Let's get some stuff out of the way first,
6 |
7 | In this tutorial will use Node.js and npm, if you already have that installed then that's great move on to the next step, otherwise [learn about // get npm here.](https://www.npmjs.com/get-npm)
8 |
9 | This is *not* a tutorial on how to use React. If you want to learn more about how React works check out [Fullstack React](https://www.fullstackreact.com/)
10 |
11 | The first thing we need to do is download create-react-app to get our react boilerplate. [Here are the docs if you want to learn more.](https://github.com/facebookincubator/create-react-app)
12 | Type the following into your terminal:
13 |
14 | ```
15 | npm install -g create-react-app
16 | ```
17 |
18 | ### Okay now let's get started!
19 |
20 | We can create our app by typing this command followed by the name of your application. I called mine audio-visuals in this example. Type the following into your terminal:
21 |
22 |
23 | ```
24 | create-react-app audio-visuals
25 | ```
26 |
27 | This may take a moment...
28 | After it's done you can go ahead and change directories into the newly created app. Type the following into your terminal.
29 | ```
30 | cd audio-visuals
31 | ```
32 |
33 | Then open up the directory in your favorite text editor. \(I use Atom\) You can open it up from the terminal by typing
34 | ```
35 | atom .
36 | ```
37 | If you see an error that says atom is not a command then go to atom and look at the top menu bar. Click the drop down that says Atom and look for Install shell commands. Click that and you should now be able to use the atom command in your terminal.
38 |
39 |
40 | 
41 |
42 |
43 | Now that you've opened up the directory with your text editor, take a look around! Don't worry about the node modules or anything else that looks confusing. We will walk through this step by step.
44 |
45 | The file structure will look like this:
46 | 
47 |
64 | Navigate to audio-visuals/src/App.js
65 | you should see this in the file:
66 |
67 | ```
68 | import React, { Component } from 'react';
69 | import logo from './logo.svg';
70 | import './App.css';
71 |
72 | class App extends Component {
73 | render() {
74 | return (
75 |
76 |
77 |
78 |
Welcome to React
79 |
80 |
81 | To get started, edit src/App.js and save to reload.
82 |
83 |
84 | );
85 | }
86 | }
87 |
88 | export default App;
89 | ```
90 | You can delete some lines and leave it looking like this, or just paste the following code over it.
91 |
92 | ```
93 | import React, { Component } from 'react';
94 | import './App.css';
95 |
96 | class App extends Component {
97 | render() {
98 | return (
99 |
100 |
101 | );
102 | }
103 | }
104 |
105 | export default App;
106 | ```
107 | ### Now comes the real coding :)
108 |
109 | Now inside the div with the className App we will insert an audio tag, with whatever song you'd like. I'm going to use sublime! Also add an h2 tag to say the name of the song and artist you choose.
110 |
111 | now the App Component should look like this:
112 |
113 | ```
114 | class App extends Component {
115 | render() {
116 | return (
117 |
118 |
Sublime - 40oz to Freedom
119 |
126 |
127 | );
128 | }
129 | }
130 | ```
131 |
132 | As you can see we have set a few attributes on the audio tag, including the ref attribute. This is so we can reference the tag in a method we will write on our component later on. [Learn more about the ref attribute here!](https://facebook.github.io/react/docs/refs-and-the-dom.html)
133 |
134 | You can now run ```npm start``` in your terminal and see the audio tag rendered on your webpage running on localhost:3000. Mine looks like this:
135 |
136 |
137 | 
138 |
139 | Go back to atom or your text editor and add a canvas tag underneath the audio tag. Add a ref attribute of "analyzerCanvas" and an id of "analyzer". I've also added a couple divs with specific Ids so we can reference them later. Your app component should look like this now:
140 |
141 | ```
142 | class App extends Component {
143 | render() {
144 | return (
145 |
146 |
Sublime - 40oz to Freedom
147 |
148 |
149 |
157 |
158 |
163 |
164 |
165 | );
166 | }
167 | }
168 | ```
169 |
170 | Now we're going to add a method to the App component called createVisualization.
171 | inside that method we will create a new audio context with the Web Audio API. You do not need to download anything to have access to this API. An audio context represents an audio-processing graph, built from audio modules linked together, that are represented by AudioNodes. Just create a new instance by typing new AudioContext(); and save it to a variable. Later our audio context will be connected to our audio tag. So far our method looks like this
172 |
173 | ```
174 | createVisualization(){
175 | let context = new AudioContext();
176 | }
177 | ```
178 | Now that we have the Audio context object saved to a variable we can create an analyser node from it with the create analyser method. According to [the MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode) an analyser node "represents a node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations." If that sounds confusing it's okay you will still be able to move forward with the tutorial.
179 |
180 | ```
181 | let analyser = context.createAnalyser();
182 | ```
183 | Then we create a reference to the canvas element and save it to a variable. We do this by accessing the refs object that React sets up for us by typing ```this.refs```. Then we want to get the context of the canvas so we can draw shapes on it. We do this with the methods that the canvas element has available for us to use.
184 |
185 | ```
186 | let canvas = this.refs.analyserCanvas;
187 | let ctx = canvas.getContext('2d');
188 | ```
189 | Now we want to grab the audio tag in the same way we did the canvas. Then we set the cross origin of the audio tag to anonymous
190 |
191 | ```
192 | let audio = this.refs.audio;
193 | audio.crossOrigin = "anonymous"
194 | ```
195 | After that we pass the audio tag into the Audio context method called createMediaElementSource in order to create an audio source that the audio context can work with. Then we connect it to the audio context's analyser and then both the analyser and the audio source are connected to the context's destination.
196 |
197 | ```
198 | let audioSrc = context.createMediaElementSource(audio);
199 | audioSrc.connect(analyser);
200 | audioSrc.connect(context.destination);
201 | analyser.connect(context.destination);
202 | ```
203 | #### Just to check in this is what App.js should look like so far:
204 |
205 | ```
206 | import React, { Component } from 'react';
207 | import './App.css';
208 |
209 | class App extends Component {
210 |
211 | createVisualization(){
212 | let context = new AudioContext();
213 | let analyser = context.createAnalyser();
214 | let canvas = this.refs.analyserCanvas;
215 | let ctx = canvas.getContext('2d');
216 | let audio = this.refs.audio;
217 | audio.crossOrigin = "anonymous";
218 | let audioSrc = context.createMediaElementSource(audio);
219 | audioSrc.connect(analyser);
220 | audioSrc.connect(context.destination);
221 | analyser.connect(context.destination);
222 |
223 | }
224 |
225 | render() {
226 | return (
227 |
228 |
Sublime - 40oz to Freedom
229 |
230 |
231 |
239 |
240 |
245 |
246 |
247 | );
248 | }
249 | }
250 |
251 | export default App;
252 | ```
253 |
254 | Now we will create a recursive function called renderFrame within our createVisualization method and then we will invoke it.
255 |
256 | ```
257 | function renderFrame(){
258 | let freqData = new Uint8Array(analyser.frequencyBinCount)
259 | requestAnimationFrame(renderFrame)
260 | analyser.getByteFrequencyData(freqData)
261 | ctx.clearRect(0, 0, canvas.width, canvas.height)
262 | console.log(freqData)
263 | ctx.fillStyle = '#9933ff';
264 | let bars = 100;
265 | for (var i = 0; i < bars; i++) {
266 | let bar_x = i * 3;
267 | let bar_width = 2;
268 | let bar_height = -(freqData[i] / 2);
269 | ctx.fillRect(bar_x, canvas.height, bar_width, bar_height)
270 | }
271 | };
272 | renderFrame()
273 | ```
274 |
275 | Here we are using some methods from analyser nodes to collect frequency data from the music playing and repeatedly draw bars on the canvas. The bars height depend on the audio's frequency. I made my bars purple but feel free to change the value of ctx.fillStyle to whatever color you want.
276 |
277 | ### Almost done!
278 |
279 | Now we need to make sure to invoke the createVisualization method after the app component loads. We will do this with a built in method called componentDidMount. This is called after the render function. Add this to your app component's methods.
280 | ```
281 | componentDidMount(){
282 | this.createVisualization()
283 | }
284 | ```
285 |
286 | Now we just need to bind the context of this to the createVisualization method so that when we say ```this``` we mean the app component, not the createVisualization method. We will do this in the constructor function.
287 |
288 | ```
289 | constructor(props){
290 | super(props)
291 |
292 | this.createVisualization = this.createVisualization.bind(this)
293 | }
294 | ```
295 |
296 | ### Congratulations you're done! Run npm start in your terminal to see it working on localhost:3000 and if you have problems check your code against mine:
297 |
298 | ```
299 | import React, { Component } from 'react';
300 | import './App.css';
301 |
302 | class App extends Component {
303 | constructor(props){
304 | super(props)
305 |
306 | this.createVisualization = this.createVisualization.bind(this)
307 | }
308 |
309 | componentDidMount(){
310 | this.createVisualization()
311 | }
312 |
313 | createVisualization(){
314 | let context = new AudioContext();
315 | let analyser = context.createAnalyser();
316 | let canvas = this.refs.analyzerCanvas;
317 | let ctx = canvas.getContext('2d');
318 | let audio = this.refs.audio;
319 | audio.crossOrigin = "anonymous";
320 | let audioSrc = context.createMediaElementSource(audio);
321 | audioSrc.connect(analyser);
322 | audioSrc.connect(context.destination);
323 | analyser.connect(context.destination);
324 |
325 | function renderFrame(){
326 | let freqData = new Uint8Array(analyser.frequencyBinCount)
327 | requestAnimationFrame(renderFrame)
328 | analyser.getByteFrequencyData(freqData)
329 | ctx.clearRect(0, 0, canvas.width, canvas.height)
330 | console.log(freqData)
331 | ctx.fillStyle = '#9933ff';
332 | let bars = 100;
333 | for (var i = 0; i < bars; i++) {
334 | let bar_x = i * 3;
335 | let bar_width = 2;
336 | let bar_height = -(freqData[i] / 2);
337 | ctx.fillRect(bar_x, canvas.height, bar_width, bar_height)
338 | }
339 | };
340 | renderFrame()
341 | }
342 |
343 | render() {
344 | return (
345 |
346 |
Sublime - 40oz to Freedom
347 |
348 |
349 |
357 |
358 |
363 |
364 |
365 | );
366 | }
367 | }
368 |
369 | export default App;
370 | ```
371 |
--------------------------------------------------------------------------------
/audio-visuals/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 |
6 | # testing
7 | /coverage
8 |
9 | # production
10 | /build
11 |
12 | # misc
13 | .DS_Store
14 | .env
15 | npm-debug.log*
16 | yarn-debug.log*
17 | yarn-error.log*
18 |
19 |
--------------------------------------------------------------------------------
/audio-visuals/README.md:
--------------------------------------------------------------------------------
1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
2 |
3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md).
5 |
6 | ## Table of Contents
7 |
8 | - [Updating to New Releases](#updating-to-new-releases)
9 | - [Sending Feedback](#sending-feedback)
10 | - [Folder Structure](#folder-structure)
11 | - [Available Scripts](#available-scripts)
12 | - [npm start](#npm-start)
13 | - [npm test](#npm-test)
14 | - [npm run build](#npm-run-build)
15 | - [npm run eject](#npm-run-eject)
16 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
17 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
18 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
19 | - [Debugging in the Editor](#debugging-in-the-editor)
20 | - [Changing the Page ``](#changing-the-page-title)
21 | - [Installing a Dependency](#installing-a-dependency)
22 | - [Importing a Component](#importing-a-component)
23 | - [Adding a Stylesheet](#adding-a-stylesheet)
24 | - [Post-Processing CSS](#post-processing-css)
25 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
26 | - [Adding Images and Fonts](#adding-images-and-fonts)
27 | - [Using the `public` Folder](#using-the-public-folder)
28 | - [Changing the HTML](#changing-the-html)
29 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
30 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
31 | - [Using Global Variables](#using-global-variables)
32 | - [Adding Bootstrap](#adding-bootstrap)
33 | - [Using a Custom Theme](#using-a-custom-theme)
34 | - [Adding Flow](#adding-flow)
35 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
36 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
37 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
38 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
39 | - [Can I Use Decorators?](#can-i-use-decorators)
40 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
41 | - [Node](#node)
42 | - [Ruby on Rails](#ruby-on-rails)
43 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
44 | - [Using HTTPS in Development](#using-https-in-development)
45 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
46 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
47 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
48 | - [Running Tests](#running-tests)
49 | - [Filename Conventions](#filename-conventions)
50 | - [Command Line Interface](#command-line-interface)
51 | - [Version Control Integration](#version-control-integration)
52 | - [Writing Tests](#writing-tests)
53 | - [Testing Components](#testing-components)
54 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
55 | - [Initializing Test Environment](#initializing-test-environment)
56 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
57 | - [Coverage Reporting](#coverage-reporting)
58 | - [Continuous Integration](#continuous-integration)
59 | - [Disabling jsdom](#disabling-jsdom)
60 | - [Snapshot Testing](#snapshot-testing)
61 | - [Editor Integration](#editor-integration)
62 | - [Developing Components in Isolation](#developing-components-in-isolation)
63 | - [Making a Progressive Web App](#making-a-progressive-web-app)
64 | - [Deployment](#deployment)
65 | - [Static Server](#static-server)
66 | - [Other Solutions](#other-solutions)
67 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
68 | - [Building for Relative Paths](#building-for-relative-paths)
69 | - [Azure](#azure)
70 | - [Firebase](#firebase)
71 | - [GitHub Pages](#github-pages)
72 | - [Heroku](#heroku)
73 | - [Modulus](#modulus)
74 | - [Netlify](#netlify)
75 | - [Now](#now)
76 | - [S3 and CloudFront](#s3-and-cloudfront)
77 | - [Surge](#surge)
78 | - [Advanced Configuration](#advanced-configuration)
79 | - [Troubleshooting](#troubleshooting)
80 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
81 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
82 | - [`npm run build` silently fails](#npm-run-build-silently-fails)
83 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
84 | - [Something Missing?](#something-missing)
85 |
86 | ## Updating to New Releases
87 |
88 | Create React App is divided into two packages:
89 |
90 | * `create-react-app` is a global command-line utility that you use to create new projects.
91 | * `react-scripts` is a development dependency in the generated projects (including this one).
92 |
93 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
94 |
95 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically.
96 |
97 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions.
98 |
99 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes.
100 |
101 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
102 |
103 | ## Sending Feedback
104 |
105 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
106 |
107 | ## Folder Structure
108 |
109 | After creation, your project should look like this:
110 |
111 | ```
112 | my-app/
113 | README.md
114 | node_modules/
115 | package.json
116 | public/
117 | index.html
118 | favicon.ico
119 | src/
120 | App.css
121 | App.js
122 | App.test.js
123 | index.css
124 | index.js
125 | logo.svg
126 | ```
127 |
128 | For the project to build, **these files must exist with exact filenames**:
129 |
130 | * `public/index.html` is the page template;
131 | * `src/index.js` is the JavaScript entry point.
132 |
133 | You can delete or rename the other files.
134 |
135 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
136 | You need to **put any JS and CSS files inside `src`**, or Webpack won’t see them.
137 |
138 | Only files inside `public` can be used from `public/index.html`.
139 | Read instructions below for using assets from JavaScript and HTML.
140 |
141 | You can, however, create more top-level directories.
142 | They will not be included in the production build so you can use them for things like documentation.
143 |
144 | ## Available Scripts
145 |
146 | In the project directory, you can run:
147 |
148 | ### `npm start`
149 |
150 | Runs the app in the development mode.
151 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
152 |
153 | The page will reload if you make edits.
154 | You will also see any lint errors in the console.
155 |
156 | ### `npm test`
157 |
158 | Launches the test runner in the interactive watch mode.
159 | See the section about [running tests](#running-tests) for more information.
160 |
161 | ### `npm run build`
162 |
163 | Builds the app for production to the `build` folder.
164 | It correctly bundles React in production mode and optimizes the build for the best performance.
165 |
166 | The build is minified and the filenames include the hashes.
167 | Your app is ready to be deployed!
168 |
169 | See the section about [deployment](#deployment) for more information.
170 |
171 | ### `npm run eject`
172 |
173 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
174 |
175 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
176 |
177 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
178 |
179 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
180 |
181 | ## Supported Language Features and Polyfills
182 |
183 | This project supports a superset of the latest JavaScript standard.
184 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
185 |
186 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
187 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
188 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
189 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal).
190 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
191 |
192 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
193 |
194 | While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future.
195 |
196 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
197 |
198 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
199 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
200 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
201 |
202 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them.
203 |
204 | ## Syntax Highlighting in the Editor
205 |
206 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered.
207 |
208 | ## Displaying Lint Output in the Editor
209 |
210 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
211 |
212 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
213 |
214 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do.
215 |
216 | You would need to install an ESLint plugin for your editor first.
217 |
218 | >**A note for Atom `linter-eslint` users**
219 |
220 | >If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked:
221 |
222 | >
223 |
224 |
225 | >**For Visual Studio Code users**
226 |
227 | >VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line:
228 |
229 | >```js
230 | {
231 | // ...
232 | "extends": "react-app"
233 | }
234 | ```
235 |
236 | Then add this block to the `package.json` file of your project:
237 |
238 | ```js
239 | {
240 | // ...
241 | "eslintConfig": {
242 | "extends": "react-app"
243 | }
244 | }
245 | ```
246 |
247 | Finally, you will need to install some packages *globally*:
248 |
249 | ```sh
250 | npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@4.0.0 eslint-plugin-flowtype@2.21.0
251 | ```
252 |
253 | We recognize that this is suboptimal, but it is currently required due to the way we hide the ESLint dependency. The ESLint team is already [working on a solution to this](https://github.com/eslint/eslint/issues/3458) so this may become unnecessary in a couple of months.
254 |
255 | ## Debugging in the Editor
256 |
257 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.**
258 |
259 | Visual Studio Code supports live-editing and debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools.
260 |
261 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed.
262 |
263 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
264 |
265 | ```json
266 | {
267 | "version": "0.2.0",
268 | "configurations": [{
269 | "name": "Chrome",
270 | "type": "chrome",
271 | "request": "launch",
272 | "url": "http://localhost:3000",
273 | "webRoot": "${workspaceRoot}/src",
274 | "userDataDir": "${workspaceRoot}/.vscode/chrome",
275 | "sourceMapPathOverrides": {
276 | "webpack:///src/*": "${webRoot}/*"
277 | }
278 | }]
279 | }
280 | ```
281 |
282 | Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor.
283 |
284 | ## Changing the Page ``
285 |
286 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `` tag in it to change the title from “React App” to anything else.
287 |
288 | Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML.
289 |
290 | If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library.
291 |
292 | If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files).
293 |
294 | ## Installing a Dependency
295 |
296 | The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`:
297 |
298 | ```
299 | npm install --save
300 | ```
301 |
302 | ## Importing a Component
303 |
304 | This project setup supports ES6 modules thanks to Babel.
305 | While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead.
306 |
307 | For example:
308 |
309 | ### `Button.js`
310 |
311 | ```js
312 | import React, { Component } from 'react';
313 |
314 | class Button extends Component {
315 | render() {
316 | // ...
317 | }
318 | }
319 |
320 | export default Button; // Don’t forget to use export default!
321 | ```
322 |
323 | ### `DangerButton.js`
324 |
325 |
326 | ```js
327 | import React, { Component } from 'react';
328 | import Button from './Button'; // Import a component from another file
329 |
330 | class DangerButton extends Component {
331 | render() {
332 | return ;
333 | }
334 | }
335 |
336 | export default DangerButton;
337 | ```
338 |
339 | Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes.
340 |
341 | We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`.
342 |
343 | Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like.
344 |
345 | Learn more about ES6 modules:
346 |
347 | * [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281)
348 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
349 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
350 |
351 | ## Adding a Stylesheet
352 |
353 | This project setup uses [Webpack](https://webpack.github.io/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**:
354 |
355 | ### `Button.css`
356 |
357 | ```css
358 | .Button {
359 | padding: 20px;
360 | }
361 | ```
362 |
363 | ### `Button.js`
364 |
365 | ```js
366 | import React, { Component } from 'react';
367 | import './Button.css'; // Tell Webpack that Button.js uses these styles
368 |
369 | class Button extends Component {
370 | render() {
371 | // You can use them as regular CSS styles
372 | return ;
373 | }
374 | }
375 | ```
376 |
377 | **This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack.
378 |
379 | In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output.
380 |
381 | If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool.
382 |
383 | ## Post-Processing CSS
384 |
385 | This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it.
386 |
387 | For example, this:
388 |
389 | ```css
390 | .App {
391 | display: flex;
392 | flex-direction: row;
393 | align-items: center;
394 | }
395 | ```
396 |
397 | becomes this:
398 |
399 | ```css
400 | .App {
401 | display: -webkit-box;
402 | display: -ms-flexbox;
403 | display: flex;
404 | -webkit-box-orient: horizontal;
405 | -webkit-box-direction: normal;
406 | -ms-flex-direction: row;
407 | flex-direction: row;
408 | -webkit-box-align: center;
409 | -ms-flex-align: center;
410 | align-items: center;
411 | }
412 | ```
413 |
414 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
415 |
416 | ## Adding a CSS Preprocessor (Sass, Less etc.)
417 |
418 | Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `` and `` components, we recommend creating a `