27 | );
28 |
29 | InputToggle.propTypes = {
30 | id: PropTypes.string,
31 | name: PropTypes.string.isRequired,
32 | label: PropTypes.string,
33 | value: PropTypes.string,
34 | isChecked: PropTypes.bool,
35 | onClick: PropTypes.func.isRequired,
36 | isInvalid: PropTypes.bool,
37 | };
38 |
39 | InputToggle.defaultProps = {
40 | id: inputId,
41 | value: '',
42 | isChecked: false,
43 | label: '',
44 | isInvalid: false,
45 | };
46 |
47 | export default InputToggle;
48 |
--------------------------------------------------------------------------------
/src/containers/SecondStepForm/reducer.js:
--------------------------------------------------------------------------------
1 | import {
2 | SECOND_STEP_CHANGE_RADIO,
3 | SECOND_STEP_SHOW_PROGRESSBAR,
4 | SECOND_STEP_HIDE_PROGRESSBAR,
5 | SECOND_STEP_NEXT_STEP,
6 | } from './constants';
7 |
8 | export const secondStepFormInitialState = {
9 | b1: false,
10 | b2: false,
11 | showProgressBar: false,
12 | completed: false,
13 | };
14 |
15 | const verifyStateToGo = (state) => {
16 | if (state.b1 || state.b2) {
17 | return {
18 | ...state,
19 | completed: true,
20 | showProgressBar: false,
21 | };
22 | }
23 |
24 | return {
25 | ...state,
26 | showProgressBar: false,
27 | };
28 | };
29 |
30 | const secondStepFormReducer = (state = secondStepFormInitialState, action) => {
31 | switch (action.type) {
32 | case SECOND_STEP_CHANGE_RADIO:
33 | return {
34 | ...state,
35 | b1: action.payload.name === 'b1',
36 | b2: action.payload.name === 'b2',
37 | };
38 | case SECOND_STEP_SHOW_PROGRESSBAR:
39 | return {
40 | ...state,
41 | showProgressBar: true,
42 | };
43 | case SECOND_STEP_HIDE_PROGRESSBAR:
44 | return {
45 | ...state,
46 | showProgressBar: false,
47 | };
48 | case SECOND_STEP_NEXT_STEP:
49 | return verifyStateToGo(state);
50 | default:
51 | return state;
52 | }
53 | };
54 |
55 | export default secondStepFormReducer;
56 |
--------------------------------------------------------------------------------
/src/containers/FirstStepForm/FirstStepForm.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import Form from 'components/Form';
5 |
6 | import Container from 'components/Container';
7 | import Item from 'components/Item';
8 | import InputCheckBox from 'components/InputCheckBox';
9 | import ProgressBar from 'components/ProgressBar';
10 |
11 | const FirstStepForm = ({ onClickCheckBox, firstStepForm }) => (
12 |
27 | );
28 |
29 | FirstStepForm.propTypes = {
30 | onClickCheckBox: PropTypes.func.isRequired,
31 | firstStepForm: PropTypes.objectOf(PropTypes.bool).isRequired,
32 | };
33 |
34 | export default FirstStepForm;
35 |
--------------------------------------------------------------------------------
/src/containers/SecondStepForm/SecondStepForm.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import Container from 'components/Container';
5 | import Item from 'components/Item';
6 | import InputToggle from 'components/InputToggle';
7 | import Form from 'components/Form';
8 | import ProgressBar from 'components/ProgressBar';
9 |
10 | const SecondStepForm = ({ onClickRadio, secondStepForm }) => (
11 |
26 | );
27 |
28 | SecondStepForm.propTypes = {
29 | onClickRadio: PropTypes.func.isRequired,
30 | secondStepForm: PropTypes.objectOf(PropTypes.bool).isRequired,
31 | };
32 |
33 | export default SecondStepForm;
34 |
--------------------------------------------------------------------------------
/src/containers/ThirdStepForm/ThirdStepForm.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import Container from 'components/Container';
5 | import Item from 'components/Item';
6 | import InputText from 'components/InputText';
7 | import Button from 'components/Button';
8 | import Form from 'components/Form';
9 | import ProgressBar from 'components/ProgressBar';
10 |
11 | const ThirdStepForm = ({ onChangeInput, thirdStepForm, onClickCheck }) => (
12 |
27 | );
28 |
29 | ThirdStepForm.propTypes = {
30 | onChangeInput: PropTypes.func.isRequired,
31 | thirdStepForm: PropTypes.shape({
32 | text: PropTypes.string,
33 | errorMessage: PropTypes.string,
34 | completed: PropTypes.bool,
35 | }).isRequired,
36 | onClickCheck: PropTypes.func.isRequired,
37 | };
38 |
39 | export default ThirdStepForm;
40 |
--------------------------------------------------------------------------------
/src/containers/ComposeAllForms/ComposeAllForms.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | import Item from 'components/Item';
5 | import FirstStepForm from 'containers/FirstStepForm';
6 | import SecondStepForm from 'containers/SecondStepForm';
7 | import ThirdStepForm from 'containers/ThirdStepForm';
8 | import FourthStepForm from 'containers/FourthStepForm';
9 | import FivethStepForm from 'containers/FivethStepForm';
10 | import LastStep from 'containers/LastStep';
11 | import Header from 'components/Header';
12 | import StepsWrapper from 'components/StepsWrapper';
13 | import Container from 'components/Container';
14 | import Box from 'components/Box';
15 |
16 | const ComposeAllForms = ({ dataForm }) => {
17 | const { currentStep } = dataForm;
18 |
19 | return (
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 | {currentStep === 1 && }
30 | {currentStep === 2 && }
31 | {currentStep === 3 && }
32 | {currentStep === 4 && }
33 | {currentStep === 5 && }
34 | {currentStep === 6 && }
35 |
36 |
37 | );
38 | };
39 |
40 | ComposeAllForms.propTypes = {
41 | dataForm: PropTypes.shape({
42 | form: PropTypes.object,
43 | currentStep: PropTypes.number,
44 | }).isRequired,
45 | };
46 |
47 | export default ComposeAllForms;
48 |
--------------------------------------------------------------------------------
/src/components/Step/Step.sass:
--------------------------------------------------------------------------------
1 | @import 'css/variables'
2 |
3 | .step
4 | font-family: $font-stack
5 | border: 1px solid $gray-light
6 | display: inline-block
7 | border-radius: 50%
8 | background-color: $background-default
9 | font-size: $font-size-lg
10 | width: 50px
11 | height: 50px
12 | text-align: center
13 | line-height: 50px
14 | font-weight: 600
15 | color: $gray-default
16 | position: relative
17 | z-index: 1
18 |
19 | .is-completed
20 | background-color: $default-blue
21 | color: $default-blue
22 | border-color: $default-blue
23 |
24 | &:after
25 | content: ""
26 | border-bottom: 4px solid #fff
27 | border-left: 4px solid #fff
28 | transform: rotateZ(320deg)
29 | position: absolute
30 | width: 15px
31 | height: 7px
32 | top: 18px
33 | left: 15px
34 | opacity: 1
35 | animation-name: grow-check
36 | animation-duration: .5s
37 | animation-timing-function: linear
38 |
39 | .line-way
40 | display: inline-block
41 | height: 5px
42 | background-color: $gray-light
43 | width: 50px
44 | margin-left: -5px
45 | margin-right: -5px
46 | vertical-align: top
47 | position: relative
48 | z-index: 0
49 | top: 25px
50 |
51 | .is-line-completed
52 | background-color: $default-blue
53 |
54 | @keyframes grow-check
55 | 0%
56 | width: 8px
57 | height: 4px
58 | top: 21px
59 | left: 20px
60 | opacity: 0
61 | border-bottom: 2px solid #fff
62 | border-left: 2px solid #fff
63 |
64 | 80%
65 | width: 22px
66 | height: 10px
67 | top: 15px
68 | left: 13px
69 | border-bottom: 6px solid #fff
70 | border-left: 6px solid #fff
71 |
72 | 100%
73 | width: 15px
74 | height: 7px
75 | top: 18px
76 | left: 17px
77 | opacity: 1
78 | border-bottom: 4px solid #fff
79 | border-left: 4px solid #fff
80 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-multi-step-form",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "classnames": "^2.2.5",
7 | "prop-types": "^15.5.10",
8 | "react": "^15.6.1",
9 | "react-dnd": "^2.5.4",
10 | "react-dnd-html5-backend": "^2.5.4",
11 | "react-dom": "^15.6.1",
12 | "react-redux": "^5.0.6",
13 | "redux": "^3.7.2",
14 | "redux-persist": "^4.10.1",
15 | "redux-saga": "^0.16.0",
16 | "uid": "^0.0.2"
17 | },
18 | "scripts": {
19 | "start": "webpack-dev-server --open",
20 | "watch": "webpack --progress --watch",
21 | "build": "webpack --config webpack.config.js",
22 | "lint": "esw src/** -w",
23 | "lint:fix": "eslint src/** --fix",
24 | "storybook": "start-storybook -p 9001 -c .storybook",
25 | "test": "jest --config jestconfig.json",
26 | "test:watch": "jest --config jestconfig.json --watch",
27 | "test:cov": "jest --config jestconfig.json --coverage",
28 | "server:cov": "http-server ./coverage"
29 | },
30 | "devDependencies": {
31 | "@storybook/addon-actions": "^3.2.16",
32 | "@storybook/addon-info": "^3.2.16",
33 | "@storybook/react": "^3.2.16",
34 | "babel-core": "^6.25.0",
35 | "babel-loader": "^7.1.1",
36 | "babel-plugin-transform-object-rest-spread": "^6.26.0",
37 | "babel-preset-env": "^1.6.0",
38 | "babel-preset-react": "^6.24.1",
39 | "coveralls": "^3.0.0",
40 | "css-loader": "^0.28.4",
41 | "enzyme": "^2.9.1",
42 | "enzyme-to-json": "2.0.1",
43 | "eslint": "^3",
44 | "eslint-config-airbnb": "^15.0.2",
45 | "eslint-config-airbnb-base": "^11.2.0",
46 | "eslint-import-resolver-webpack": "^0.8.3",
47 | "eslint-plugin-import": "^2.8.0",
48 | "eslint-plugin-jsx-a11y": "^5.1.1",
49 | "eslint-plugin-react": "^7.1.0",
50 | "eslint-watch": "^3.1.2",
51 | "http-server": "^0.10.0",
52 | "identity-obj-proxy": "^3.0.0",
53 | "jest": "^20.0.4",
54 | "jest-enzyme": "^3.4.0",
55 | "node-sass": "^4.5.3",
56 | "react-addons-test-utils": "^15.6.0",
57 | "react-dnd-test-backend": "^2.5.4",
58 | "react-test-renderer": "^15.6.1",
59 | "sass-loader": "^6.0.6",
60 | "style-loader": "^0.18.2",
61 | "webpack": "^2.2.0",
62 | "webpack-dev-server": "^2.5.0"
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Multi Step Form
2 | It's a simple step-by-step form using React/Redux. Created to solve this [challenge](https://gist.github.com/rewop/d3aa46cb3874c2a47e51c0a33f1f60f6#file-api-js).
3 |
4 | ## The project
5 |
6 | ### The structure
7 |
8 | ```
9 | |- src/
10 | |- components
11 | |- containers
12 | |- store
13 | |- saga
14 | |- css
15 | ```
16 |
17 | ### Presentational components
18 | First of all I created the `components` module containing all presentational components. Only these components can be styled. These components are leaned on their `css` and `test` files.
19 |
20 | ```
21 | |- components
22 | |- Step
23 | |- index.js
24 | |- Step.js
25 | |- Step.css.js
26 | |- Step.test.js
27 | ```
28 |
29 | ### Containers components
30 | The `containers` folder has to organize only the containers components to map the redux states and dispatch to props. Here you should create the *actions, reducers, constants, sagas*. And the most important, the **component** that will receive the props.
31 |
32 | ```
33 | |- containers
34 | |- FirstStepForm
35 | |- FirstStepForm.js
36 | |- actions.js
37 | |- constants.js
38 | |- container.js
39 | |- index.js
40 | |- reducer.js
41 | |- sagas.js
42 | ```
43 |
44 | ### Store
45 | The `store` folder was created to combine the "thousands and thousands" reducers of the applications and apply any middleware.
46 |
47 | ### Saga
48 | The `saga` folder was created to combine all sagas of the application.
49 |
50 | ### Css
51 | And finally `css` is where the general styles are introduced to reset the application, and some root configurations for `sass` like *_variables* and *_mixins*.
52 |
53 | ## Layout
54 | I think that one of the things most dificult to define is the style(colors and the ux desing), so I've considered figure it out searching some designs to get inspired.
55 |
56 | - The style was inspired by the [Asana Login](https://app.asana.com/-/login). I liked it :smile:, didn't you?
57 |
58 | ## Technologies
59 |
60 | - **JavaScript** - *ES6+ (Babel)*;
61 | - **UI Components** - *React*;
62 | - **State management** - *Redux, React Redux, Redux Saga*;
63 | - **Preprocessor** - *Sass*;
64 | - **Modules** - *Webpack, CSS Modules*;
65 | - **Unit tests**: *Jest, Enzyme*;
66 | - **Clean code** - *Lint*;
67 |
68 | ## Getting started
69 | I encourage you to use the `yarn` to install the packages, you'll enjoy the yarn.lock to a faster installation, and the scripts will be fast too.
70 |
71 | ### Install
72 | ```
73 | yarn
74 | ```
75 |
76 | ### Start app
77 | ```
78 | yarn start
79 | ```
80 |
81 | ### Running tests
82 | ```
83 | yarn test
84 | ```
85 |
86 | ### Watching the tests
87 | ```
88 | yarn test:watch
89 | ```
90 |
91 | ### Running coverage
92 | ```
93 | yarn test:cov
94 | ```
95 |
96 | ### Start Coverage Server
97 | ```
98 | yarn server:cov
99 | ```
100 |
101 | ### Running ESLint
102 | ```
103 | yarn lint
104 | ```
105 |
106 | ### Troubleshoot Lint issues
107 | ```
108 | yarn lint:fix
109 | ```
110 |
111 | ### Storybook
112 | ```
113 | yarn storybook
114 | ```
115 |
116 | ### Production build
117 | ```
118 | yarn build
119 | ```
120 |
121 | ### Production build watch
122 | ```
123 | yarn watch
124 | ```
125 |
126 | ## Credits
127 | Created by [jmlavoier](https://github.com/jmlavoier)
128 |
--------------------------------------------------------------------------------
/src/components/Form/__snapshots__/Form.test.js.snap:
--------------------------------------------------------------------------------
1 | // Jest Snapshot v1, https://goo.gl/fbAQLP
2 |
3 | exports[`Should component render text 1`] = `
4 |
216 | `;
217 |
--------------------------------------------------------------------------------
/README-CREATE-REACT-APP.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 | - [Formatting Code Automatically](#formatting-code-automatically)
21 | - [Changing the Page ``](#changing-the-page-title)
22 | - [Installing a Dependency](#installing-a-dependency)
23 | - [Importing a Component](#importing-a-component)
24 | - [Code Splitting](#code-splitting)
25 | - [Adding a Stylesheet](#adding-a-stylesheet)
26 | - [Post-Processing CSS](#post-processing-css)
27 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
28 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
29 | - [Using the `public` Folder](#using-the-public-folder)
30 | - [Changing the HTML](#changing-the-html)
31 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
32 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
33 | - [Using Global Variables](#using-global-variables)
34 | - [Adding Bootstrap](#adding-bootstrap)
35 | - [Using a Custom Theme](#using-a-custom-theme)
36 | - [Adding Flow](#adding-flow)
37 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
38 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
39 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
40 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
41 | - [Can I Use Decorators?](#can-i-use-decorators)
42 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
43 | - [Node](#node)
44 | - [Ruby on Rails](#ruby-on-rails)
45 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
46 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
47 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
48 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
49 | - [Using HTTPS in Development](#using-https-in-development)
50 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
51 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
52 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
53 | - [Running Tests](#running-tests)
54 | - [Filename Conventions](#filename-conventions)
55 | - [Command Line Interface](#command-line-interface)
56 | - [Version Control Integration](#version-control-integration)
57 | - [Writing Tests](#writing-tests)
58 | - [Testing Components](#testing-components)
59 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
60 | - [Initializing Test Environment](#initializing-test-environment)
61 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
62 | - [Coverage Reporting](#coverage-reporting)
63 | - [Continuous Integration](#continuous-integration)
64 | - [Disabling jsdom](#disabling-jsdom)
65 | - [Snapshot Testing](#snapshot-testing)
66 | - [Editor Integration](#editor-integration)
67 | - [Developing Components in Isolation](#developing-components-in-isolation)
68 | - [Getting Started with Storybook](#getting-started-with-storybook)
69 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
70 | - [Making a Progressive Web App](#making-a-progressive-web-app)
71 | - [Opting Out of Caching](#opting-out-of-caching)
72 | - [Offline-First Considerations](#offline-first-considerations)
73 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
74 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
75 | - [Deployment](#deployment)
76 | - [Static Server](#static-server)
77 | - [Other Solutions](#other-solutions)
78 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
79 | - [Building for Relative Paths](#building-for-relative-paths)
80 | - [Azure](#azure)
81 | - [Firebase](#firebase)
82 | - [GitHub Pages](#github-pages)
83 | - [Heroku](#heroku)
84 | - [Netlify](#netlify)
85 | - [Now](#now)
86 | - [S3 and CloudFront](#s3-and-cloudfront)
87 | - [Surge](#surge)
88 | - [Advanced Configuration](#advanced-configuration)
89 | - [Troubleshooting](#troubleshooting)
90 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes)
91 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
92 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
93 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
94 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
95 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
96 | - [Something Missing?](#something-missing)
97 |
98 | ## Updating to New Releases
99 |
100 | Create React App is divided into two packages:
101 |
102 | * `create-react-app` is a global command-line utility that you use to create new projects.
103 | * `react-scripts` is a development dependency in the generated projects (including this one).
104 |
105 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
106 |
107 | 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.
108 |
109 | 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.
110 |
111 | 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.
112 |
113 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
114 |
115 | ## Sending Feedback
116 |
117 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
118 |
119 | ## Folder Structure
120 |
121 | After creation, your project should look like this:
122 |
123 | ```
124 | my-app/
125 | README.md
126 | node_modules/
127 | package.json
128 | public/
129 | index.html
130 | favicon.ico
131 | src/
132 | App.css
133 | App.js
134 | App.test.js
135 | index.css
136 | index.js
137 | logo.svg
138 | ```
139 |
140 | For the project to build, **these files must exist with exact filenames**:
141 |
142 | * `public/index.html` is the page template;
143 | * `src/index.js` is the JavaScript entry point.
144 |
145 | You can delete or rename the other files.
146 |
147 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
148 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them.
149 |
150 | Only files inside `public` can be used from `public/index.html`.
151 | Read instructions below for using assets from JavaScript and HTML.
152 |
153 | You can, however, create more top-level directories.
154 | They will not be included in the production build so you can use them for things like documentation.
155 |
156 | ## Available Scripts
157 |
158 | In the project directory, you can run:
159 |
160 | ### `npm start`
161 |
162 | Runs the app in the development mode.
163 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
164 |
165 | The page will reload if you make edits.
166 | You will also see any lint errors in the console.
167 |
168 | ### `npm test`
169 |
170 | Launches the test runner in the interactive watch mode.
171 | See the section about [running tests](#running-tests) for more information.
172 |
173 | ### `npm run build`
174 |
175 | Builds the app for production to the `build` folder.
176 | It correctly bundles React in production mode and optimizes the build for the best performance.
177 |
178 | The build is minified and the filenames include the hashes.
179 | Your app is ready to be deployed!
180 |
181 | See the section about [deployment](#deployment) for more information.
182 |
183 | ### `npm run eject`
184 |
185 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!**
186 |
187 | 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.
188 |
189 | 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.
190 |
191 | 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.
192 |
193 | ## Supported Language Features and Polyfills
194 |
195 | This project supports a superset of the latest JavaScript standard.
196 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
197 |
198 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
199 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
200 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
201 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
202 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
203 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
204 |
205 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
206 |
207 | While we recommend using 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.
208 |
209 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
210 |
211 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
212 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
213 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
214 |
215 | 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.
216 |
217 | ## Syntax Highlighting in the Editor
218 |
219 | 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.
220 |
221 | ## Displaying Lint Output in the Editor
222 |
223 | >Note: this feature is available with `react-scripts@0.2.0` and higher.
224 | >It also only works with npm 3 or higher.
225 |
226 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
227 |
228 | 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.
229 |
230 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
231 |
232 | ```js
233 | {
234 | "extends": "react-app"
235 | }
236 | ```
237 |
238 | Now your editor should report the linting warnings.
239 |
240 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes.
241 |
242 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
243 |
244 | ## Debugging in the Editor
245 |
246 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
247 |
248 | Visual Studio Code and WebStorm support 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.
249 |
250 | ### Visual Studio Code
251 |
252 | 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.
253 |
254 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory.
255 |
256 | ```json
257 | {
258 | "version": "0.2.0",
259 | "configurations": [{
260 | "name": "Chrome",
261 | "type": "chrome",
262 | "request": "launch",
263 | "url": "http://localhost:3000",
264 | "webRoot": "${workspaceRoot}/src",
265 | "sourceMapPathOverrides": {
266 | "webpack:///src/*": "${webRoot}/*"
267 | }
268 | }]
269 | }
270 | ```
271 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
272 |
273 | 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.
274 |
275 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting).
276 |
277 | ### WebStorm
278 |
279 | You would need to have [WebStorm](https://www.jetbrains.com/webstorm/) and [JetBrains IDE Support](https://chrome.google.com/webstore/detail/jetbrains-ide-support/hmhgeddbohgjknpmjagkdomcpobmllji) Chrome extension installed.
280 |
281 | In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `JavaScript Debug`. Paste `http://localhost:3000` into the URL field and save the configuration.
282 |
283 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
284 |
285 | Start your app by running `npm start`, then press `^D` on macOS or `F9` on Windows and Linux or click the green debug icon to start debugging in WebStorm.
286 |
287 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
288 |
289 | ## Formatting Code Automatically
290 |
291 | Prettier is an opinionated code formatter with support for JavaScript, CSS and JSON. With Prettier you can format the code you write automatically to ensure a code style within your project. See the [Prettier's GitHub page](https://github.com/prettier/prettier) for more information, and look at this [page to see it in action](https://prettier.github.io/prettier/).
292 |
293 | To format our code whenever we make a commit in git, we need to install the following dependencies:
294 |
295 | ```sh
296 | npm install --save husky lint-staged prettier
297 | ```
298 |
299 | Alternatively you may use `yarn`:
300 |
301 | ```sh
302 | yarn add husky lint-staged prettier
303 | ```
304 |
305 | * `husky` makes it easy to use githooks as if they are npm scripts.
306 | * `lint-staged` allows us to run scripts on staged files in git. See this [blog post about lint-staged to learn more about it](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8).
307 | * `prettier` is the JavaScript formatter we will run before commits.
308 |
309 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
310 |
311 | Add the following line to `scripts` section:
312 |
313 | ```diff
314 | "scripts": {
315 | + "precommit": "lint-staged",
316 | "start": "react-scripts start",
317 | "build": "react-scripts build",
318 | ```
319 |
320 | Next we add a 'lint-staged' field to the `package.json`, for example:
321 |
322 | ```diff
323 | "dependencies": {
324 | // ...
325 | },
326 | + "lint-staged": {
327 | + "src/**/*.{js,jsx,json,css}": [
328 | + "prettier --single-quote --write",
329 | + "git add"
330 | + ]
331 | + },
332 | "scripts": {
333 | ```
334 |
335 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time.
336 |
337 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page.
338 |
339 | ## Changing the Page ``
340 |
341 | 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.
342 |
343 | 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.
344 |
345 | 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.
346 |
347 | 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).
348 |
349 | ## Installing a Dependency
350 |
351 | 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`:
352 |
353 | ```sh
354 | npm install --save react-router
355 | ```
356 |
357 | Alternatively you may use `yarn`:
358 |
359 | ```sh
360 | yarn add react-router
361 | ```
362 |
363 | This works for any library, not just `react-router`.
364 |
365 | ## Importing a Component
366 |
367 | This project setup supports ES6 modules thanks to Babel.
368 | 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.
369 |
370 | For example:
371 |
372 | ### `Button.js`
373 |
374 | ```js
375 | import React, { Component } from 'react';
376 |
377 | class Button extends Component {
378 | render() {
379 | // ...
380 | }
381 | }
382 |
383 | export default Button; // Don’t forget to use export default!
384 | ```
385 |
386 | ### `DangerButton.js`
387 |
388 |
389 | ```js
390 | import React, { Component } from 'react';
391 | import Button from './Button'; // Import a component from another file
392 |
393 | class DangerButton extends Component {
394 | render() {
395 | return ;
396 | }
397 | }
398 |
399 | export default DangerButton;
400 | ```
401 |
402 | 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.
403 |
404 | 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'`.
405 |
406 | 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.
407 |
408 | Learn more about ES6 modules:
409 |
410 | * [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)
411 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
412 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
413 |
414 | ## Code Splitting
415 |
416 | Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.
417 |
418 | This project setup supports code splitting via [dynamic `import()`](http://2ality.com/2017/01/import-operator.html#loading-code-on-demand). Its [proposal](https://github.com/tc39/proposal-dynamic-import) is in stage 3. The `import()` function-like form takes the module name as an argument and returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which always resolves to the namespace object of the module.
419 |
420 | Here is an example:
421 |
422 | ### `moduleA.js`
423 |
424 | ```js
425 | const moduleA = 'Hello';
426 |
427 | export { moduleA };
428 | ```
429 | ### `App.js`
430 |
431 | ```js
432 | import React, { Component } from 'react';
433 |
434 | class App extends Component {
435 | handleClick = () => {
436 | import('./moduleA')
437 | .then(({ moduleA }) => {
438 | // Use moduleA
439 | })
440 | .catch(err => {
441 | // Handle failure
442 | });
443 | };
444 |
445 | render() {
446 | return (
447 |
448 | Load
449 |
450 | );
451 | }
452 | }
453 |
454 | export default App;
455 | ```
456 |
457 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
458 |
459 | You can also use it with `async` / `await` syntax if you prefer it.
460 |
461 | ### With React Router
462 |
463 | If you are using React Router check out [this tutorial](http://serverless-stack.com/chapters/code-splitting-in-create-react-app.html) on how to use code splitting with it. You can find the companion GitHub repository [here](https://github.com/AnomalyInnovations/serverless-stack-demo-client/tree/code-splitting-in-create-react-app).
464 |
465 | ## Adding a Stylesheet
466 |
467 | This project setup uses [Webpack](https://webpack.js.org/) 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**:
468 |
469 | ### `Button.css`
470 |
471 | ```css
472 | .Button {
473 | padding: 20px;
474 | }
475 | ```
476 |
477 | ### `Button.js`
478 |
479 | ```js
480 | import React, { Component } from 'react';
481 | import './Button.css'; // Tell Webpack that Button.js uses these styles
482 |
483 | class Button extends Component {
484 | render() {
485 | // You can use them as regular CSS styles
486 | return ;
487 | }
488 | }
489 | ```
490 |
491 | **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.
492 |
493 | 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.
494 |
495 | 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.
496 |
497 | ## Post-Processing CSS
498 |
499 | 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.
500 |
501 | For example, this:
502 |
503 | ```css
504 | .App {
505 | display: flex;
506 | flex-direction: row;
507 | align-items: center;
508 | }
509 | ```
510 |
511 | becomes this:
512 |
513 | ```css
514 | .App {
515 | display: -webkit-box;
516 | display: -ms-flexbox;
517 | display: flex;
518 | -webkit-box-orient: horizontal;
519 | -webkit-box-direction: normal;
520 | -ms-flex-direction: row;
521 | flex-direction: row;
522 | -webkit-box-align: center;
523 | -ms-flex-align: center;
524 | align-items: center;
525 | }
526 | ```
527 |
528 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
529 |
530 | ## Adding a CSS Preprocessor (Sass, Less etc.)
531 |
532 | 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 `` component with its own `.Button` styles, that both `` and `` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)).
533 |
534 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative.
535 |
536 | First, let’s install the command-line interface for Sass:
537 |
538 | ```sh
539 | npm install --save node-sass-chokidar
540 | ```
541 |
542 | Alternatively you may use `yarn`:
543 |
544 | ```sh
545 | yarn add node-sass-chokidar
546 | ```
547 |
548 | Then in `package.json`, add the following lines to `scripts`:
549 |
550 | ```diff
551 | "scripts": {
552 | + "build-css": "node-sass-chokidar src/ -o src/",
553 | + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
554 | "start": "react-scripts start",
555 | "build": "react-scripts build",
556 | "test": "react-scripts test --env=jsdom",
557 | ```
558 |
559 | >Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation.
560 |
561 | Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated.
562 |
563 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions.
564 |
565 | To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`.
566 |
567 | ```
568 | "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
569 | "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
570 | ```
571 |
572 | This will allow you to do imports like
573 |
574 | ```scss
575 | @import 'styles/_colors.scss'; // assuming a styles directory under src/
576 | @import 'nprogress/nprogress'; // importing a css file from the nprogress node module
577 | ```
578 |
579 | At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control.
580 |
581 | As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this:
582 |
583 | ```sh
584 | npm install --save npm-run-all
585 | ```
586 |
587 | Alternatively you may use `yarn`:
588 |
589 | ```sh
590 | yarn add npm-run-all
591 | ```
592 |
593 | Then we can change `start` and `build` scripts to include the CSS preprocessor commands:
594 |
595 | ```diff
596 | "scripts": {
597 | "build-css": "node-sass-chokidar src/ -o src/",
598 | "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive",
599 | - "start": "react-scripts start",
600 | - "build": "react-scripts build",
601 | + "start-js": "react-scripts start",
602 | + "start": "npm-run-all -p watch-css start-js",
603 | + "build-js": "react-scripts build",
604 | + "build": "npm-run-all build-css build-js",
605 | "test": "react-scripts test --env=jsdom",
606 | "eject": "react-scripts eject"
607 | }
608 | ```
609 |
610 | Now running `npm start` and `npm run build` also builds Sass files.
611 |
612 | **Why `node-sass-chokidar`?**
613 |
614 | `node-sass` has been reported as having the following issues:
615 |
616 | - `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker.
617 |
618 | - Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939)
619 |
620 | - `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891)
621 |
622 | `node-sass-chokidar` is used here as it addresses these issues.
623 |
624 | ## Adding Images, Fonts, and Files
625 |
626 | With Webpack, using static assets like images and fonts works similarly to CSS.
627 |
628 | You can **`import` a file right in a JavaScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF.
629 |
630 | To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153).
631 |
632 | Here is an example:
633 |
634 | ```js
635 | import React from 'react';
636 | import logo from './logo.png'; // Tell Webpack this JS file uses this image
637 |
638 | console.log(logo); // /logo.84287d09.png
639 |
640 | function Header() {
641 | // Import result is the URL of your image
642 | return ;
643 | }
644 |
645 | export default Header;
646 | ```
647 |
648 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths.
649 |
650 | This works in CSS too:
651 |
652 | ```css
653 | .Logo {
654 | background-image: url(./logo.png);
655 | }
656 | ```
657 |
658 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets.
659 |
660 | Please be advised that this is also a custom feature of Webpack.
661 |
662 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).
663 | An alternative way of handling static assets is described in the next section.
664 |
665 | ## Using the `public` Folder
666 |
667 | >Note: this feature is available with `react-scripts@0.5.0` and higher.
668 |
669 | ### Changing the HTML
670 |
671 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title).
672 | The `
1180 | ```
1181 |
1182 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.**
1183 |
1184 | ## Running Tests
1185 |
1186 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
1187 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030)
1188 |
1189 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try.
1190 |
1191 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness.
1192 |
1193 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks.
1194 |
1195 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App.
1196 |
1197 | ### Filename Conventions
1198 |
1199 | Jest will look for test files with any of the following popular naming conventions:
1200 |
1201 | * Files with `.js` suffix in `__tests__` folders.
1202 | * Files with `.test.js` suffix.
1203 | * Files with `.spec.js` suffix.
1204 |
1205 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder.
1206 |
1207 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects.
1208 |
1209 | ### Command Line Interface
1210 |
1211 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code.
1212 |
1213 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run:
1214 |
1215 | 
1216 |
1217 | ### Version Control Integration
1218 |
1219 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests.
1220 |
1221 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests.
1222 |
1223 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository.
1224 |
1225 | ### Writing Tests
1226 |
1227 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended.
1228 |
1229 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this:
1230 |
1231 | ```js
1232 | import sum from './sum';
1233 |
1234 | it('sums numbers', () => {
1235 | expect(sum(1, 2)).toEqual(3);
1236 | expect(sum(2, 2)).toEqual(4);
1237 | });
1238 | ```
1239 |
1240 | All `expect()` matchers supported by Jest are [extensively documented here](https://facebook.github.io/jest/docs/en/expect.html#content).
1241 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](https://facebook.github.io/jest/docs/en/expect.html#tohavebeencalled) to create “spies” or mock functions.
1242 |
1243 | ### Testing Components
1244 |
1245 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes.
1246 |
1247 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components:
1248 |
1249 | ```js
1250 | import React from 'react';
1251 | import ReactDOM from 'react-dom';
1252 | import App from './App';
1253 |
1254 | it('renders without crashing', () => {
1255 | const div = document.createElement('div');
1256 | ReactDOM.render(, div);
1257 | });
1258 | ```
1259 |
1260 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`.
1261 |
1262 | When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior.
1263 |
1264 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run:
1265 |
1266 | ```sh
1267 | npm install --save enzyme enzyme-adapter-react-16 react-test-renderer
1268 | ```
1269 |
1270 | Alternatively you may use `yarn`:
1271 |
1272 | ```sh
1273 | yarn add enzyme enzyme-adapter-react-16 react-test-renderer
1274 | ```
1275 |
1276 | As of Enzyme 3, you will need to install Enzyme along with an Adapter corresponding to the version of React you are using. (The examples above use the adapter for React 16.)
1277 |
1278 | The adapter will also need to be configured in your [global setup file](#initializing-test-environment):
1279 |
1280 | #### `src/setupTests.js`
1281 | ```js
1282 | import { configure } from 'enzyme';
1283 | import Adapter from 'enzyme-adapter-react-16';
1284 |
1285 | configure({ adapter: new Adapter() });
1286 | ```
1287 |
1288 | Now you can write a smoke test with it:
1289 |
1290 | ```js
1291 | import React from 'react';
1292 | import { shallow } from 'enzyme';
1293 | import App from './App';
1294 |
1295 | it('renders without crashing', () => {
1296 | shallow();
1297 | });
1298 | ```
1299 |
1300 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `` that throws, this test will pass. Shallow rendering is great for isolated unit tests, but you may still want to create some full rendering tests to ensure the components integrate correctly. Enzyme supports [full rendering with `mount()`](http://airbnb.io/enzyme/docs/api/mount.html), and you can also use it for testing state changes and component lifecycle.
1301 |
1302 | You can read the [Enzyme documentation](http://airbnb.io/enzyme/) for more testing techniques. Enzyme documentation uses Chai and Sinon for assertions but you don’t have to use them because Jest provides built-in `expect()` and `jest.fn()` for spies.
1303 |
1304 | Here is an example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
1305 |
1306 | ```js
1307 | import React from 'react';
1308 | import { shallow } from 'enzyme';
1309 | import App from './App';
1310 |
1311 | it('renders welcome message', () => {
1312 | const wrapper = shallow();
1313 | const welcome =