5119125, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
1B Akimatunar/ d3-and-react Pubic
Demo: B3js and React
2 dband-esctverelappy
Gr Tear YF fore BF Branches © Tags Ay Aetity
St se D. Wettetions
© Code © kssves M1 pulleaquests © Actions (B Projecs O Seurty Le Insights
FP maser - P 18nnch © 0 PO Q Goto fle ote fie
© Akimatunar vpdste READMEME aesatto-Syanago
pubic 10 Syearsage
me 10 S yearsag0
Be temptes 10 S yeas ago
D siigrore 10 s yeas age
Di pretiewe 10 S yeus ago
1 rexowema Update README md S yeas ago
D paceageson 10 s year age
D plopties 10 year age
1D README.
Using D3.js in React applications
{DEMO} [SLIDES]
Invroduction to integrating D3 data visualization in React apps using functional components and hooks
This project was bootstrapped with Create React Avo.
Below you will ind some information an how to perform common tasks
You can find the most recent version ofthis guide her,
Table of Contents
it
‘Send
0 New Releases
feedback
+ Folder Structure
+ Available Seripts
© opm start
© ppm test
pm run built
© pmun eject
sy
orted Language Features and Polyfils
+ Syntax Highlighting in the Eaitor
ntps:iigtnub.com/AkimaL unarid8-and-react
195119725, 5:34 PM.
ntps:ifgthub.comiAkimaL una
Displaying Lin
Debugging in the Eelitor
changing the Page,
Ruby on Ralls
Proxying API Requests in Developmer
Using HTTPS in Development
Generating Oynamic. enets> Tags onthe Server
Pre-Rendering into Static HTML Files
Injecting Data from the Server into the Page
Running Tests
® Filename Conventions
© Command Line Interface
© Version Control integration
© Writing Tests
© Testing Components
© Using Third Pary Assertion Linares
© Initializing Test Envizonment
© Focusing and Excluding Teste
© Coverage Reporting
© Continuous Integration,
© Disabling jam
Snapshot Testing
© Editor Integration
Developing Components in tolation
‘Making a Progressive Web App
Deployment
tie Server
© Other Solutions
© Serving A
© Building for Relative Paths
with Cnt-Side Routing
© Aue
GitHub AkimaLunare-ang-react: Demo: 03 and React5119725, 5:34 PM. GitHub AkimaLunare-anc-raact: Demo: 03 js
o irae
© GitHub Pages
© Heroky
© Modulus
Netty
© Now
© SBand CloudFront
o Suse
+ Advanced Configuration
+ Troubleshooting
© npn stars doesn’ detect changes
Updating to New Releases
‘create React App is vided into two packages:
+ create-resct-app isa global command-line utility that you use to create new projects
+ neact-serapts isa development dependency in the generated projects including this one)
You almost never need to update create-react-app ite it delegates all the setup to react-senspte
When you run create-react-app it always creates the project withthe latest version of react-seripts. so youll get al the new features and
Improvements in newly created apps automatically
To update an existing project to a new version of react-reripts, open the changelog, find the version you're curtenty on (check
package. son in this folder if youre not sure), and apply the migration instructions fo the newer versions.
Im most cases bumping the react-seripts version in
consult the changelog for potential breaking changes.
tage. json and running gn snstel1 inthis folder should be enough, but it's good to
We commit to keeping the breaking changes minimal so you can upgrade react-scripts nls
Sending Feedback
We ae abays open to your feedback
Folder Structure
Aer craton, your projec shoul look te his
sy-ap0/ e
Reabne na
rode_nodules/
package. json
puslser
‘ngex hem
favicon. seo
sel
ope
0p.
op. testis
Andon. ces
index is
For the project to build, these files must exist with exact filenames
ntps:iigtnub.com/AkimaLunarid8-and-react
31295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
‘+ puntic/tndex.heal isthe page template A
+ src/index.js isthe JavaScript entry point.
You can delete or rename the other fies.
You may create subdirectories inside sre. For faster rebuilds only fles inside sre are processed by Webpack.
‘You need to put any JS and CSS files inside src , oF Webpack won't see them,
(Only files inside pusise can be used from public/index. htm
Read instructions below for using assets from JavaScript and HTML.
Yu can, however, create more top-level directories.
‘They wil not be included inthe production build so you can use them for things ike documentation.
Available Scripts
Inthe project directory, you can ru:
pm start
Runs the app in the development mode
‘Open hi/localnos'3000 te view it in the browser,
‘The page will reload ifyou make edits
‘You will also see any lint erors in the console,
pm test
Launches the test runner in the interactive watch mode
See the section about running tests for more information,
‘apm run build
Builds the app for production tothe buiae folder
Ie correctly buneles React in production mode and optimizes the build forthe best performance.
‘The build is mined and the filenames include the hashes
Your app is ready 1 be deployed!
See the section about deployment for mare information,
‘apm run eject
"Note: this sa one-way operation. Once you eject , you can't go back!
IF you aren't satisfied withthe ould tool and configuration choices, you can eject at any time. This command will remove the single build
dependency from your projec.
Instead, twill copy all the configuration files andthe transitive dependencies Webpack, Babe, ESL, etc) ight into your project so you have
{ull control over them. All of the commands except eject will still work, but they will pint to the copied serpts so you can tweak them. At this
point you're on your own,
You don't have to ever use exect The curated feature sets suitable for small and middle deployments, and you shouldnt feel obligated to
se this feature, However we understand that ths tool wouldn't be usefulif you couldn't customize it when you ae ready fori
‘Supported Language Features and Polyfills
This project suppor a superset of the latest JavaScript standard
In ation to ESé syntax features, it also support:
+ Exponentistion Operator (€52016)
+ Asyne/awais€S2017),
+ Object Res/Spread Properties (stage 3 propos,
ntps:iigtnub.com/AkimaLunarid8-and-react 41295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
+ Class Felde and Static Propertiss (tage 2 proposal.
+ 13% and Flow syntax
Learn more about diferent proposal stages,
‘While we recommend to use experimental proposals with some caution, Facebook heavily uses these features inthe product code, so we
intend to provide coserodif any of these proposals change inthe future,
Note thatthe project only includes 2 few E56 po
# ject.2ssign() via object-assien
+ promise via grantee
+ fesent) via snag. faten
IF you use any ather ES6+ features that need runtime support (such as array.fron() oF Symbol), make sure you are including the appropriate
pall: manualy or thatthe browsers you are targeting already support them.
Syntax the Editor
ighlighting
To configure the syntax highlighting in you favorite text editor, head tothe relevant Babel documentation page and follow the instructions
Some of the most popula ecitors are covered,
playing Lint Output
Note: this feature is avalable with react-sriptto.2.0 and higher.
Some editors, incluting Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint.
‘They are not required for lntng. You should see te lnter eutput right in your terminal as walls the browser console, However, fyou prefer
the lint results to appear right in your editor, there are same extra steps you can do,
‘You would need to instal an ESLint plugin for your editor first.
Anote for Atom Linter-eslint users
Ifyou are using the Atom tinter-estint phigin, make sure that Use global ESLint installation option is checked!
ee ao
For Visual Studio Code users
VS Code ESLint plugin automaticaly detects Create React App's configuration file. So you do not need to create eslintre.json atthe
root directory, except when you want to add yo
‘own tues n that case, you should include CRA’s config by adding this Hine:
ws
S
‘Then ade this block to the “package. Json’ file of your projes
‘
“a
Final you will nee to install some packages global.
-ntps:ifgitb.com/Akima.unarid3-and-react
5295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
on instal =f eslint-config-rsact-apo80.2.0 es140083,8.4 babel-es1inte7.0.8 eslint-plugin-react@6.4.2 eslint-plugin-taporten.@ ©
\We recognize that ths is suboptimal, but itis currently required due tothe way we hide the ESLint dependency. The ESLint teams already
12 solution to thi go this may became unnecessary in a couple of months
Debugging in the Editor
This feature is currently only supported by Visual Studio Code editor
Visual Stuaio Code supports live-edting and debugging out af the box with Create React App This enables you asa developer to write and
debug your React code without leaving the editr, and most importantly it enables you to have 2 continuous development workflow, where
context switching is minimal as you dont have to switch between tools
You would need to have the latest version of VS Cade and VS Code Chvome Debugger Extension installed,
‘Then add the block below to your 1aunch.3s0n fle and put it inside the .vscode folder in your apps root dectory.
4 e
configurations’: ({
suet": "https //ecathost 3006",
ebRoot": “S{worsspaceRoot}/sre",
aseroatapir"s “s{aorsspaceRoot)/wscode/chrone",
'sourcemapPethoverrices": {
aebpack:///sre/*"2 “$(uebRoot}/
?
ay
>
Startyour app by running ron start, and start debugging in VS Code by pressing F5 orby clicking the green debug icon. You can now write
code, set breakpoints, make changes tothe code, and debug your newly modified code—al rom your editor
Changing the Page
You can find the source HTML fle in the public folder ofthe generated project You may edit the tag init to change the te from
“React App” to anything else.
"Note that normally you wouldn't edt files in the public folder vey often. For example, adding a stylesheet is done without touching the
HTML
IF you need to dynamically update the page tte based on the content, you can use the browser dounent.citie APL For more complex
scenarios when you want to change the title from React components, you can use React Helmet, a third party brary.
IF you use 2 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 Aleratively, you can pre-build each page as a static HTML fle which then loads the JavaScript bundle, which is covered here.
Installing a Dependency
‘The generated project includes React and ReactDOM as dependencies. I aso includes a set ofsrints used by Create React App as 2
development dependency. You may install ather dependencies (far example, React Route) with men
nom install save elsbrary-nanes e
Importing a Component
This project setup supports ESS modules thanks to Babel
While you can stil use equirec) and wosule.exports , We encourage you to USE nport and expert instead.
ntps:iigtnub.com/AkimaLunarid8-and-react 61295119725, 5:34 PM. GitHub AkimaLunare-anc-raact: Demo: 03 js
For example:
Button. js
Anport React, ( Conponent } fron ‘reacts e
lags button extends Component (
render) {
?
>
‘export default eutton; // Oon’t forget to use export defavit!
DangerButton. js
Inport React, { Conponent } fron ‘reacts e
Inport Button from /Button"; // deport » component from another Fie
lass Dangerautton extends Component {
render)
>
>
bs
‘vport ofsult Dangersuttons
Be aware ofthe diference between default and named exoorts It is @ common source of mistakes.
We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, 8 component) Tha’
what you get when you use export default gutvon and snpact Button from */Button
[Named exports are useful fr utility modules that expart several functions. A module may have at most ane default expart and as many named
exports a you like,
eam mote about £96 modules
+ Winen to use the curly braces?
* Exploring £56: Modules
+ Understanding £55: Modules
Adding a Stylesheet
This projec setup uses Webpack for handling all assets. Webpack offers a custom way of ‘extending’ the concept of inpors beyond
JvaScrat To express that a JavaScript file depends on a CSS fl, you need to import the CSS from the JavaScript file
Button.css
surton ( e
poddinas 205
>
Button. js
Inport React, { Conponent } fron ‘reacts e
Inport ".fautton.css'; // Tell Mebpack that Qutton.js uses these styles
lags buston extends Component (
render)
ntps:ifgthub.comiAkimaL una
7295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
> A
>
This isnot required for React but many peopl find this feature convenient You can read about the benefits of this approach here However
you should be aware that this makes your code less portable to other build tools and environments than Webpack
In development expressing dependences this way allows your styles to be reloaded on the fly as you edit ther. In production, al CSS files wil
bbe concatenated into a single minted css file inthe build output.
IF you are concerned about using Webpack-speciic semantics, you can put all your CSS right nto. sre/neex. ess. It would still be imported
fom sre/index.3s , but you could always remove that import ifyou later migrate t a eifferent build too
Post-Processing CSS
This project setup minifes your CSS and adds vendor prefies to it automaticaly through Autoprefixer so you don't need to worry about it
For example, this
00 e
display: flex:
flex-shraction: row
alignettens: centers
)
becomes thie
0p ( e
splay: ~ebidt-boxs
display: -as-Flexbox:
aispley: flex:
sbi -boxcortents horSzontali
sbit-box-align: centers
rsflex-align: centers
siian-svens: centers
IF you need to disable autoprefxing for some reason, follow this section
Adding a CSS Preprocessor (Sass, Less etc.)
Generally, we recommend that you don't reuse the same CSS classes across ifferent components. For example, instead of using a avtton
(CSSclass in components, we recommend creating 2 component withits own .sutton styles,
that both and
>
‘export efoutt Headers
This ensues that when the project is built, Webpack will correctly move the images into the build folder, and provide us with corect paths.
This works in C85 too:
ntps:ifgthub.comiAkimaL una
91295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
Loge « @
beckground-inoge: url. /ToRo-Pn@)s
)
\Webpack finds all relative module references in CSS (they start with.) and replaces them with the final paths from the compiled bundle.
you make a typo or accidentaly delete an important file, ou will see a compilation error, jus like when you import a non-enstent JavaScript
‘modtle. The final flenames in the compiled bundle are generated by Webpack from content hashes. Ifthe file content changes inthe future,
\Webpack wil give it a cifferent name in production so you don't need to warty bout long-term caching of assets
Please be advised that this i alk a custom feature of Webpack
Itis not required for React but many people enjoy it (and React Native uss a similar mechanism for images)
[An alternative way of haneling static assets is described inthe next section.
Using the public Folder
Note this feature i available wth react-scriptst9.5.0 and higher
Changing the HTML
‘The pubrse folder contains the HTML fle so you can tweak it for example, to set the page tite, The cseript> tag with the compiled code will
bbe added toit automatically during the buld process.
‘Adding Assets Outside of the Module System
You can also ad other assets to the pubise folder
[Note that we normaly encourage you to. taport_ assets in JavaScript files instead. For example, see the sections on adding a stylesheet and
adding images and fonts, Ths mechanism provides a number of benefits:
+ Seripts and stylesheets get miniied and bundled together to avoid extra network requests
+ Missing files cause compilation errors instead of 404 erors for your users
+ Result flenames include content hashes so you don't need to worry about browsers caching their old versions.
However there isan escape hatch that you can use to add an asst outside of the module system,
you puta fle into the pote folder, it will nt be processed by Webpack. Instead it wl be copied into the build folder untouched. To
reference assets inthe pubtie folder, you need to use a special variable called PusLsc URL
Inside incor. hemi, you can use it ike this
Link rele"shoteut con” hre®=MPUBLIC,URL/ favicon Leo"> e
(Only les inside the pubtie folder willbe accessible by soustic_utux prefix Ifyou need to useafle from are OF nose nodules, youll have
to.copy it there to explicitly specity your intention to make this fle apart ofthe build
When you run npn run build, Create React App will substitute xpvaLtc_uRLX with a correct absolute path so your project works even ifyou
se client-side routing or host tat a non-root URL.
In JavaScript code, you can use_process.env. PUBL for similar purposes
render() { e
11 Note: this ts an escape hatcn and shouté be used sparingly’
return cing srce(process.er¥.PUBLIC.URL + */ing/logp.pra’) />3
Keap in mind the downsides ofthis approach:
1 None ofthe files in pubic folder get post-processed or minfie
+ Missing files wil not be called at compilation time, and will cause 44 errors fr your users
ntps:iigtnub.com/AkimaLunarid8-and-react 101295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
+ Result filenames wonrt incase content hashes so you'll need to add query arguments or rename them every time they change. -
When to Use the public Folder
[Normally we recommend importing stylesheets images, and fonts from JavaScript The punice folderis useful as a workaround for a number
‘of less common cases
‘+ You need a file witha specifi name in the build output, such as
+ You have thousands of mages and need to dynamically reference ther paths
+ Youwant to include small script ike gace.s= outside ofthe bundled code
fect brant fest
+ Some brary may be incompatible with Webpack and you have no other option but to include tas tag
[Note that if you add a cseript> that declares global variables, you also need to read the next section on using them,
Using Global Variables
‘When you include a script in the HTML fle that defines global variables and ty to use one ofthese variables inthe code, the lintr will
complain because it cannot see the definition of the variable
You can avid hs by reading the global vaabe epic fom the snow objet for mame
const $ = window.$; e
‘This makes it obvious you are using a global variable intentionally rather than because ofa typo,
‘Alternatively, you can force the linter to ignore any line by adding // estint-aisable-tine after it
Adding Bootstrap
You don't have to use React Sootstrap together with React but itis populr oray for integrating Bootstrap with React apps. you need it
you can integrate it with Create React App by following these steps
Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as wel
on instalt react-bootsteap --save e
npn install boctstrapes ~-save
Inport Bootstaa CSS and optionally Bootstrap theme CSS in the beginning of your arc/tndex. Js ile
Inport ‘sooestrap/dtst/ces/boatstrap.css" e
Snport "soorstrap/dtee/cre/boatetrap-chene.c85°5
1) Pat any obher (C58 fram your
Import required React Bootstrap components within sre/pp.js fll or your custom component files:
Inport { navbar, 2unbotron, Button } fron ‘neact-bootstrap's e
[Now you are ready to use the imported React Bootstrap components within your component hierarchy define in the render method. Heres
anevample ssp.js redone using React Bootstrap.
Using a Custom Theme
‘Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package)
‘We sugges the following approach:
+ Create a new package that depends on the package you wish to customize, eg. Bootstrap
+ Add the necessary build steps to tweak the theme, and publish your package on npm.
+ Install your own theme npm package asa dependency of your app,
ntps:iigtnub.com/AkimaLunarid8-and-react s1n95119125, 5:34 PM GitHub - AkimaLunave-ane-react: Demo: 03s and React
Here isan example of adding a customized Bootstrap that fellows these steps.
Adding Flow
Flow is static type checker that helps you write code with fewer bugs. Check out this introduction to using static types in JavaScript ifyou are
‘new to this concept.
Recent versions of Flow work with Create Reset App projects out of the box.
To add Flow to a Create React App project, follow these steps:
1. Run npn iassalt -osavendey flowsbin (OF yarn ad =
fv flowbin
2.Add “foe: “flow to the scripts section of your package. Jeon
3.Run pm ran flow ~~ init (or yann flow -- dnit to create 2 .siowconig file inthe raat directory,
4.Add_// @f108 to any files you want to type check (or example, to. sre/npp. ts )
[Now you can run apn run flow (or yarn flow to check the les for ype errors, You can optionally use an IDE Tike Nuclde for a better
Integrated experience. Inthe future we plan to integrate it into Create React App even more closely.
To leam more about Flow, check out its documentation.
Adding Custom Environment Variables
Note: this feature is available wth react-scriptsge.2.3 and higher.
Your project can consume variables declare in your environment af they were declared locally in your J files. By default you will have
‘ovs_v defined for you, and any other environment variables stating with eacr_aP>_
‘The environment variables are embedded during the build time. Since Create React App produces a static KTML/CSS/JS bundle it cant
possibly read them at runtime. To read them at cuntme, you would need o load HTML into memory on the server and replace placeholders in
runtime, just like described here, Altematvely you can rebuild the app on the server anytime you change them,
Note: You must create custom environment variables beginning with ReAct_APP_. Any other variables except nooe_ew willbe ignored to
void accidentally exposing a private key on the machine that could have the same name, Changing any environment variables wll require
you to restart the development server if itis running
‘These environment variables will be defined for you on process.env For example, having an environment variable named
EACT_APp_SEcRtT_¢o0t willbe exposed in your JS 35. gracess.env, REACT_APP_SECRET_ CODE
‘Theres also 2 special bull-in environment variable called nooe_ew . You can read it from process.env.seoe_eav When youn npe start it
|salways equal lo “cevelopnert’ when you run apn test its always equal to “test”, and when you run gon rn busla to make a
production bundle, iis always equal to ‘prodiction’ . You cannot averride nooe_ew manually. Tis prevents developers from accidentally
deploying a slow development build to production
‘These environment variables can be useful fr displaying information condtionally based on where the project is deployed or consuming
sensitive data that lves outside of version conta
First, you need to have environment variables defined. For example, e's say you wanted to consume a secret defined inthe environment inside
rendert) < e
return (
case
“enallbYou ane cunning this application in cb (process.env.NOOE_PW} nage. c/snall>
“input types"hidcen” defoultValues{precess.env REACT APP_SECRET CODE) />
«ison
aw
>
During the bull, process env.REACT_APP_StCRET_coo® willbe replaced with the curent value ofthe AEACT_APP_SEERET_coDe environment
variable. Remember thatthe Noot_gW variable willbe set for you automatically.
ntps:iigtnub.com/AkimaLunarid8-and-react
12295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
\When you load the app inthe browser and inspect the , you wl see its value set to abedet , and the bald text will show the Bi
‘environment provided when using npn stare
cai @
“anallbYou are running this application in cesdevelopnenté/ node.=nal1>
input ty
Te above form is looking for 3 variable called ReAcT_Ap>_SECRET_cooe from the environment. In order to consume this value, we need to have
itdefined in the environment This ean be done using two ways: either in your shell orn a env fle. Both of these ways are described in the
et few sections
Having access to the noe_eny is also useful for performing actions conditionaly
Af (process.env.NODE_FNV =~ ‘production’) ( e
aniyties atsalets
>
When you compile the app with rea run but, the minifcation step wil trp out this condition an the resuking bundle wil be smaller.
Referencing Environment Variables in the HTML
Note: this feature is avaliable with react-scriptste.9.0 and higher
You can also access the environment variables starting with aeacr_aee_ in the publse/index. hem For example:
Tags on the Server
Since Create React App doesn't support server rendering, you might be wondering how to make creta> tags dynamic and reflect the current
URL To solve this, we recommend to add placeholders into the HTML, lke this
toctype him> e
ental 2angeren>
freta propertyavogstitle™ contents 06 TITLE_">
‘neta propersye"ogidescription™ convents_96]DESCRIPTION_">
‘Then, on the server, regardless ofthe backend you use, you can read ndex.heal into memory and replace _06_11TLE_,
06, eScRIPTION_, and any other placeholders with values depending on the current URL, Just make sure to sanitize and escape the
Interpolated values So that they are safe to embed into HTML!
IF you use 2 Node server, you can even share the route matching logic between the client and the server. However duplicating t also work fine
In simple cases.
Pre-Rendering into Static HTML Files
you're hosting your suttd with a static hosting provider you can use react-snapshot to generate HTML pages for each route, or relative link,
Jnyour application, These pages wil then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded,
‘There are ako opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes
‘The primary benefit of pre-rendering is that you get the core content ofeach page withthe HTML payload—regardles of whether or not your
JmsaScrit bundle successfully downloads. tals increases the likellhood that each route of your applieation willbe pike up by search
engines
You can read more about zer0-configuration pre-rendering (also called snapshottng} here
ntps:iigtnub.com/AkimaLunarid8-and-react
191295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
Injecting Data from the Server into the Page
Similarly tothe previous section, you can leave some placeholders in the HTML that inject global variables, for example:
(
const div = document.createtlenent (Av);
fReactoarrenser(eape 13, aiv)3,
D
This test mounts a component and makes sue that it didn't throw during rendering, Tests like ths provide alot value with very litle effort so
they are great 98 a starting point, and ths is the test you wil find in. src/Apo. test. Js
\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.
IF you'd like to test components inisclation from the child components they render, we recommend using shaliow() rendering API from
Enzyme, You can write a smoke test with it too:
‘npn install ~-save-dev enzyne react-addons-test-utils @
Anport React for ‘reacts @
Inport { shallow } fron ‘enzyme’;
Anport Sop from". /Rp5
se¢-renders without crashing’, () =>
stallentape >):
»
Unlike the previous smoke test using teact0o.rerder() ths test only renders and doesn't go deeper. For example, even if cApp>
Itself renders 9 that throws, this test will pass, Shallow tendering is great for isolated unit tests, but you may still want to create some
{ull enderng tests to ensure the components integrate correctly. Enzyme supports [ull rendering with mount) , and you can aso use i for
testing state changes and component lifecycle
You can read the Enzyme dacumentation for more testing techniques, Enzyme documentation uses Chai and Sinon for assertions but you don't
hhave to use them because Jest provides built-in expect() and dest.) for spies.
ntps:iigtnub.com/AkimaLunarid8-and-react ie5119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
Here isan example from Enzyme documentation that asserts specific output, rewritten to use Jest matchers:
Anport React (oor “reacts e
nport { shadow } from “enayme's
Snport Sop fom."
ieCrrenders welcone message's (> (
const wrapper = shaltow(espa />)3
Const weleore = chDsMeleone to Reacte/h2>;
11 expect( wrapper contains weleane))-to.equal(true)
fexpect(wrapper contains velcone)).coEqual(trve):
vs
All Jest matchers are extensively documented here
"Nevertheless you can use a this-paty assertion library Tke Cha if you want to as described below,
‘Additionally, you might find jest-enzyme helpfulto simplify your tests with readable matchers. The above contains code can be writen
simpler with jesteenzyme,
‘expect (wrapper) tocontaintesct(velcone) e
To setup jestenzyme with Create React App fellow the instructions for initializing your test environment to import est-enzyne
npn instalt ~-saventov jest-ensyne e
1) srefaatuptosts. js e
Anport “Jest-enayne"
Using Third Party Assertion Libraries
‘We recommend that you use expect() for assertions and jest.n() for spies. I you are having issues with them please file shose against Jest
‘and well fix them, We intend te keep making them better for React, supporting for example, prtty-prnting React elements as ISX,
However, ifyou are used to other libraries, such as Chal and Sinon, or ifyou have existing code using thom that you'd lke to port over, you can
Jmport them normaly like this
Inport sinon for “sinen"s e
nport (expect } feon "chads
‘an then use them in your tests ke you normally do,
Initializing Test Environment
Note: this feature is avallable with react-scripsee.4.0 and higher
IF your app uses a browser API that you need to mock in your tess or if you just need a glabal setup before running your tests, add »
src/setuptests. js to yOUr project. Iwill be automaticaly executed before running your tess.
For example:
sre/setuptests.Js
‘const Lecabstoragetooe = { e
getrten: Jest. 0),
setztan: Jest.nQ),
clears gest. fr)
F
Focusing and Excluding Tests
ntps:iigtnub.com/AkimaLunarid8-and-react
181295119725, 624 Pm
You can replace 12() with xit¢) to temporary exclude ates from being executed.
Similarly, 4420) lets you focus on a specific tes witho
Coverage Reporting
Jest hasan integrated coverage reporter that works well with ES6 and requires no configuration
Run npn teat -~ ~-coverage (note extra -- in the middle to include a coverage report like this
TT aed
Note that tests run much slower with covers
Continuous Integration
By default npn test. runs the watcher with interactive CLL However, you can force it to un tests once and finish the process by setting an
wher
bill to perform a inter warning check by setting the environment variable. cx. I any warnings are encountered then the build fas
Popular Cl servers already set the environment variable c1 by defaul but you can do this yourself to:
On Cl servers
Travis cl
1. Following the Trav’ Getting started guide for syncing your Gitlub repository with Tavs, You may need t
in your profile pa
2.Add a. travis.yni fle to your git repository.
Aanguage: node_4s
1
2, Customize your Tavis C1 Buld if needed.
er your fist build with agit push
‘On your own environment
Windows fem exe)
tps thu. convAKImaLnare-ane-react
GitHub AkimaLunare®-anc-react: Demo: 03 js and React
running any other tests
Pea emcee
0 it is recommended to run it separately from your normal worklow.
ating a build of your application with npn run bu ot checked by default. Like npn test , you can force the
inialize some settings manually
191295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
vet run butld @
{Note the lack of whitespace is intentional)
ix mac05 (Bath)
Cletrue apn test e
CTetrue npn run build e
‘The test command will force Jest to run tests once instead of lunching the watcher
Ifyou find yourself doing ths often in development, please file a
‘the best experience and ate open to changing how it works to accommodate mote workflows,
issue to tell us about your use case because we want to make watcher
‘The build command ill check for inter warnings and failf any ae found,
Disabling jsdom
‘By defauly, the packaze-tson of the generated projec looks Ike this:
an e
sseripese:
test's Tractosertpts test --envejscor™
3
IF you know that none of your tests depend on jsiom, you can safely remove. --enve}sdon and your tests will run faster.
To help you make up your mind, here sa list of APIs that need jsdom:
+ Ary browser globls ke window and docunens
+ seacto. render
Yestutts renderintovounert) (ashortut forthe above)
In contrast jsdom is not needed forthe following APIs
+ Tenueitscrestetendanart) (shallow rendering)
+ spaltont) in Enzyme
Finalyjadom i algo not needed for snapshot testing,
‘Snapshot Testing
‘Snapshot testing isa feature of Jost that automaticaly generates text snapshots of your components and saves thom on the disk so ifthe UL
‘output changes, you get notified without manually writing any assertions onthe component output, Read more about snapshot testing
Editor Integration
IF you use Visual Studio Cos, there sa Jest extension which works with Create React App out ofthe box. This provides alot of IDE-ke features
while using 2 text editor: showing the status ofa test run with potential fail messages inline, starting and stopping the watcher automaticaly,
and offering one-click snapshot updates,
ntps:ifgthub.comiAkimaL una 201295119725, 624 PM CGithub- AkimaL unav-ane-react: Demo: 03s and React
Bees
oF
Developing Components in Isolation
Usually, in an app, you have alot of Ul components, andl each of them has many diferent states. For an example, a simple button component
could have following states:
+ With a text abel
+ With an emoji
+ Inthe disabled mode,
Usually, i's hard to see these states without running a sample app or some examples,
Create React App dessn't include any tools for ths by defauk, but you can easily ade to your project tis a third-party tool
that lets you develop components and see all ther states in isolation from your app,
tps thu. convAKImaLnare-ane-react 211295119125, 5:34 PM
eee cole
GitHub AkimaLunare-ang-raact: Dem: 03 and React
ays
Wileome
to storybook
Welcome to STORYBOOK
This isa Ul component dev envionment for your app.
We've added some basic stories inside the axe/stories drectoy.
‘Astor i a single state of one of more Ul components, You can nave as many
stores a you want.
(Bosicallya story i ke a visual testcase)
‘See these sample stoves fora component called nutton
ust th that, you can ad your own components a stories.
You can also ect those components and see changes right aay.
(reciting the mutton componentiocated at sre/stores/auttor
You can also deplay your Stonibook asa static app. This way, everyone in your team can view and review cifferent states of Ul components
without starting a backend server or creating an account in your app.
Here's how to setup your app with Storybook:
First install te following npm package globally:
npn instal -g getstorybook
Then, run the following command inside your app's director
aststoryook
Alter that, ollw the instructions onthe screen.
Lear mare about React Storyoook
+ Screencast: Gatting Started with React Storybook
+ GitHub Repo.
* Documentation
+ Snapshot Testing with React Storybook
Making a Progressive Web App
You can turn your React ap into a Progressive Wels App by following the steps in ths repository,
Deployment
ron run butleé creates butte directory with a production build of your app. Setup your favourite HTTP server so that a visitor to your sit is
served index.ntol, and requests to static paths lke /static/}s/main.chasho.3s are served with the contents of the /static/}s/nain.
hasty. fle
Static Server
For enviranments using Node, the easiest way to handle this would be to install serve and let it handle the rest
ntps:ifgthub.comiAkimaL una
i-and-roact
221295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
npn install -g serve @
serve <= butld
‘The last command shown above will Serve your static site on the port $000, Like many of seve's internal settings the port can be adjusted
using the -p or --pore flags
Run this command to get full ist ofthe options available
serve oh e
Other Solutions
You don't necessarily need a static server in order to run a Create React App project in production. It work just as fine integrated into an
‘existing dynamic one
Here's a programmatic example using Node and Bxnress
const @ess = require express") e
forse path ~ reavie("path'}s
onst app = express();
spp.uselenpress. static" /bul'));
spp.a0t('/"s fonction (rea es)
Pesesendrile(path. jin alomane, */builé', “index. htal'Y);
ws
spp. 1ssten(s00);
The choice of your server software isn't important ether Since Create React App is completely platform-agnostc there's no need to explicily
se Node.
‘The butte folder with static assets isthe only output produced by Create React App,
‘However this isnot quite enough if you use client-side routing, Rea the next section if you want to support URLS lke. /todos/a2 in your
single-page app.
Serving Apps with Client-Side Routing
IF you use routers that use the HTMLS_pushstate history API under the hood {for example, React Router with browserHistory ), many static fle
serves wl fal For example, f you used React Router witha route for /t0%0s/42, the development server will respond to
oealtost:300@/tedos/42_ properly, but an Express serving a production build as above will not
This is because wnen there isa fresh page load for a /tados/e2, the server looks forthe file suile/todos/42 andl does not fin it.The server
needs tobe configured to respond to request to /odos/42 by serving index.html. For example, we can amend our Express example above
to-serve sndex.ntnt for any unknown paths
spp.useCanpress stat ie" /build")); e
app.gett'/', function (req, re8) (
sappiaet( 7", function (ree, P28) (
res.sendtile(path. oin(_sierane, *./bvile', “indox.html));
Ds
you're using Anache, you need to create a .ntaccess flim the pute folder that looks like this:
options -muresviens e
eweitetagine 06
ewritacond 3(REQUEST_FILENANE) If
Revrstetule * index.heel. (@5A,
Tewill get copied tothe usta folderwhen you run npn ran suid
ntps:iigtnub.com/AkimaLunarid8-and-react 231295119125, 5:34 PM GitHub AkimaLunare-anc-raact: Demo: 03 js
Now requests to /tesss/42 willbe handled correctly both in development and in production.
Building for Relative Paths
By default, Create React App produces a build assuming your app is hosted at the server root
To override this, specity the tonepage inyour package. json for example:
horepage' “hetps//nyaabsite.can/relativepath”, e
‘This wil let Create Reset App correctly infer the rot path to use inthe generated HIME ile
Serving the Same Build rom Different Paths
Note: this feature is avalable wth reset-scrips89.9.0 and higher.
Ifyou are not using the HTMLS.pusstate history APL or not using client-side outing at all tis unnecessary to speciy the URL fom which
your app willbe served. Instead, you can ut this in your package. 3son
stoepnes *, e
This will make sure that all the asset paths are relative to. sndex.ntat . You ill then be able to move your app from nttp://nywebsite.com tO
etp://mpcbsite,con/relativepath or even hetp://myaebsite.con/relative/eath without having to rebuild it
Azure
See ths blog post on how to deploy your React app to Microsoft Azure,
Firebase
Install the Firebase CL if you haver't already by running npe snstall -g #irease-tools. Sign up fora Flrebase account and create anew
project. Run iretase login and login wit your previous created Firebase account
Thon run the frebase init command from your project's root You need to choose the Hesting: Configure and deploy Frebase Hosting
sites and choose the Frebase project you created inthe previous step. You will need to agree with dacabase.rvles. json being created, choose
build asthe public directory, and alo agree ta Configure as a single-page app by replying with
Project Setup e
First, let's assoctate this project airectory with a Fleebase project.
You can create multiple project aliases by running flrebase use --246,
tot for now we'll Gust set up a cefault project.
2 hat Ficcbase project do you want to assactate as cofaule? fxanple app (oxanple-3
Firebase Realtine Database Rules allow you to define how your data should be
2 hat flue should be used for Database Rules? database.rules. json
Y_ batabase Rules for exarple-app-f4698 have been dovnloaced to database.rules. son.
Future modifications to datatase.rules. json will upéste Database fules when you ron
ireease deploy.
sting Setup
‘our public directory Ss the foler (relative to your profact directory) that
vill contatn Hosting assets to uploaéed with firetase deploy. 1f you
have a bute process “or your assets, use your builds ovtout directory.
2 what do you want to use as your public directory? buitd
> contigure 25 2 single-page app (rearite all urls to /index.htnl)? Yes
J Wrote bulla/index. heat
4 writing configuration info to ficebase. jn
4 uniting project information to -firebasere
ntps:iigtnub.com/AkimaLunarid8-and-react
2ai29ntps:ifgthub.comiAkimaL una
5119125, 5:34 PM GitHub - AkimaLunave-ane-react: Demo: 03s and React
Y. Firobaae Snitiaitzation complete!
Now, afteryou create a production build with pn run buttd, you can deploy it by running firebase depioy
Deploying to “exenple-spp= "090
A. ceploying datanase, hosting
“J sacabarer rules ready %0 deploy
1 testing: preparing BuLlé civeccory “or yploae
Uplossine’
hosting: @ Files uploaded successfully
J starcing release process (nay take several minutes)
17S posting: butld foleer uploaded successfully
Deploy compete!
Project Console: nttps://eansole.Fireease, google. con/project/exanple-spp-(a6s@/overvicn
Hosting URL? nttps://exanole-spp-f4680.firebaseapp.cor
For more information see Add Fitebase to your JavaScrint Project,
GitHub Pages
Note this featur i available wth resct-seriptsge.2.0 and higher
‘Step 1: Add homes
10 package. json
‘The step below is important!
Ityou skip it, your app will not deploy correctly.
‘Open your package. json and add 2 hanepage ele
rorepage' “hetps://nyasernane.github.10/ay-oF9",
‘create React App uses the honepage field to determine the root URLin the built HTML fle
‘Step 2: Install gh-pages and add deploy to scripts in package.json
‘Now, whenever you run apr run build, you wil se a cheat sheet with instructions on how to deploy to GitHub Pages,
To publish tat htips:/myusername github io/my-app, rum
|Add the following sriots in your package. 3500
“a
sseriptses
”
“predeploy": "apm run butle",
deploy": “eh-papes 4 butle™
>
‘The predeploy script ll un automatically before deploy is run
Step 3: Deploy the site by running pm run deploy
Then run
om run deploy
Step 4: Ensure your projects settings use gh-pages
i-and-roact5119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
Finally, make sure GitHub Pages option in your GitHub projct settings is set to use the gh-pages branch
Source
Your GiHub Pages ste curently being bul from the pares branch
gh-pages branch» | Save
Select source
Y gh-pages branch
lomain other than 4
Use the eh-pages branch fr Gitub Pages.
‘Step 5: Optional
Configure the domain
You can configure a custom domain with GitHub Pages by adding a CMMME file to the public/ folder.
"Notes on client-side routing
GitHub Pages doesn't support routers that use the HTMLS.pushstate history AP under the hood (fer example, React Router using
brouserittary ), This is because when thee is afresh page load fora ul like http://user.gfthab.to/todanve/todos/42 , Where /2odoe/82 is 3
frontend route the Gitub Pages server retums 404 because it knows nothing of /tedos/4z. I you want to add a router toa project hosted on
GitHub Pages, here are 9 couple of solutions:
+ You could switch from using HTMLS history API to routing witn hashes. you use React Router, you can switch to Rashidstory for this
effect, but the URL wil be longer and more verbose (or example, nttp:/Juser.github. 1/tedonve/#/t0¢0s/422_keykna} ). Read more about
Afferent history implementations in React Router
+ Akeratively,you can use a tick to teach Gitub Pages to handle 404 by redirecting to your sndex.ntal_ page with a special redirect
parameter. You would need to add » a4.ntnl fle wih the redirection code tothe builé folder before deploying your project, and you'll
need ta add code handling the esirect parameter to sndex. tl . You can find a detsiled explanation of this technique in this ould,
Heroku
Use the Heroku Bulldpack for Create React App,
You can find instructions in Deploying React with Zero Configuration
Resolving Heroku Deployment Errors
Sometimes npn run nutld works locally bu fails during deploy via Heroku. Following are the mast common cases
“Module not found: ror: Cannot rele fi or‘drectory™
HF you get something lice this:
renote: Failed to create a production build. Reason e
remote: Modula not found: Error: Cannot resolve "file" oF “ébrectory
ypirectony in /emp/buthd_1238/sre
Ik means you need to ensure thatthe lettercase of the file or directory you. Inport. matches the ene you see on your filesystem or on Github.
This is important because Linux the operating system used by Heroku} i case sensitive, So. myoirectory andl ayatrectory are two distin
dlirecories and thus, even though the project bulds locally, te difference in case breaks the ingort statements on Heroku remotes
cou not Find 3 raquo fle”
Ifyou exclude or ignore necessary files from the package you will see a error similar ths one:
renote: Could not find = requires fle e
Fenote: Searched in: /emp/buite a747Sfe163}20022512246H516Fidée/poblic
remote: npn ERR! Linx 3.13.6-105-gereric
enote: apm E8RI ang */enp/busle 37875fe16902092951224685160dke/ heroku/nose/bte/node™
"Pemp/buha3287541590209225122059916¢/ sneroku/nade/Din/npA” “ren” "bul
ntps:iigtnub.com/AkimaLunarid8-and-react
261295119725, 5:34 PM. GitHub - AkimaLunave-ane-react: Demo: 03s and React
Inthis case, ensure thatthe file is there withthe proper letercase and that’s not ignored en your local .gitignore or ~/.gitignore globaa
Modulus
‘See the Modulus blog post on how to deploy your reset app to Modulus
Netlify
‘To do.» manual deploy to Netty CDR
om instal netaisy-cls e
nethity deploy
Choose bustd asthe path to deploy.
To setup continuous delivery:
[With this setup Netty will bul and deploy when you push to git or open a pul request:
1. Start anew netfy project
2. Pick your Gi hosting service and select your repository
3-Click outie your site
‘Support for client-side routing:
To support pushstate , make sure to create a public/_redsrects file withthe following rewrite rules:
7+ Fandex.need 298 e
\Whon you bulld the project, Create React App will place the pubtie folder contents into the build output
Now
naw offers a 2er0-configuration single-command deployment.
‘install the now commandline tool either via the recommended desktop too! er via nade with pm instat3
2 Install serve by running pn Snstala ~-save serve
3.Add this line to scripts Jn package. json
row-start: “serve bullé/*, @
4, Run ow from your project directory. You will see now.sh URL in your output like this
> henty! hep //yoursroset-sirane-tospymeet.ronsh (copies clipboard) @
Paste that URL into your browser then the build is complete, and you wil see your deployed app
Details are avaiable inthis arte
$3 and CloudFront
See this blog poston how ta deploy your React app to Amazon Web SenicesS3 and Clousront
surge
Install the Surge CLifyou havent alesdy by cunning npe snstall -z singe Run the sunge command and og in you or create anew
account, You just need 'o speci te build older and your custom domain and you are done.
cmos enatteeoain.con i @
!ntps:ub convakimaL unaids-ane-rct 2195119125, 5:34 PM GitHub - AkimaLunav-ane-reac: Demo: 03 and React
project path: /oatn/to/preject/outld 5 5
Hae: 7 files, 2.8 Me
domain: eveate-resce-app.surge.sh
plod: [seeseceescesssssssss] 180%, eta: 0.65
propagate on COM: [ 00x
plan: Free
Users! anal onain.con
1 Adorose: XXX
Success! Project 1s published and running at ereste-resct-app.surg.s|
[Note that n order to support routers that use HTMLS pusnstate APL you may want to rename the index. heel in your bulé folder to
200.nem1_ before deploying to Surge Ths ensures that every URL falls back ta that fe
Advanced Configuration
You can adjust various development and production settings by setting environment variables in your shell or with nv,
Variable Development Production Usage
8y default, Create React App will open the default system browser, favoring Chrome on
BROWSER a % ——_-mac05. Specify a browse to overide this behavior, orsetitto rene to dsableit
complete,
85y defo the development web server binds to ocsthost- You may use this variable to
Host a % speci a citerent host,
'8y default the development webserver wil attempt to Fsten on port 3000 or prompt you
port a % | to-attempt the nest avallable port. You may use hs variable ospedyaiferent por.
artes g X% ——_ When setto true Create React App will un the development server in tates mode
Create React App assumes your application is hosted at the serving web server's root ora
subpath as specified in package. eon { nonegage |. Normally, Create React App ignores the
PUBLIC_URL x EZ hostname. You may use this variable to force asses to be referenced verbatim to the rl
You provide (hostname included). This may be particularly useful when using 2 CDN to
hhost your application.
When set to trve Create React App treats warnings as failures nthe build It also makes
the test runner non-watching. Most cls set this flag by default
a ° a
Troubleshooting
npm start doesn’t detect changes
‘When you save a file while npn start is running, the browser should refresh with the updated code,
IF this doesnt happen, try one of the following workarounds:
* your project isin a Dropbox folder, ty moving it out.
+ Ifthe watcher doesnt see a fle called indox.3s_ and you'te referencing it by te folder name, you need to restart the watcher due toa
\webpack bug
+ Some editors lke Vim and Intell) havea “safe write” feature that currently breaks the watcher. You will need to disable it Follow the
instructions in “Working with editors supporting safe wie”
‘+ Ifyour project path contains parentheses, ry moving the project to apath without them. This is caused by a Weloack watcher bus
+ On Linux and macOS, you might need to tweak system settings to allow more watchers
+ tf the project runs inside a virtual machine such a (a Vagrant provisioned! VirtualBox create an env fle in your project crectory fit
doesnt exist, and add cocrons_usePoLLiNostre toi This ensures tha the next time you tun npr start, the watcher uses the polling
mod, as necessary inside a VM
28129
ntps:igtnub. comiAkimaL una5119125, 5:34 PM GitHub ~ AkimaLunav-ane-reac: Dem: 03 and React
Releases
Packages
Languages
-ntps:ifgitb.com/Akima.unarid3-and-react 29129