21 | );
22 | }
23 | }
24 |
25 | ExampleStuckContent.baseClass = 'ExampleStuckContent';
26 |
27 | export default ExampleStuckContent;
28 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App__head {
6 | }
7 |
8 | .App__title {
9 | font-size: 1.5em;
10 | padding: 20px;
11 | }
12 |
13 | .ExampleStuckContent {
14 | position: relative;
15 | padding: 10px;
16 | }
17 |
18 | .ExampleStuckContent__label {
19 | position: absolute;
20 | border-radius: 2px;
21 | bottom: 5px;
22 | right: 5px;
23 | background: black;
24 | color: white;
25 | padding: 5px;
26 | }
27 |
28 | .ExampleStuckContent--stuck-top {
29 | position: fixed;
30 | top: 0;
31 | left: 0;
32 | right: 0;
33 | background-color: orange;
34 | z-index: 1;
35 | }
36 | .ExampleStuckContent--stuck-bottom {
37 | position: fixed;
38 | bottom: 0;
39 | left: 0;
40 | right: 0;
41 | background-color: yellow;
42 | z-index: 1;
43 | }
44 | .ExampleStuckContent--stuck-left {
45 | outline: 5px solid cyan;
46 | }
47 | .ExampleStuckContent--stuck-right {
48 | outline: 5px solid salmon;
49 | }
50 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Chris Garcia
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (https://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # TypeScript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 | # next.js build output
61 | .next
62 |
63 | # testing
64 | /coverage
65 |
66 | # production
67 | # /build
68 |
69 | # misc
70 | .DS_Store
71 |
--------------------------------------------------------------------------------
/src/App.jsx:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import './App.css';
3 | import Sticky from './Sticky.jsx';
4 | import ExampleStuckContent from './ExampleStuckContent.jsx';
5 | import PlaceholderP from './PlaceholderP.jsx';
6 |
7 | class App extends Component {
8 | render
9 | render() {
10 | return (
11 |
12 |
13 | React sticky header
14 |
15 |
16 | This content should scroll normally
17 |
18 |
19 |
20 |
21 | This is a stickable component.
22 | It will get a prop called "modifiers" containing an array of strings like "stuck-top" when it's been scrolled out of view.
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | This component sticks to the bottom.
31 | It will get a prop called "modifiers" containing an array of strings like "stuck-top" when it's been scrolled out of view.
32 |
33 |
34 |
35 |
36 |
37 | );
38 | }
39 | }
40 |
41 | export default App;
42 |
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
22 | React Sticky
23 |
24 |
25 |
28 |
29 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/src/registerServiceWorker.js:
--------------------------------------------------------------------------------
1 | // In production, we register a service worker to serve assets from local cache.
2 |
3 | // This lets the app load faster on subsequent visits in production, and gives
4 | // it offline capabilities. However, it also means that developers (and users)
5 | // will only see deployed updates on the "N+1" visit to a page, since previously
6 | // cached resources are updated in the background.
7 |
8 | // To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
9 | // This link also includes instructions on opting out of this behavior.
10 |
11 | const isLocalhost = Boolean(
12 | window.location.hostname === 'localhost' ||
13 | // [::1] is the IPv6 localhost address.
14 | window.location.hostname === '[::1]' ||
15 | // 127.0.0.1/8 is considered localhost for IPv4.
16 | window.location.hostname.match(
17 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
18 | )
19 | );
20 |
21 | export default function register() {
22 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
23 | // The URL constructor is available in all browsers that support SW.
24 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
25 | if (publicUrl.origin !== window.location.origin) {
26 | // Our service worker won't work if PUBLIC_URL is on a different origin
27 | // from what our page is served on. This might happen if a CDN is used to
28 | // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
29 | return;
30 | }
31 |
32 | window.addEventListener('load', () => {
33 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
34 |
35 | if (isLocalhost) {
36 | // This is running on localhost. Lets check if a service worker still exists or not.
37 | checkValidServiceWorker(swUrl);
38 |
39 | // Add some additional logging to localhost, pointing developers to the
40 | // service worker/PWA documentation.
41 | navigator.serviceWorker.ready.then(() => {
42 | console.log(
43 | 'This web app is being served cache-first by a service ' +
44 | 'worker. To learn more, visit https://goo.gl/SC7cgQ'
45 | );
46 | });
47 | } else {
48 | // Is not local host. Just register service worker
49 | registerValidSW(swUrl);
50 | }
51 | });
52 | }
53 | }
54 |
55 | function registerValidSW(swUrl) {
56 | navigator.serviceWorker
57 | .register(swUrl)
58 | .then(registration => {
59 | registration.onupdatefound = () => {
60 | const installingWorker = registration.installing;
61 | installingWorker.onstatechange = () => {
62 | if (installingWorker.state === 'installed') {
63 | if (navigator.serviceWorker.controller) {
64 | // At this point, the old content will have been purged and
65 | // the fresh content will have been added to the cache.
66 | // It's the perfect time to display a "New content is
67 | // available; please refresh." message in your web app.
68 | console.log('New content is available; please refresh.');
69 | } else {
70 | // At this point, everything has been precached.
71 | // It's the perfect time to display a
72 | // "Content is cached for offline use." message.
73 | console.log('Content is cached for offline use.');
74 | }
75 | }
76 | };
77 | };
78 | })
79 | .catch(error => {
80 | console.error('Error during service worker registration:', error);
81 | });
82 | }
83 |
84 | function checkValidServiceWorker(swUrl) {
85 | // Check if the service worker can be found. If it can't reload the page.
86 | fetch(swUrl)
87 | .then(response => {
88 | // Ensure service worker exists, and that we really are getting a JS file.
89 | if (
90 | response.status === 404 ||
91 | response.headers.get('content-type').indexOf('javascript') === -1
92 | ) {
93 | // No service worker found. Probably a different app. Reload the page.
94 | navigator.serviceWorker.ready.then(registration => {
95 | registration.unregister().then(() => {
96 | window.location.reload();
97 | });
98 | });
99 | } else {
100 | // Service worker found. Proceed as normal.
101 | registerValidSW(swUrl);
102 | }
103 | })
104 | .catch(() => {
105 | console.log(
106 | 'No internet connection found. App is running in offline mode.'
107 | );
108 | });
109 | }
110 |
111 | export function unregister() {
112 | if ('serviceWorker' in navigator) {
113 | navigator.serviceWorker.ready.then(registration => {
114 | registration.unregister();
115 | });
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/src/Sticky.jsx:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import PropTypes from 'prop-types';
3 |
4 | class Sticky extends Component {
5 | static baseClass = 'tk-sticky'
6 |
7 | state = {
8 | height: 0,
9 | width: 0,
10 | stuckBottom: false,
11 | stuckLeft: false,
12 | stuckRight: false,
13 | stuckTop: false,
14 | }
15 |
16 | componentDidMount() {
17 | this.addEvents();
18 | this.handleScroll();
19 | }
20 |
21 | componentDidUpdate(prevProps) {
22 | if (prevProps.scrollTarget !== this.props.scrollTarget) {
23 | this.removeEvents();
24 | this.addEvents();
25 | }
26 | }
27 |
28 | componentWillUnmount() {
29 | this.removeEvents();
30 | }
31 |
32 | frameId = 0
33 |
34 | stickyDiv = React.createRef();
35 |
36 | handleScroll = () => {
37 | const { sides } = this.props;
38 | const stickyDiv = this.stickyDiv.current || null;
39 | const scrollTarget = this.props.scrollTarget || window;
40 |
41 | this.frameId = 0;
42 |
43 | if (!stickyDiv) {
44 | return;
45 | }
46 |
47 | let scrollRect = { // scrollTarget is the window
48 | height: scrollTarget.innerHeight,
49 | width: scrollTarget.innerWidth,
50 | top: 0,
51 | bottom: 0,
52 | left: 0,
53 | right: 0,
54 | x: scrollTarget.scrollX,
55 | y: scrollTarget.scrollY,
56 | };
57 |
58 | if (scrollTarget.getBoundingClientRect) { // scrollTarget is not the window
59 | scrollRect = scrollTarget.getBoundingClientRect();
60 | }
61 |
62 | let stickyRect = stickyDiv.getBoundingClientRect();
63 |
64 | if (!this.state.height || !this.state.width) {
65 | this.setState({
66 | height: stickyRect.height,
67 | width: stickyRect.height,
68 | });
69 | }
70 |
71 | stickyRect = { // Apparently you can't spread the results of a bounding client rectangle
72 | height: this.state.height || stickyRect.height,
73 | width: this.state.width || stickyRect.width,
74 | x: stickyRect.x,
75 | y: stickyRect.y,
76 | };
77 |
78 | if (typeof sides.bottom === 'number') {
79 | if (stickyRect.y + stickyRect.height > (scrollRect.height + scrollRect.top) - sides.bottom) {
80 | this.setState({ stuckBottom: true });
81 | } else {
82 | this.setState({ stuckBottom: false });
83 | }
84 | }
85 |
86 | if (typeof sides.top === 'number') {
87 | if (stickyRect.y < scrollRect.top + sides.top) {
88 | this.setState({ stuckTop: true });
89 | } else {
90 | this.setState({ stuckTop: false });
91 | }
92 | }
93 |
94 | if (typeof sides.left === 'number') {
95 | if (stickyRect.x < scrollRect.left + sides.left) {
96 | this.setState({ stuckLeft: true });
97 | } else {
98 | this.setState({ stuckLeft: false });
99 | }
100 | }
101 |
102 | if (typeof sides.right === 'number') {
103 | if (stickyRect.x + stickyRect.width > (scrollRect.width + scrollRect.left) - sides.right) {
104 | this.setState({ stuckRight: true });
105 | } else {
106 | this.setState({ stuckRight: false });
107 | }
108 | }
109 | }
110 |
111 | debouncedScroll = () => {
112 | if (!this.frameId) {
113 | const frameId = requestAnimationFrame(this.handleScroll);
114 | this.frameId = frameId;
115 | }
116 | }
117 |
118 | addEvents() {
119 | const scrollTarget = this.props.scrollTarget || window;
120 |
121 | if (scrollTarget && this.stickyDiv.current) {
122 | scrollTarget.addEventListener('scroll', this.debouncedScroll);
123 | }
124 | }
125 |
126 | removeEvents() {
127 | const scrollTarget = this.props.scrollTarget || window;
128 |
129 | if (scrollTarget) {
130 | scrollTarget.removeEventListener('scroll', this.debouncedScroll);
131 | }
132 |
133 | if (this.frameId) {
134 | cancelAnimationFrame(this.frameId);
135 | }
136 | }
137 |
138 | render() {
139 | const { children } = this.props;
140 | const { stuckBottom, stuckLeft, stuckRight, stuckTop } = this.state;
141 |
142 | const stickyModifiers = [];
143 |
144 | if (stuckBottom) {
145 | stickyModifiers.push('stuck-bottom');
146 | }
147 |
148 | if (stuckLeft) {
149 | stickyModifiers.push('stuck-left');
150 | }
151 |
152 | if (stuckRight) {
153 | stickyModifiers.push('stuck-right');
154 | }
155 |
156 | if (stuckTop) {
157 | stickyModifiers.push('stuck-top');
158 | }
159 |
160 | const childrenWithStuckProps = React.Children.map(children, (child) => {
161 | const childModifiers = (child.props && child.props.modifiers) || [];
162 | return React.cloneElement(child, { modifiers: [...childModifiers, ...stickyModifiers] });
163 | });
164 |
165 | return (
166 |
170 | {childrenWithStuckProps}
171 |
172 | );
173 | }
174 | }
175 |
176 | Sticky.propTypes = {
177 | /** Pass in a React component, and it will receive `stuckBottom`, `stuckLeft`, `stuckRight`, and/or `stuckTop` modifiers */
178 | children: PropTypes.node.isRequired,
179 | /** If you have an internally scrolling component, pass its ref callback to watch for scroll events */
180 | scrollTarget: PropTypes.object,
181 | /** These offsets determine how far from the edge of the page an element must be to count as 'stuck' */
182 | sides: PropTypes.shape({
183 | bottom: PropTypes.number,
184 | left: PropTypes.number,
185 | right: PropTypes.number,
186 | top: PropTypes.number,
187 | }),
188 | };
189 |
190 | Sticky.defaultProps = {
191 | scrollTarget: null,
192 | sides: {
193 | top: 0,
194 | },
195 | };
196 |
197 | export default Sticky;
198 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-sticky
2 |
3 | A Sticky header/footer component for React
4 |
5 | The main component's src file is in `src/Sticky.jsx`
6 |
7 | To use it, use a `` component and pass the sticky header/footer/sidebar's contents as children.
8 |
9 | [Live example](https://pixelbandito.github.io/react-sticky/build)
10 |
11 | ## Usage
12 |
13 | ### `{children}`
14 |
15 | ```jsx
16 | import React, {Component} from 'react';
17 | import Sticky from './Sticky.jsx';
18 | import classnames from 'classnames';
19 |
20 | const sides = {
21 | top: 0, // Sticks when it scrolls past the top edge
22 | bottom: 0, // Sticks when it scrolls past the bottom edge
23 | left: 10, // Sticks 10px from the left edge
24 | right: -20, // Sticks 20px past the right edge (useful for content that should stick only when it's fully out of the frame)
25 | };
26 |
27 | function MyComponent() {
28 | return (
29 |
30 |
Lorem ipsum...
31 | {/** Without a scrollTarget, Sticky will watch the window for scroll events. */}
32 |
33 | {/** Content will be called with an additional "modifiers" prop */}
34 |
35 |
36 |
Lorem ipsum...
37 |
38 | );
39 | };
40 |
41 | /**
42 | * This will generate following HTML:
43 | *
44 | */
45 |
46 | render(, document.getElementById('app'));
47 | ```
48 |
49 | #### Properties
50 |
51 | - `props.children`
52 |
53 | Must be one or more React node. Each child will get an extra prop called `modifiers` when the `` component is scrolled within a set distance from the edge of the scroll area.
54 |
55 | The `modifiers` prop is an array of one or more of these strings: `'stuck-top'`, `'stuck-bottom'`, `'stuck-left'`, `'stuck-right'`
56 |
57 | - `props.sides`
58 |
59 | An object in the form
60 |
61 | ```js
62 | sides = {
63 | top: 1,
64 | bottom: 2,
65 | left: 3,
66 | right: 4,
67 | };
68 | ```
69 |
70 | `sides` controls how far the `` component should be from each edge of the scroll area before it receives the corresponding modifier string.
71 |
72 | - `props.scrollTarget`
73 |
74 | By default, `` watches for scroll events on the window, and measures side offsets from the window's edge.
75 | If you want to stick something to the edge of an internally scrolling DOM element (a `` that uses `overflow: scroll` or `overflow: auto`, for instance), you can optionally pass a React ref to your scrolling area. Then `` will watch that element and measure side offsets from it.
76 |
77 | ## Disclaimer
78 |
79 | I'm providing this code free under an open source license. This is my personal repository, and the code is provided by me, not my employer.
80 |
81 | ## Developing and building locally
82 |
83 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
84 |
85 | Below you will find some information on how to perform common tasks.
86 | 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).
87 |
88 | ## Table of Contents
89 |
90 | - [Updating to New Releases](#updating-to-new-releases)
91 | - [Sending Feedback](#sending-feedback)
92 | - [Folder Structure](#folder-structure)
93 | - [Available Scripts](#available-scripts)
94 |
95 | - [npm start](#npm-start)
96 | - [npm test](#npm-test)
97 | - [npm run build](#npm-run-build)
98 | - [npm run eject](#npm-run-eject)
99 |
100 | - [Supported Browsers](#supported-browsers)
101 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills)
102 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor)
103 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor)
104 | - [Debugging in the Editor](#debugging-in-the-editor)
105 | - [Formatting Code Automatically](#formatting-code-automatically)
106 | - [Changing the Page ``](#changing-the-page-title)
107 | - [Installing a Dependency](#installing-a-dependency)
108 | - [Importing a Component](#importing-a-component)
109 | - [Code Splitting](#code-splitting)
110 | - [Adding a Stylesheet](#adding-a-stylesheet)
111 | - [Post-Processing CSS](#post-processing-css)
112 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc)
113 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files)
114 | - [Using the `public` Folder](#using-the-public-folder)
115 |
116 | - [Changing the HTML](#changing-the-html)
117 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system)
118 | - [When to Use the `public` Folder](#when-to-use-the-public-folder)
119 |
120 | - [Using Global Variables](#using-global-variables)
121 | - [Adding Bootstrap](#adding-bootstrap)
122 |
123 | - [Using a Custom Theme](#using-a-custom-theme)
124 |
125 | - [Adding Flow](#adding-flow)
126 | - [Adding a Router](#adding-a-router)
127 | - [Adding Custom Environment Variables](#adding-custom-environment-variables)
128 |
129 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html)
130 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell)
131 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env)
132 |
133 | - [Can I Use Decorators?](#can-i-use-decorators)
134 | - [Fetching Data with AJAX Requests](#fetching-data-with-ajax-requests)
135 | - [Integrating with an API Backend](#integrating-with-an-api-backend)
136 |
137 | - [Node](#node)
138 | - [Ruby on Rails](#ruby-on-rails)
139 |
140 | - [Proxying API Requests in Development](#proxying-api-requests-in-development)
141 |
142 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy)
143 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually)
144 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy)
145 |
146 | - [Using HTTPS in Development](#using-https-in-development)
147 | - [Generating Dynamic `` Tags on the Server](#generating-dynamic-meta-tags-on-the-server)
148 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files)
149 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page)
150 | - [Running Tests](#running-tests)
151 |
152 | - [Filename Conventions](#filename-conventions)
153 | - [Command Line Interface](#command-line-interface)
154 | - [Version Control Integration](#version-control-integration)
155 | - [Writing Tests](#writing-tests)
156 | - [Testing Components](#testing-components)
157 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries)
158 | - [Initializing Test Environment](#initializing-test-environment)
159 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests)
160 | - [Coverage Reporting](#coverage-reporting)
161 | - [Continuous Integration](#continuous-integration)
162 | - [Disabling jsdom](#disabling-jsdom)
163 | - [Snapshot Testing](#snapshot-testing)
164 | - [Editor Integration](#editor-integration)
165 |
166 | - [Debugging Tests](#debugging-tests)
167 |
168 | - [Debugging Tests in Chrome](#debugging-tests-in-chrome)
169 | - [Debugging Tests in Visual Studio Code](#debugging-tests-in-visual-studio-code)
170 |
171 | - [Developing Components in Isolation](#developing-components-in-isolation)
172 |
173 | - [Getting Started with Storybook](#getting-started-with-storybook)
174 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist)
175 |
176 | - [Publishing Components to npm](#publishing-components-to-npm)
177 | - [Making a Progressive Web App](#making-a-progressive-web-app)
178 |
179 | - [Opting Out of Caching](#opting-out-of-caching)
180 | - [Offline-First Considerations](#offline-first-considerations)
181 | - [Progressive Web App Metadata](#progressive-web-app-metadata)
182 |
183 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size)
184 | - [Deployment](#deployment)
185 |
186 | - [Static Server](#static-server)
187 | - [Other Solutions](#other-solutions)
188 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing)
189 | - [Building for Relative Paths](#building-for-relative-paths)
190 | - [Azure](#azure)
191 | - [Firebase](#firebase)
192 | - [GitHub Pages](#github-pages)
193 | - [Heroku](#heroku)
194 | - [Netlify](#netlify)
195 | - [Now](#now)
196 | - [S3 and CloudFront](#s3-and-cloudfront)
197 | - [Surge](#surge)
198 |
199 | - [Advanced Configuration](#advanced-configuration)
200 | - [Troubleshooting](#troubleshooting)
201 |
202 | - [`npm start` doesn't detect changes](#npm-start-doesnt-detect-changes)
203 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra)
204 | - [`npm run build` exits too early](#npm-run-build-exits-too-early)
205 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku)
206 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify)
207 | - [Moment.js locales are missing](#momentjs-locales-are-missing)
208 |
209 | - [Alternatives to Ejecting](#alternatives-to-ejecting)
210 | - [Something Missing?](#something-missing)
211 |
212 | ## Updating to New Releases
213 |
214 | Create React App is divided into two packages:
215 |
216 | - `create-react-app` is a global command-line utility that you use to create new projects.
217 | - `react-scripts` is a development dependency in the generated projects (including this one).
218 |
219 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`.
220 |
221 | 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.
222 |
223 | 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.
224 |
225 | 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.
226 |
227 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly.
228 |
229 | ## Sending Feedback
230 |
231 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues).
232 |
233 | ## Folder Structure
234 |
235 | After creation, your project should look like this:
236 |
237 | ```
238 | my-app/
239 | README.md
240 | node_modules/
241 | package.json
242 | public/
243 | index.html
244 | favicon.ico
245 | src/
246 | App.css
247 | App.js
248 | App.test.js
249 | index.css
250 | index.js
251 | logo.svg
252 | ```
253 |
254 | For the project to build, **these files must exist with exact filenames**:
255 |
256 | - `public/index.html` is the page template;
257 | - `src/index.js` is the JavaScript entry point.
258 |
259 | You can delete or rename the other files.
260 |
261 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.
262 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won't see them.
263 |
264 | Only files inside `public` can be used from `public/index.html`.
265 | Read instructions below for using assets from JavaScript and HTML.
266 |
267 | You can, however, create more top-level directories.
268 | They will not be included in the production build so you can use them for things like documentation.
269 |
270 | ## Available Scripts
271 |
272 | In the project directory, you can run:
273 |
274 | ### `npm start`
275 |
276 | Runs the app in the development mode.
277 | Open to view it in the browser.
278 |
279 | The page will reload if you make edits.
280 | You will also see any lint errors in the console.
281 |
282 | ### `npm test`
283 |
284 | Launches the test runner in the interactive watch mode.
285 | See the section about [running tests](#running-tests) for more information.
286 |
287 | ### `npm run build`
288 |
289 | Builds the app for production to the `build` folder.
290 | It correctly bundles React in production mode and optimizes the build for the best performance.
291 |
292 | The build is minified and the filenames include the hashes.
293 | Your app is ready to be deployed!
294 |
295 | See the section about [deployment](#deployment) for more information.
296 |
297 | ### `npm run eject`
298 |
299 | **Note: this is a one-way operation. Once you `eject`, you can't go back!**
300 |
301 | 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.
302 |
303 | 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.
304 |
305 | 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.
306 |
307 | ## Supported Browsers
308 |
309 | By default, the generated project uses the latest version of React.
310 |
311 | You can refer [to the React documentation](https://reactjs.org/docs/react-dom.html#browser-support) for more information about supported browsers.
312 |
313 | ## Supported Language Features and Polyfills
314 |
315 | This project supports a superset of the latest JavaScript standard.
316 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports:
317 |
318 | - [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016).
319 | - [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017).
320 | - [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal).
321 | - [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal)
322 | - [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (part of stage 3 proposal).
323 | - [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax.
324 |
325 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-).
326 |
327 | 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.
328 |
329 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**:
330 |
331 | - [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign).
332 | - [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise).
333 | - [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch).
334 |
335 | 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.
336 |
337 | Also note that using some newer syntax features like `for...of` or `[...nonArrayValue]` causes Babel to emit code that depends on ES6 runtime features and might not work without a polyfill. When in doubt, use [Babel REPL](https://babeljs.io/repl/) to see what any specific syntax compiles down to.
338 |
339 | ## Syntax Highlighting in the Editor
340 |
341 | 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.
342 |
343 | ## Displaying Lint Output in the Editor
344 |
345 | > Note: this feature is available with `react-scripts@0.2.0` and higher.
346 | > It also only works with npm 3 or higher.
347 |
348 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
349 |
350 | 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.
351 |
352 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root:
353 |
354 | ```javascript
355 | {
356 | "extends": "react-app"
357 | }
358 | ```
359 |
360 | Now your editor should report the linting warnings.
361 |
362 | 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.
363 |
364 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules.
365 |
366 | ## Debugging in the Editor
367 |
368 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).**
369 |
370 | 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.
371 |
372 | ### Visual Studio Code
373 |
374 | 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.
375 |
376 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app's root directory.
377 |
378 | ```json
379 | {
380 | "version": "0.2.0",
381 | "configurations": [{
382 | "name": "Chrome",
383 | "type": "chrome",
384 | "request": "launch",
385 | "url": "http://localhost:3000",
386 | "webRoot": "${workspaceRoot}/src",
387 | "sourceMapPathOverrides": {
388 | "webpack:///src/*": "${webRoot}/*"
389 | }
390 | }]
391 | }
392 | ```
393 |
394 | > Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
395 |
396 | 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.
397 |
398 | Having problems with VS Code Debugging? Please see their [troubleshooting guide](https://github.com/Microsoft/vscode-chrome-debug/blob/master/README.md#troubleshooting).
399 |
400 | ### WebStorm
401 |
402 | 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.
403 |
404 | 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.
405 |
406 | > Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration).
407 |
408 | 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.
409 |
410 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine.
411 |
412 | ## Formatting Code Automatically
413 |
414 | 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/).
415 |
416 | To format our code whenever we make a commit in git, we need to install the following dependencies:
417 |
418 | ```sh
419 | npm install --save husky lint-staged prettier
420 | ```
421 |
422 | Alternatively you may use `yarn`:
423 |
424 | ```sh
425 | yarn add husky lint-staged prettier
426 | ```
427 |
428 | - `husky` makes it easy to use githooks as if they are npm scripts.
429 | - `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).
430 | - `prettier` is the JavaScript formatter we will run before commits.
431 |
432 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root.
433 |
434 | Add the following line to `scripts` section:
435 |
436 | ```diff
437 | "scripts": {
438 | + "precommit": "lint-staged",
439 | "start": "react-scripts start",
440 | "build": "react-scripts build",
441 | ```
442 |
443 | Next we add a 'lint-staged' field to the `package.json`, for example:
444 |
445 | ```diff
446 | "dependencies": {
447 | // ...
448 | },
449 | + "lint-staged": {
450 | + "src/**/*.{js,jsx,json,css}": [
451 | + "prettier --single-quote --write",
452 | + "git add"
453 | + ]
454 | + },
455 | "scripts": {
456 | ```
457 |
458 | 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,json,css}"` to format your entire project for the first time.
459 |
460 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://prettier.io/docs/en/editors.html) on the Prettier GitHub page.
461 |
462 | ## Changing the Page ``
463 |
464 | 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.
465 |
466 | 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.
467 |
468 | 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.
469 |
470 | 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).
471 |
472 | ## Installing a Dependency
473 |
474 | 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`:
475 |
476 | ```sh
477 | npm install --save react-router
478 | ```
479 |
480 | Alternatively you may use `yarn`:
481 |
482 | ```sh
483 | yarn add react-router
484 | ```
485 |
486 | This works for any library, not just `react-router`.
487 |
488 | ## Importing a Component
489 |
490 | This project setup supports ES6 modules thanks to Babel.
491 | 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.
492 |
493 | For example:
494 |
495 | ### `Button.js`
496 |
497 | ```javascript
498 | import React, { Component } from 'react';
499 |
500 | class Button extends Component {
501 | render() {
502 | // ...
503 | }
504 | }
505 |
506 | export default Button; // Don’t forget to use export default!
507 | ```
508 |
509 | ### `DangerButton.js`
510 |
511 | ```javascript
512 | import React, { Component } from 'react';
513 | import Button from './Button'; // Import a component from another file
514 |
515 | class DangerButton extends Component {
516 | render() {
517 | return ;
518 | }
519 | }
520 |
521 | export default DangerButton;
522 | ```
523 |
524 | 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.
525 |
526 | 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'`.
527 |
528 | 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.
529 |
530 | Learn more about ES6 modules:
531 |
532 | - [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)
533 | - [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html)
534 | - [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules)
535 |
536 | ## Code Splitting
537 |
538 | 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.
539 |
540 | 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.
541 |
542 | Here is an example:
543 |
544 | ### `moduleA.js`
545 |
546 | ```javascript
547 | const moduleA = 'Hello';
548 |
549 | export { moduleA };
550 | ```
551 |
552 | ### `App.js`
553 |
554 | ```javascript
555 | import React, { Component } from 'react';
556 |
557 | class App extends Component {
558 | handleClick = () => {
559 | import('./moduleA')
560 | .then(({ moduleA }) => {
561 | // Use moduleA
562 | })
563 | .catch(err => {
564 | // Handle failure
565 | });
566 | };
567 |
568 | render() {
569 | return (
570 |
571 |
572 |
573 | );
574 | }
575 | }
576 |
577 | export default App;
578 | ```
579 |
580 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button.
581 |
582 | You can also use it with `async` / `await` syntax if you prefer it.
583 |
584 | ### With React Router
585 |
586 | 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).
587 |
588 | Also check out the [Code Splitting](https://reactjs.org/docs/code-splitting.html) section in React documentation.
589 |
590 | ## Adding a Stylesheet
591 |
592 | 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**:
593 |
594 | ### `Button.css`
595 |
596 | ```css
597 | .Button {
598 | padding: 20px;
599 | }
600 | ```
601 |
602 | ### `Button.js`
603 |
604 | ```javascript
605 | import React, { Component } from 'react';
606 | import './Button.css'; // Tell Webpack that Button.js uses these styles
607 |
608 | class Button extends Component {
609 | render() {
610 | // You can use them as regular CSS styles
611 | return ;
612 | }
613 | }
614 | ```
615 |
616 | **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.
617 |
618 | 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.
619 |
620 | 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.
621 |
622 | ## Post-Processing CSS
623 |
624 | 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.
625 |
626 | For example, this:
627 |
628 | ```css
629 | .App {
630 | display: flex;
631 | flex-direction: row;
632 | align-items: center;
633 | }
634 | ```
635 |
636 | becomes this:
637 |
638 | ```css
639 | .App {
640 | display: -webkit-box;
641 | display: -ms-flexbox;
642 | display: flex;
643 | -webkit-box-orient: horizontal;
644 | -webkit-box-direction: normal;
645 | -ms-flex-direction: row;
646 | flex-direction: row;
647 | -webkit-box-align: center;
648 | -ms-flex-align: center;
649 | align-items: center;
650 | }
651 | ```
652 |
653 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling).
654 |
655 | ## Adding a CSS Preprocessor (Sass, Less etc.)
656 |
657 | 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 `