Configure ReactJS with create-react-app
This is post about necessary configures for create-react-app with redux, react-redux, redux-thunk, react-router, react-router-dom, sass, code spliting, jQuery, bootstrap, react-loadable, react-scrollchor, react-intl, react-select, react-datepicker, react-table, moment, ... My GitHub Source Code ...
This is post about necessary configures for create-react-app with redux, react-redux, redux-thunk, react-router, react-router-dom, sass, code spliting, jQuery, bootstrap, react-loadable, react-scrollchor, react-intl, react-select, react-datepicker, react-table, moment, ...
My GitHub Source Code here: https://github.com/huynhsamha/create-react-app-config
My Demo here: https://huynhsamha.github.io/create-react-app-config/
Version Vietnamese here
In this step, you should have create-react-app is installed global.
- Create new app: create-react-app react-app
- use npm start or yarn start to start development
- use npm build or yarn build to build production
In this tutorial, I will use yarn, you can also use npm.
Create environment files, create-react-app will use them.
- In terminal at root: touch .env .env.development .env.production
- In .env.development: REACT_APP_ENV=development
- In .env.production : REACT_APP_ENV=production
You can also set new environment variable. Note: only variable with prefix REACT_APP_ can use in create-react-app
As create-react-app said:
This project setup minifies your CSS and adds vendor prefixes to it automatically through Autoprefixer so you don’t need to worry about it.
- In terminal: yarn add node-sass-chokidar npm-run-all
- In file package.json:
{ "scripts": { - "start": "react-scripts start", - "build": "react-scripts build", + "start": "npm-run-all -p watch-css start-js", + "build": "npm-run-all build-css build-js", + "start-js": "react-scripts start", + "build-js": "react-scripts build", + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", + "build-css": "node-sass-chokidar src/ -o src/", } }
- In file .gitignore:
# auto generated files (sass, less, ...) src/**/*.css
Use express to initialization
mkdir server cd server express
Configuration
- Rename app.js to server.js
- Join server.js and ./bin/www
- Move server.js to root app
- Insert dependencies in package.json (which is generated by express) to package.json in root (which is generated by create-react-app)
- Remove dependencies not use (serve-favicon, jade, ejs, etc.)
- Remove all file in server, execpt routes/index.js
- Correct and customize file server.js
Install dependencies package
yarn
Install package cors
For development, use package cors to cross localhost:3000 (client-side, is react app) to localhost:4200 (server-side, is node express)
yarn add cors
Start server-client
yarn start or npm start: start client side (react): localhost:3000
node server: start server-side (node express): localhost:4200
In development, because we use node server at port 4200, but client side is port 3000, so we should check out environment variable REACT_APP_ENV (which created in above steps) to fetch data from server.
- Create environment files: In your terminal:
mkdir src/environments cd src/environments touch env.development.js env.production.js index.js
- Edit the files as source code. baseUrl is url to server.
Styles
Create styles in src/ to contain variables, mixins, classes, common styles, or theme, etc. for your app: + _variables.scss: declare variables for style. + _mixins.scss: declare mixins for style + _classes.scss: declare some util classes for style + index.scss: import _ files to this file, you should move index.scss (in root) to this folder, and in index.js, you only import ./styles/index.css + You also override some theme (such as AdminLTE, Bootstrap, Material, Angular, Datatables, Charts, ...) with files _ and import to index.scss
Library and packages
Create lib in src to contain some library or package you use in this app, or config something with these packages (such as jQuery, Bootstrap, Font-Awesome, Ionicons, Material, ...): + You also create index.js in lib to import these files in folder. + In index.js in root, you only import by one line: import './lib';
Utility service
Create services to contain your services for app. Guides is below sections
Reducers - Actions
Create actions, reducers to do with redux. Guides is below sections
Components
Create components to contain components in app: Guides for these components is below sections
Layout Components
- Create layout in components to contain layout of app (flow).
- Your App.js, App.scss also in here, which import Header, Footer, Sidebar, Menu, Body,... for Navigations and Router
Common Components
Create common in components to contain some components which is used a lot of times. Such as Loading, Modal, Alert, Notification, Box, ...
Pages Components
Create pages in components to contain some pages in app, which is route in component Body, such as Home, Dashboard, Profile, Form, Terms of Service, Support, Page not found, Error page,...
Installation
- In terminal: yarn add jquery
- In terminal: touch src/lib/jquery.js
- Edit created file by following lines:
import $ from 'jquery'; // config jquery variables for other lib use jQuery (such as bootstrap) window.$ = $; window.jQuery = $;
How to use?
- In lib/index.js, import by: import './jquery';
- In index.js at root, import './lib'; (if you don't have).
- In the component, to use jQuery, you should import: import $ from 'jquery';
- To use jquery function, only use from componentDidMount() in Lifecycle React components:
- View Demo here
- View Implementation here
componentDidMount() { // jQuery should declare at here $(document).ready(() => { $('#alert').click(() => alert('This is alert be jQuery')); }); }
Recommend
Not use jQuery if it's not needed
Use along with jQuery
Installation
- In terminal: yarn add bootstrap (add @version you choose)
- In terminal: mkdir src/lib (if you have lib, skip this step)
- In terminal: touch src/lib/bootstrap.js
- Edit created file as lines (In this tutorial, I use bootstrap 4):
import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap/dist/js/bootstrap.bundle.min.js';
How to use?
- In lib/index.js, import by: import './bootstrap';
- In index.js at root, import './lib'; (if you don't have).
- In the component, you can use bootstrap 3, 4 as document available
- View demo with component DemoBootstrap.
- View Demo here
- View Implementation here
Use via React Component - reactstrap
Installation and Usage
- In terminal: yarn add reactstrap@next
- Only import Component to use as reactstrap document
- View demo with component DemoReactstrap.
- View Demo here
- View Implementation here
Recommend
- I think you should use reactstrap if you want use some component in react, with event handle.
- If you need some style in bootstrap, you can use directly, and don't need use jQuery
Add via index.html
You can include via file index.html in folder public via cdn or download and link stylesheet
Add via npm package
- In terminal: yarn add font-awesome
- Create file lib/font-awesome.js and add line import 'font-awesome/css/font-awesome.min.css';
- In lib/index.js, import by: import './font-awesome';
- In index.js at root, import './lib'; (if you don't have).
Install and configure
- yarn add animate.css
- In lib/ create file animate-css.js and add import 'animate.css';
- In index.js, also import by line import './animate-css';
Custom duration time
- Custom duration of animation by file scss config in style/:
- Create file _animate.scss as source code
- In index.scss: @import './animate.scss';
- This file will create classes style to custom time duration:
.animated.duration-100 .animated.duration-200 ... .animated.duration-1100 .animated.duration-1200 ... .animated.duration-3000
How to use
Example:
<div class="animated slideInUp">ABCDEFGHIJKLMNOP</div> <div class="animated slideOut" >ABCDEFGHIJKLMNOP</div> <div class="animated fadeInDown" >ABCDEFGHIJKLMNOP</div> <div class="animated fadeInUp duration-500" >ABCDEFGHIJKLMNOP</div> <div class="animated flipIn duration-1000" >ABCDEFGHIJKLMNOP</div> <div class="animated slideOutDown duration-700" >ABCDEFGHIJKLMNOP</div> <div class="animated flash infinite" >ABCDEFGHIJKLMNOP</div> <div class="animated flash infinite duration-1200" >ABCDEFGHIJKLMNOP</div>
Demo
- View demo at component DemoAnimateCss
- View Demo here
- View Implementation here
react-router-dom is used for route Single Page Application (SPA), not loading again page.
-
In terminal: yarn add react-router-dom
-
You can view implement in components/layout/body
-
You also view implement in components/pages/demo-react-router
-
Documents is available at React Router Dom
-
View Demo here
-
View Implementation here
Installation, Usage
react-loadable is useful for code-splitting:
- Lazy load components until it's called by user, it speed up your Single Page App (SPA).
- create-react-app will bundle new script file, when it's called, it will import this file to app.
- In terminal: yarn add react-loadable react-router-dom
- Create Loading component (view components/common/loading/)
- When use Loadable with loading component, it will add props to this component, such as: { isLoading: true, pastDelay: false, timedOut: false, error: null }
- View components/page/demo-loadable-component to sample implement.
- Component DemoLoadableComponent (is not loadable) and LoadableDemoComponent (is loadable)
Test Loadable Components - code-splitting
- Inspect element in browser
- Choose tab network
- Click filter JS
- Refresh page
- First only bundle.js and some js file
- Click component which loadable, you see *.chunk.js is loaded. That is lazy loading component
- View Demo here
- View Implementation here
Internationalize React apps. This library provides React components and an API to format dates, numbers, and strings, including pluralization and handling translations.
Features
- Display numbers with separators.
- Display dates and times correctly.
- Display dates relative to "now".
- Pluralize labels in strings.
- Support for 150+ languages.
- Runs in the browser and Node.js.
- Built on standards.
Document
You can view document at here: https://github.com/yahoo/react-intl
Usage in this tutorial
- In index.js, we import and use provider for App component:
import { IntlProvider } from 'react-intl'; ReactDOM.render( <Provider store={store}> <IntlProvider locale="en"> <App /> </IntlProvider> </Provider>, document.getElementById('root') );
- In specific component, you can import component of react-intl to use. You can view 1 demo about this in demo redux with format date.
Installation
yarn add redux react-redux redux-thunk
Usage
-
In src, create dir and files:
- actions/action-types.js: declare action name as const
- actions/index.js: declare actions for redux
- reducers/: declare reducers
- reducers/[name].js: declare action for a specific object.
- reducers/index.js: to combine reducer with redux, after that is to createStore.
-
In index.js:
- import { Provider } from 'react-redux';: use Provider to store redux
- import { createStore, applyMiddleware } from 'redux';: use createStore and middleware thunk with createStore
- import thunk from 'redux-thunk';: middleware for createStore, support async function
- import allReducers from './reducers';: reducers after combined
- const store = createStore(allReducers, applyMiddleware(thunk));: createStore with combined reducer, and apply middleware thunk
- You don't care about other reducers, such as Users
-
In reducers/index.js: combine reducers:
- In this tutorial, I demo with Items and Users (users is used for other section demo).
import { combineReducers } from 'redux'; import Items from './items'; import Users from './users'; const reducers = combineReducers({ Items, Users }); export default reducers;
- View Demo here
- View Implementation here
Create services to get API
- mkdir src/services (if you have not)
- touch db-service.js auth-service.js (db- to get database, auth- to authentication user)
- Example with db-service.js:
- import Env from './../environments';: to get baseUrl with environments
- export default class DbService as static class
- set baseUrl to get API:
static baseUrl() { return Env.baseUrl; } static parseUrl(url) { return DbService.baseUrl() + url; }
Example get API:
static getItems = () => { let url = DbService.parseUrl('/api/items'); console.log(url); return fetch(url).then(res => res.json()); }
Example Post API:
static addItem = (item) => { let url = DbService.parseUrl('/api/items'); return fetch(url, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(item) }).then(res => res.json()); }
Reveal Component on scroll: use react-reveal
Animation to show component when user scroll to view.
Installation
yarn add react-reveal
Support
Reveal with React
Fade Flip Rotate Zoom Bounce Slide Roll left/right/top/bottom fadeOut
Animated.css with React
Jump Flash HeadShake Jello Pulse RubberBand Shake Spin Swing Tada
How to use?
-
Use http://www.react-reveal.com/examples/.
-
View demo with component DemoReactReveal.
-
View Demo here
-
View Implementation here
Scroll animted to target - react-scrollchor
Animation to scoll to component when user click link to.
Installation
yarn add react-scrollchor
How to use?
-
Use https://github.com/bySabi/react-scrollchor
-
View demo with component DemoReactScrollchor.
-
View Demo here
-
View Implementation here
- View demo for this guide here: Demo
- View implementation in demo-react-table - Implementation
- In this guide, we use react-table with features:
- Lightweight at 11kb (and just 2kb more for styles)
- Fully customizable (JSX, templates, state, styles, callbacks)
- Client-side & Server-side pagination
- Multi-sort
- Filters
- Pivoting & Aggregation
- Minimal design & easily themeable
- Fully controllable via optional props and callbacks
- In this guide, we also use react-select and react-datepicker with moment. You can view docs for these package here:
- react-select - Demo
- react-select - Docs
- react-datepicker - Demo
- react-datepicker - Docs
I think following extensions is helpful for development:
Icons, Colors, View
- vscode-icons
- Bracket Pair Colorizer
Snippets
- ES7 React/Redux/GraphQL/React-Native snippets
- JavaScript (ES6) code snippets
- Bootstrap 3 Snippets
- Bootstrap 4 & Font awesome snippets
- Font-awesome codes for html
- Font-awesome codes for css
- HTML Snippets
- HTML CSS suppport
Intellisence
- npm
- npm Intellisence
- Path Intellisense
- SCSS IntelliSence
- Auto Close Tag
- Auto Rename Tag
- IntelliSense for CSS class names
Lint Code, Formater
- Prettier - Code formatter
- EditorConfig for VS Code
- ESLint
- TSLint
- Sass
- Sass Formatter
- Beautify css/sass/scss/less
Edit, Preview README - Markdown files
- Markdown All in One
- Markdown Preview Enhanced
- Markdown PDF
I think you also setting your VSCode by following steps:
- Enter Ctrl + Shift P
- Search user settings
- Choose Preferences: Open User Settings and enter.
- Edit your file User Settings by following lines: (you can search in Default Settings and customize your style)
{ "workbench.iconTheme": "vscode-icons", "workbench.startupEditor": "newUntitledFile", "window.zoomLevel": 0, "editor.fontSize": 13, "eslint.autoFixOnSave": true, "tslint.autoFixOnSave": true, "editor.formatOnSave": false, "editor.renderWhitespace": "boundary", "editor.quickSuggestions": { "other": true, "comments": true, "strings": true }, "terminal.integrated.cursorStyle": "line", "terminal.integrated.fontSize": 13, "terminal.integrated.fontFamily": "", "vsicons.projectDetection.autoReload": true, }