├── .gitignore ├── examples └── counterTypeScript │ ├── tsconfig.test.json │ ├── public │ ├── favicon.ico │ ├── manifest.json │ └── index.html │ ├── src │ ├── index.css │ ├── index.tsx │ ├── reducers │ │ └── index.ts │ ├── uiState.ts │ ├── components │ │ ├── Counters.container.tsx │ │ ├── Counters.tsx │ │ └── App.tsx │ └── registerServiceWorker.ts │ ├── .gitignore │ ├── tsconfig.json │ ├── package.json │ ├── tslint.json │ └── README.md ├── .travis.yml ├── .npmignore ├── jest.json ├── src ├── actions.ts ├── reducer.ts ├── index.ts ├── __tests__ │ ├── componentTestUtils.ts │ ├── createUIState.test.tsx │ ├── reducer.test.ts │ ├── connectUIState.test.tsx │ └── utils.test.ts ├── createUIState.ts ├── connectUIState.ts └── utils.ts ├── tsconfig.json ├── rollup.config.js ├── LICENCE.md ├── package.json ├── tslint.json └── readme.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | /yarn-error.log 3 | /npm-debug.log 4 | /lib 5 | /dist 6 | /.rpt2_cache 7 | -------------------------------------------------------------------------------- /examples/counterTypeScript/tsconfig.test.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "module": "commonjs" 5 | } 6 | } -------------------------------------------------------------------------------- /examples/counterTypeScript/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jamiecopeland/redux-ui-state/HEAD/examples/counterTypeScript/public/favicon.ico -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | 3 | node_js: 4 | - '8' 5 | 6 | install: 7 | - npm install 8 | 9 | script: 10 | - npm run test 11 | - npm run build -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | /.rpt2_cache 2 | /examples 3 | /jest 4 | /node_modules 5 | 6 | /npm-debug.log 7 | /yarn-error.log 8 | /.travs.yml 9 | /jest.json 10 | /npm-debug.log 11 | /rollup.config.js 12 | /tslint.json 13 | /tsconfig.json 14 | -------------------------------------------------------------------------------- /jest.json: -------------------------------------------------------------------------------- 1 | { 2 | "transform": { 3 | ".(ts|tsx)": "ts-jest/preprocessor.js" 4 | }, 5 | "moduleFileExtensions": [ 6 | "ts", 7 | "tsx", 8 | "js" 9 | ], 10 | "testRegex": "./src/.*\\.test\\.(ts|tsx|js)$" 11 | } -------------------------------------------------------------------------------- /examples/counterTypeScript/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 20; 3 | padding: 20; 4 | font-family: sans-serif; 5 | } 6 | 7 | hr { 8 | height: 1px; 9 | background-color: #CCC; 10 | border: none; 11 | margin-top: 1rem; 12 | } 13 | -------------------------------------------------------------------------------- /examples/counterTypeScript/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | 6 | # testing 7 | /coverage 8 | 9 | # production 10 | /build 11 | 12 | # misc 13 | .DS_Store 14 | .env.local 15 | .env.development.local 16 | .env.test.local 17 | .env.production.local 18 | 19 | npm-debug.log* 20 | yarn-debug.log* 21 | yarn-error.log* 22 | -------------------------------------------------------------------------------- /examples/counterTypeScript/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": "./index.html", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/actions.ts: -------------------------------------------------------------------------------- 1 | export const SET_UI_STATE = '@@redux-ui-state/SET_UI_STATE'; 2 | 3 | export interface ModifyUIStateActionPayload { 4 | id: string; 5 | state: TUIState; 6 | } 7 | 8 | export interface ModifyUIStateAction { 9 | type: string; 10 | payload: ModifyUIStateActionPayload; 11 | } 12 | 13 | export const setUIState = ({ id, state }: ModifyUIStateActionPayload>) => ({ 14 | type: SET_UI_STATE, 15 | payload: { id, state }, 16 | }); 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "declaration": true, 4 | "jsx": "react", 5 | "lib": ["es6", "dom"], 6 | "forceConsistentCasingInFileNames": true, 7 | "module": "commonjs", 8 | "moduleResolution": "node", 9 | "noImplicitReturns": true, 10 | "noUnusedLocals": true, 11 | "outDir": "lib", 12 | "rootDir": "src", 13 | "sourceMap": true, 14 | "strict": true, 15 | "target": "es5", 16 | "types": ["jest"] 17 | }, 18 | "exclude": [ 19 | "src/__tests__", 20 | "examples", 21 | "node_modules", 22 | "lib" 23 | ] 24 | } -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | 2 | import typescript from 'rollup-plugin-typescript2'; 3 | import uglify from 'rollup-plugin-uglify'; 4 | 5 | export default { 6 | input: './src/index.ts', 7 | output: { 8 | name: 'redux-ui-state', 9 | file: 'dist/redux-ui-state.min.js', 10 | format: 'umd', 11 | exports: 'named', 12 | globals: { 13 | react: 'React', 14 | 'react-dom': 'ReactDOM', 15 | 'redux': 'Redux', 16 | 'react-redux': 'ReactRedux', 17 | 'reselect': 'Reselect' 18 | }, 19 | }, 20 | external: ['react', 'react-dom', 'redux', 'react-redux', 'reselect'], 21 | plugins: [ 22 | typescript(), 23 | uglify() 24 | ], 25 | }; 26 | -------------------------------------------------------------------------------- /examples/counterTypeScript/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "build/dist", 4 | "module": "esnext", 5 | "target": "es5", 6 | "lib": ["es6", "dom"], 7 | "sourceMap": true, 8 | "allowJs": true, 9 | "jsx": "react", 10 | "moduleResolution": "node", 11 | "rootDir": "src", 12 | "forceConsistentCasingInFileNames": true, 13 | "noImplicitReturns": true, 14 | "noImplicitThis": true, 15 | "noImplicitAny": true, 16 | "strictNullChecks": true, 17 | "suppressImplicitAnyIndexErrors": true, 18 | "noUnusedLocals": true 19 | }, 20 | "exclude": [ 21 | "node_modules", 22 | "build", 23 | "scripts", 24 | "acceptance-tests", 25 | "webpack", 26 | "jest", 27 | "src/setupTests.ts" 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /src/reducer.ts: -------------------------------------------------------------------------------- 1 | import { SET_UI_STATE, ModifyUIStateAction } from './actions'; 2 | import { UIStateBranch } from './utils'; 3 | 4 | /** 5 | * Makes all your dreams (or at least your actions) come true. 6 | */ 7 | export const createReducer = ( // tslint:disable-line:no-any 8 | initialState: UIStateBranch 9 | ) => ( 10 | state: UIStateBranch = initialState, 11 | action: ModifyUIStateAction 12 | ) => { 13 | switch (action.type) { 14 | case SET_UI_STATE: { 15 | return ({ 16 | ...state, 17 | [action.payload.id]: { 18 | ...state[action.payload.id], 19 | ...(action as ModifyUIStateAction).payload.state 20 | }, 21 | }); 22 | } 23 | 24 | default: { 25 | return state; 26 | } 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /examples/counterTypeScript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "my-app", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "react": "^16.3.1", 7 | "react-dom": "^16.3.1", 8 | "react-redux": "^5.0.7", 9 | "react-scripts-ts": "2.14.0", 10 | "redux": "^3.7.2", 11 | "redux-logger": "^3.0.6", 12 | "redux-ui-state": "^2.0.1", 13 | "reselect": "^3.0.1" 14 | }, 15 | "scripts": { 16 | "start": "react-scripts-ts start", 17 | "build": "react-scripts-ts build", 18 | "test": "react-scripts-ts test --env=jsdom", 19 | "eject": "react-scripts-ts eject" 20 | }, 21 | "devDependencies": { 22 | "@types/jest": "^22.2.3", 23 | "@types/node": "^9.6.4", 24 | "@types/react": "^16.3.9", 25 | "@types/react-dom": "^16.0.5", 26 | "@types/react-redux": "^6.0.2", 27 | "@types/redux": "^3.6.0", 28 | "@types/redux-logger": "^3.0.5", 29 | "typescript": "^2.8.1" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /LICENCE.md: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016-present, Jamie Copeland 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { 2 | IdFunction, 3 | Id, 4 | idIsString, 5 | idIsFunction, 6 | getStringFromId, 7 | DefaultStoreState, 8 | UIStateBranch, 9 | StateProps, 10 | DispatchProps, 11 | Props, 12 | AbstractWrappedComponent, 13 | WrappedComponentWithDefaultProps, 14 | WrappedComponentWithMappedProps, 15 | UIStateBranchSelector, 16 | UIStateIdProps, 17 | SetUIState, 18 | DEFAULT_BRANCH_NAME, 19 | stateSelector, 20 | propsSelector, 21 | defaultUIStateBranchSelector, 22 | UIStateBranchSelectorSelectorProps, 23 | uiStateBranchSelectorSelector, 24 | uiStateBranchSelector, 25 | idSelector, 26 | uiStateSelector, 27 | setUIStateSelector 28 | } from './utils'; 29 | 30 | export { 31 | ModifyUIStateActionPayload, 32 | ModifyUIStateAction, 33 | SET_UI_STATE, 34 | setUIState, 35 | } from './actions'; 36 | 37 | export { createReducer } from './reducer'; 38 | export { setupConnectUIState, defaultConnectUIState, MapConnectUIStateProps } from './connectUIState'; 39 | export { setupCreateUIState, MapCreateUIStateProps } from './createUIState'; 40 | -------------------------------------------------------------------------------- /examples/counterTypeScript/src/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import * as ReactDOM from 'react-dom'; 3 | import { createStore, applyMiddleware, compose } from 'redux'; 4 | import { Provider } from 'react-redux'; 5 | import { createLogger } from 'redux-logger'; 6 | 7 | import rootReducer from './reducers/index'; 8 | import App from './components/App'; 9 | import registerServiceWorker from './registerServiceWorker'; 10 | 11 | import './index.css'; 12 | 13 | // interface WindowWithDevTools { 14 | // __REDUX_DEVTOOLS_EXTENSION_COMPOSE__: string 15 | // } 16 | 17 | // tslint:disable-next-line:no-any 18 | const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ 19 | // tslint:disable-next-line:no-any 20 | ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ 21 | // options like actionSanitizer, stateSanitizer 22 | }) 23 | : compose; 24 | 25 | const enhancer = composeEnhancers( 26 | applyMiddleware(createLogger({ collapsed: true })), 27 | ); 28 | 29 | const store = createStore(rootReducer, {}, enhancer); 30 | 31 | ReactDOM.render( 32 | 33 | 34 | , 35 | document.getElementById('root') as HTMLElement 36 | ); 37 | 38 | registerServiceWorker(); 39 | -------------------------------------------------------------------------------- /examples/counterTypeScript/src/reducers/index.ts: -------------------------------------------------------------------------------- 1 | import { combineReducers } from 'redux'; 2 | import { DEFAULT_BRANCH_NAME, createReducer } from 'redux-ui-state'; 3 | import { 4 | renderPropUnmapped, 5 | renderPropMapped, 6 | utilTransformedStatic, 7 | utilTransformedDynamic1, 8 | utilTransformedDynamic2, 9 | utilRawStatic, 10 | utilRawDynamic1, 11 | utilRawDynamic2, 12 | manualTransformedStatic, 13 | manualTransformedDynamic1, 14 | manualTransformedDynamic2, 15 | manualRawStatic, 16 | manualRawDynamic1, 17 | manualRawDynamic2, 18 | } from '../uiState'; 19 | 20 | export default combineReducers({ 21 | [DEFAULT_BRANCH_NAME]: createReducer({ 22 | [renderPropUnmapped.key]: renderPropUnmapped.value, 23 | [renderPropMapped.key]: renderPropMapped.value, 24 | [utilTransformedStatic.key]: utilTransformedStatic.value, 25 | [utilTransformedDynamic1.key]: utilTransformedDynamic1.value, 26 | [utilTransformedDynamic2.key]: utilTransformedDynamic2.value, 27 | [utilRawStatic.key]: utilRawStatic.value, 28 | [utilRawDynamic1.key]: utilRawDynamic1.value, 29 | [utilRawDynamic2.key]: utilRawDynamic2.value, 30 | [manualTransformedStatic.key]: manualTransformedStatic.value, 31 | [manualTransformedDynamic1.key]: manualTransformedDynamic1.value, 32 | [manualTransformedDynamic2.key]: manualTransformedDynamic2.value, 33 | [manualRawStatic.key]: manualRawStatic.value, 34 | [manualRawDynamic1.key]: manualRawDynamic1.value, 35 | [manualRawDynamic2.key]: manualRawDynamic2.value, 36 | }), 37 | }); 38 | -------------------------------------------------------------------------------- /examples/counterTypeScript/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | 13 | 22 | React App 23 | 24 | 25 | 28 |
29 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /examples/counterTypeScript/src/uiState.ts: -------------------------------------------------------------------------------- 1 | // Standard initial value 2 | 3 | const initialValue = { 4 | index: 0, 5 | }; 6 | 7 | // Key value pairs 8 | 9 | export const renderPropUnmapped = { 10 | key: 'renderPropUnmapped', 11 | value: initialValue, 12 | }; 13 | 14 | export const renderPropMapped = { 15 | key: 'renderPropMapped', 16 | value: initialValue, 17 | }; 18 | 19 | export const utilTransformedStatic = { 20 | key: 'utilTransformedStatic', 21 | value: initialValue, 22 | }; 23 | 24 | export const utilTransformedDynamic1 = { 25 | key: 'utilTransformedDynamic1', 26 | value: initialValue, 27 | }; 28 | 29 | export const utilTransformedDynamic2 = { 30 | key: 'utilTransformedDynamic2', 31 | value: initialValue, 32 | }; 33 | 34 | export const utilRawStatic = { 35 | key: 'utilRawStatic', 36 | value: initialValue, 37 | }; 38 | 39 | export const utilRawDynamic1 = { 40 | key: 'utilRawDynamic1', 41 | value: initialValue, 42 | }; 43 | 44 | export const utilRawDynamic2 = { 45 | key: 'utilRawDynamic2', 46 | value: initialValue, 47 | }; 48 | 49 | export const manualTransformedStatic = { 50 | key: 'manualTransformedStatic', 51 | value: initialValue, 52 | }; 53 | 54 | export const manualTransformedDynamic1 = { 55 | key: 'manualTransformedDynamic1', 56 | value: initialValue, 57 | }; 58 | 59 | export const manualTransformedDynamic2 = { 60 | key: 'manualTransformedDynamic2', 61 | value: initialValue, 62 | }; 63 | 64 | export const manualRawStatic = { 65 | key: 'manualRawStatic', 66 | value: initialValue, 67 | }; 68 | 69 | export const manualRawDynamic1 = { 70 | key: 'manualRawDynamic1', 71 | value: initialValue, 72 | }; 73 | 74 | export const manualRawDynamic2 = { 75 | key: 'manualRawDynamic2', 76 | value: initialValue, 77 | }; 78 | -------------------------------------------------------------------------------- /src/__tests__/componentTestUtils.ts: -------------------------------------------------------------------------------- 1 | import * as reactRedux from 'react-redux'; 2 | 3 | import * as utils from '../utils'; 4 | import { defaultUIStateBranchSelector } from '../utils'; 5 | 6 | export interface UIState { 7 | index: number; 8 | } 9 | 10 | export interface MappedProps { 11 | message: string; 12 | increment: () => void; 13 | decrement: () => void; 14 | } 15 | 16 | export const uiStateId = 'counter'; 17 | export const initialState = { [uiStateId]: 0 }; 18 | 19 | export interface UniversalAssertionMocks { 20 | connect: jest.SpyInstance; 21 | uiStateSelector: jest.Mock; 22 | setUIStateSelector: jest.Mock; 23 | } 24 | 25 | const uiStateSelectorMockOutput = { index: 0 }; 26 | const setUIStateSelectorMockOutput = () => undefined; 27 | 28 | export const runUniversalAssertions = (mocks: UniversalAssertionMocks) => { 29 | const [mapStateToProps, mapDispatchToProps] = jest.spyOn(reactRedux, 'connect').mock.calls[0]; 30 | 31 | expect(mocks.connect).toHaveBeenCalledTimes(1); 32 | 33 | expect(mapStateToProps()) 34 | .toEqual({ uiState: uiStateSelectorMockOutput }); 35 | 36 | expect(mocks.uiStateSelector) 37 | .toBeCalledWith( 38 | undefined, 39 | { 40 | uiStateBranchSelector: defaultUIStateBranchSelector, 41 | uiStateId 42 | } 43 | ); 44 | 45 | expect(mapDispatchToProps()) 46 | .toEqual({ 47 | setUIState: setUIStateSelectorMockOutput 48 | }); 49 | expect(mocks.setUIStateSelector) 50 | .toBeCalledWith(undefined, { uiStateId }); 51 | }; 52 | 53 | export const createMocks = () => ({ 54 | connect: jest.spyOn(reactRedux, 'connect'), 55 | uiStateSelector: jest.spyOn(utils, 'uiStateSelector').mockReturnValue(uiStateSelectorMockOutput), 56 | setUIStateSelector: jest.spyOn(utils, 'setUIStateSelector').mockReturnValue(setUIStateSelectorMockOutput), 57 | }); -------------------------------------------------------------------------------- /src/__tests__/createUIState.test.tsx: -------------------------------------------------------------------------------- 1 | import * as reactRedux from 'react-redux'; 2 | import * as utils from '../utils'; 3 | import * as React from 'react'; 4 | // import { uiStateId, UIState } from './components'; 5 | import { setupCreateUIState } from '../createUIState'; 6 | 7 | import { 8 | Props as ReduxUIStateProps, 9 | defaultUIStateBranchSelector, 10 | } from '../utils'; 11 | import { createMocks, runUniversalAssertions, UIState, uiStateId } from './componentTestUtils'; 12 | 13 | const restoreMocks = (mocks: { [key: string]: jest.Mock | jest.SpyInstance }) => // tslint:disable-line:no-any 14 | Object.keys(mocks).forEach(key => (mocks[key] as any).mockRestore()); // tslint:disable-line:no-any 15 | 16 | const unmappedRenderProp = (props: utils.Props) => null; 17 | const mappedRenderProp = (props: utils.Props) => null; 18 | 19 | describe('setupConnectUIState', () => { 20 | 21 | it('should pass correct mapping functions to connect for raw props', () => { 22 | const mocks = createMocks(); 23 | 24 | setupCreateUIState(defaultUIStateBranchSelector)(uiStateId); 25 | 26 | runUniversalAssertions(mocks); 27 | 28 | restoreMocks(mocks); 29 | 30 | }); 31 | 32 | it('should pass the correct mapping functions to connect for mapped props', () => { 33 | const mocks = createMocks(); 34 | 35 | const mapPropsOutput = { message: 'I have been mapped' }; 36 | const mapProps = jest.fn().mockReturnValue(mapPropsOutput); 37 | setupCreateUIState(defaultUIStateBranchSelector)(uiStateId, mapProps); 38 | 39 | runUniversalAssertions(mocks); 40 | const [mapStateToProps, mapDispatchToProps, mergeProps] = jest.spyOn(reactRedux, 'connect').mock.calls[0]; 41 | 42 | const mergedProps = mergeProps(mapStateToProps(), mapDispatchToProps()); 43 | 44 | expect(mergedProps).toEqual(mapPropsOutput); 45 | 46 | restoreMocks(mocks); 47 | }); 48 | }); 49 | -------------------------------------------------------------------------------- /examples/counterTypeScript/src/components/Counters.container.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | defaultConnectUIState as connectUIState, 3 | MapConnectUIStateProps, 4 | } from 'redux-ui-state'; 5 | 6 | import { 7 | UIState, 8 | CounterProps, 9 | CounterDynamicIdProps, 10 | MappedProps, 11 | CounterTransformedProps, 12 | CounterRawProps, 13 | } from './Counters'; 14 | 15 | /** 16 | * Maps the raw Redux UI State API into a nicer, more contextually relevant shape 17 | * @param uiState 18 | * @param setUIState 19 | * @param props 20 | */ 21 | const mappedProps: MapConnectUIStateProps< 22 | UIState, 23 | MappedProps, 24 | CounterProps 25 | > = (uiProps, ownProps) => ({ 26 | message: `${ownProps.prefix}${uiProps.uiState.index}`, 27 | increment: () => uiProps.setUIState({ index: uiProps.uiState.index + 1 }), 28 | decrement: () => uiProps.setUIState({ index: uiProps.uiState.index - 1 }), 29 | }); 30 | 31 | // Using connectUIState with mapped props (recommended) and a static id 32 | export const CounterUtilTransformedPropsStaticId = connectUIState< 33 | UIState, 34 | CounterProps, 35 | MappedProps 36 | >('utilTransformedStatic', mappedProps)(CounterTransformedProps); 37 | 38 | // Using connectUIState with mapped props (recommended) and a dynamic id 39 | export const CounterUtilTranformedPropsDynamicId = connectUIState< 40 | UIState, 41 | CounterDynamicIdProps, 42 | MappedProps 43 | >(({ uiStateId }) => uiStateId, mappedProps)(CounterTransformedProps); // tslint:disable-line:max-line-length 44 | 45 | // Using connectUIState with raw props and a static id 46 | export const CounterUtilRawPropsStaticId = connectUIState< 47 | UIState, 48 | CounterProps 49 | >('utilRawStatic')(CounterRawProps); 50 | 51 | // Using connectUIState with raw props and a dynamic id 52 | export const CounterUtilsRawPropsDynamicId = connectUIState< 53 | UIState, 54 | CounterDynamicIdProps 55 | >(({ uiStateId }) => uiStateId)(CounterRawProps); 56 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "redux-ui-state", 3 | "version": "3.0.0", 4 | "description": "UI state management for Redux applications", 5 | "main": "lib/index.js", 6 | "directories": { 7 | "test": "test" 8 | }, 9 | "typings": "lib/index.d.ts", 10 | "scripts": { 11 | "clean": "rm -rf ./lib && rm -rf ./dist", 12 | "build:lib": "tsc", 13 | "build:lib:watch": "tsc -w", 14 | "build:dist": "rollup -c", 15 | "build": "npm run build:lib && npm run build:dist", 16 | "prepublish": "npm run clean && npm run build", 17 | "lint": "tslint 'src/**/*.{ts,tsx}'", 18 | "test": "jest --config jest.json", 19 | "test:watch": "npm run test -- --watch" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "git+https://github.com/jamiecopeland/redux-ui-state.git" 24 | }, 25 | "keywords": [ 26 | "react", 27 | "redux", 28 | "ui", 29 | "state", 30 | "ui state", 31 | "state management", 32 | "higher order component", 33 | "higher order function", 34 | "render props" 35 | ], 36 | "author": "Jamie Copeland", 37 | "license": "MIT", 38 | "bugs": { 39 | "url": "https://github.com/jamiecopeland/redux-ui-state/issues" 40 | }, 41 | "homepage": "https://github.com/jamiecopeland/redux-ui-state#readme", 42 | "peerDependencies": { 43 | "react": "^15.6.2 || ^16.0.0", 44 | "react-redux": "^5.0.7", 45 | "reselect": "^3.0.1" 46 | }, 47 | "devDependencies": { 48 | "@types/jest": "^22.2.3", 49 | "@types/react": "^16.3.9", 50 | "@types/react-redux": "^6.0.2", 51 | "jest": "^22.4.3", 52 | "react": "^15.6.2 || ^16.0.0", 53 | "react-redux": "^5.0.7", 54 | "reselect": "^3.0.1", 55 | "rollup": "^0.57.1", 56 | "rollup-plugin-typescript2": "^0.5.0", 57 | "rollup-plugin-uglify": "^3.0.0", 58 | "ts-jest": "^22.4.2", 59 | "tslint": "^4.5.1", 60 | "tslint-eslint-rules": "^2.2.1", 61 | "tslint-microsoft-contrib": "^2.0.14", 62 | "tslint-react": "^2.2.0" 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /examples/counterTypeScript/src/components/Counters.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | 3 | import { Props as ReduxUIStateProps, } from 'redux-ui-state'; 4 | 5 | export interface UIState { 6 | index: number; 7 | } 8 | 9 | export interface CounterProps { 10 | prefix: string; 11 | } 12 | 13 | export interface CounterDynamicIdProps extends CounterProps { 14 | uiStateId: string; 15 | } 16 | 17 | // ------------------------------------------------------------------------------------------------- 18 | // Component accepting mapped props 19 | // This implementation is clearly the better of the two, since it has a cleaner, more contextually relevant API. 20 | // See Counters.containers.tsx for several example implentations of how to transform props 21 | 22 | export interface MappedProps { 23 | message: string; 24 | increment: () => void; 25 | decrement: () => void; 26 | } 27 | 28 | export const CounterTransformedProps: React.StatelessComponent = ( 29 | { message, increment, decrement } 30 | ) => ( 31 |
32 |
33 | {message} 34 |
35 |
36 | 37 | 38 |
39 |
40 | ); 41 | 42 | // ------------------------------------------------------------------------------------------------- 43 | // Component acccepting raw props 44 | // This style of component still works, but the use of raw props necessitates extra, contextually irrelevant knowledge 45 | // of the inner workings of Redux UI State's API. 46 | // See Counters.containers.tsx for several example implentations of how to transform props 47 | 48 | export const CounterRawProps: React.StatelessComponent> = ({ 49 | prefix, uiState, setUIState 50 | }) => ( 51 |
52 |
53 | {prefix}{uiState.index} 54 |
55 |
56 | 57 | 58 |
59 |
60 | ); 61 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/tslint-microsoft-contrib", 4 | "node_modules/tslint-eslint-rules/dist/rules" 5 | ], 6 | "extends": ["tslint-react"], 7 | "rules": { 8 | "align": [ 9 | true, 10 | "parameters", 11 | "statements" 12 | ], 13 | "ban": false, 14 | "class-name": true, 15 | "comment-format": [ 16 | true, 17 | "check-space" 18 | ], 19 | "curly": true, 20 | "eofline": false, 21 | "forin": true, 22 | "indent": [ true, "spaces" ], 23 | "interface-name": [true, "never-prefix"], 24 | "jsdoc-format": true, 25 | "jsx-no-lambda": false, 26 | "jsx-no-multiline-js": false, 27 | "jsx-wrap-multiline": false, 28 | "label-position": true, 29 | "max-line-length": [ true, 120 ], 30 | "member-ordering": [ 31 | true, 32 | "public-before-private", 33 | "static-before-instance", 34 | "variables-before-functions" 35 | ], 36 | "no-any": true, 37 | "no-arg": true, 38 | "no-bitwise": true, 39 | "no-console": [ 40 | true, 41 | "log", 42 | "error", 43 | "debug", 44 | "info", 45 | "time", 46 | "timeEnd", 47 | "trace" 48 | ], 49 | "no-consecutive-blank-lines": [true, 1], 50 | "no-construct": true, 51 | "no-debugger": true, 52 | "no-duplicate-variable": true, 53 | "no-empty": true, 54 | "no-eval": true, 55 | "no-shadowed-variable": true, 56 | "no-string-literal": true, 57 | "no-switch-case-fall-through": false, 58 | "no-trailing-whitespace": false, 59 | "no-unused-expression": true, 60 | 61 | "no-use-before-declare": true, 62 | "one-line": [ 63 | true, 64 | "check-catch", 65 | "check-else", 66 | "check-open-brace", 67 | "check-whitespace" 68 | ], 69 | "quotemark": [true, "single", "jsx-double"], 70 | "radix": true, 71 | "semicolon": [true, "always"], 72 | "switch-default": true, 73 | 74 | "triple-equals": [ true, "allow-null-check" ], 75 | "typedef": [ 76 | true, 77 | "parameter", 78 | "property-declaration" 79 | ], 80 | "typedef-whitespace": [ 81 | true, 82 | { 83 | "call-signature": "nospace", 84 | "index-signature": "nospace", 85 | "parameter": "nospace", 86 | "property-declaration": "nospace", 87 | "variable-declaration": "nospace" 88 | } 89 | ], 90 | "variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore", "allow-pascal-case"], 91 | "whitespace": [ 92 | true, 93 | "check-branch", 94 | "check-decl", 95 | "check-module", 96 | "check-operator", 97 | "check-separator", 98 | "check-type", 99 | "check-typecast" 100 | ] 101 | } 102 | } -------------------------------------------------------------------------------- /src/__tests__/reducer.test.ts: -------------------------------------------------------------------------------- 1 | import { createReducer } from '../reducer'; 2 | import { setUIState, SET_UI_STATE } from '../actions'; 3 | import { UIStateBranch } from '../utils'; 4 | 5 | const COMPONENT_ID = 'thing'; 6 | 7 | interface ComponentUIStateOptional { 8 | readonly isOpen?: boolean; 9 | readonly selectedIndex?: number; 10 | } 11 | 12 | interface ComponentUIStateMandatory extends ComponentUIStateOptional { 13 | readonly isOpen: boolean; 14 | readonly selectedIndex: number; 15 | } 16 | 17 | const getItem1State = (): ComponentUIStateOptional => ({ 18 | isOpen: true, 19 | selectedIndex: 0, 20 | }); 21 | 22 | const getItem2State = (): ComponentUIStateOptional => ({ 23 | isOpen: false, 24 | selectedIndex: 666, 25 | }); 26 | 27 | const ITEM_1_ID = 'item1'; 28 | const ITEM_2_ID = 'item2'; 29 | 30 | const getInitialState = () => ({ 31 | [ITEM_1_ID]: getItem1State(), 32 | [ITEM_2_ID]: getItem2State(), 33 | }); 34 | 35 | describe('reducer', () => { 36 | 37 | describe('initial state', () => { 38 | 39 | it('contain the correct populated initial state', () => { 40 | const reducer = createReducer(getInitialState()); 41 | const actual = reducer(undefined as any, { type: 'NOT_AN_ACTION' } as any); // tslint:disable-line:no-any 42 | const expected = getInitialState(); 43 | 44 | expect(actual).toEqual(expected); 45 | }); 46 | 47 | it('contain the correct undefined initial state', () => { 48 | const reducer = createReducer(undefined as any); // tslint:disable-line:no-any 49 | const actual = reducer(undefined as any, { type: 'NOT_AN_ACTION' } as any); // tslint:disable-line:no-any 50 | const expected = undefined; 51 | 52 | expect(actual).toEqual(expected); 53 | }); 54 | }); 55 | 56 | describe('SET_UI_STATE', () => { 57 | it('set a new primitive value in empty initial state', () => { 58 | const action = setUIState({ 59 | state: { 60 | isOpen: false, 61 | }, 62 | id: ITEM_1_ID, 63 | }); 64 | const initialState = {}; 65 | const actual = createReducer(initialState)(initialState, action); 66 | const expected = { 67 | [ITEM_1_ID]: { 68 | isOpen: action.payload.state.isOpen 69 | } 70 | }; 71 | expect(actual).toEqual(expected); 72 | }); 73 | 74 | it('set a new primitive value in populated initial state', () => { 75 | const action = setUIState({ 76 | state: { 77 | isOpen: false, 78 | }, 79 | id: ITEM_1_ID, 80 | }); 81 | const actual = createReducer(getInitialState())(getInitialState(), action); 82 | const expected = { 83 | ...getInitialState(), 84 | [ITEM_1_ID]: { 85 | ...getInitialState()[ITEM_1_ID], 86 | isOpen: false 87 | } 88 | }; 89 | expect(actual).toEqual(expected); 90 | }); 91 | 92 | }); 93 | 94 | }); 95 | -------------------------------------------------------------------------------- /src/createUIState.ts: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { connect } from 'react-redux'; 3 | 4 | import { 5 | DefaultStoreState, 6 | uiStateSelector, 7 | setUIStateSelector, 8 | defaultUIStateBranchSelector, 9 | Props, 10 | StateProps, 11 | DispatchProps, 12 | UIStateBranchSelector, 13 | UIStateIdProps, 14 | } from './utils'; 15 | 16 | // Added temporary fix for issue related to https://github.com/Microsoft/TypeScript/issues/9944 17 | // error TS4076: Parameter 'uiStateBranchSelector' of exported function has or is using name 18 | // 'UIStateBranchSelector' from external module "[...]/redux-ui-state/src/utils" but cannot be named 19 | // tslint:disable-next-line:class-name 20 | export interface __IMPORT_FIX { 21 | UIStateBranchSelector: UIStateBranchSelector<{}>; 22 | StateProps: StateProps<{}>; 23 | DispatchProps: DispatchProps<{}>; 24 | } 25 | 26 | /** 27 | * The props for UIState component with a generic for the values accepted by the render prop 28 | */ 29 | export interface UIStateComponentProps { 30 | // tslint:disable-next-line:no-any 31 | children: (props: TProps) => React.ReactElement | null; 32 | } 33 | 34 | /** 35 | * A function that maps StateProps & DispatchProps into the shape required by the render 36 | * prop function 37 | */ 38 | export type MapCreateUIStateProps = ( 39 | props: Props 40 | ) => TMappedProps; 41 | 42 | /** 43 | * A render prop component factory responsible for injecting Redux UI State props into a render prop 44 | * component 45 | * @param uiStateBranchSelector A selector that selects the top level ui state branch from the 46 | * redux store with default if no argument is passed. 47 | */ 48 | export const setupCreateUIState = ( 49 | uiStateBranchSelector = defaultUIStateBranchSelector 50 | ) => >( 51 | id: string, 52 | mapProps?: MapCreateUIStateProps, 53 | ) => connect( 54 | (state: TAppState, props: UIStateComponentProps) => ({ 55 | uiState: uiStateSelector( 56 | state, Object.assign({ uiStateId: id, uiStateBranchSelector }, props) 57 | ) as TUIState, 58 | }), 59 | (dispatch) => ({ 60 | setUIState: setUIStateSelector>(dispatch, { uiStateId: id }), 61 | }), 62 | // Using Object.assign here to avoid "Spread types may only be created from object types" 63 | // https://github.com/Microsoft/TypeScript/issues/10727 64 | (stateProps, dispatchProps, ownProps) => Object.assign( 65 | {}, 66 | ownProps, 67 | mapProps 68 | ? mapProps({...stateProps, ...dispatchProps}) 69 | : {...stateProps, ...dispatchProps} 70 | ) 71 | )((props) => { 72 | // Until TypeScript allows spread on interfaces, force props to any to allow ES7 rest syntax 73 | // https://github.com/Microsoft/TypeScript/issues/16780 74 | // tslint:disable-next-line:no-any 75 | const { children, ...rest } = props as any; 76 | return children(rest); 77 | }); 78 | -------------------------------------------------------------------------------- /examples/counterTypeScript/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["tslint-react"], 3 | "rules": { 4 | "align": [ 5 | true, 6 | "parameters", 7 | "arguments", 8 | "statements" 9 | ], 10 | "ban": false, 11 | "class-name": true, 12 | "comment-format": [ 13 | true, 14 | "check-space" 15 | ], 16 | "curly": true, 17 | "eofline": false, 18 | "forin": true, 19 | "indent": [ true, "spaces" ], 20 | "interface-name": [true, "never-prefix"], 21 | "jsdoc-format": true, 22 | "jsx-no-lambda": false, 23 | "jsx-no-multiline-js": false, 24 | "label-position": true, 25 | "max-line-length": [ true, 120 ], 26 | "member-ordering": [ 27 | true, 28 | "public-before-private", 29 | "static-before-instance", 30 | "variables-before-functions" 31 | ], 32 | "no-any": true, 33 | "no-arg": true, 34 | "no-bitwise": true, 35 | "no-console": [ 36 | false, 37 | "log", 38 | "error", 39 | "debug", 40 | "info", 41 | "time", 42 | "timeEnd", 43 | "trace" 44 | ], 45 | "no-consecutive-blank-lines": true, 46 | "no-construct": true, 47 | "no-debugger": true, 48 | "no-duplicate-variable": true, 49 | "no-empty": true, 50 | "no-eval": true, 51 | "no-shadowed-variable": true, 52 | "no-string-literal": true, 53 | "no-switch-case-fall-through": true, 54 | "no-trailing-whitespace": false, 55 | "no-unused-expression": true, 56 | "no-use-before-declare": true, 57 | "one-line": [ 58 | true, 59 | "check-catch", 60 | "check-else", 61 | "check-open-brace", 62 | "check-whitespace" 63 | ], 64 | "quotemark": [true, "single", "jsx-double"], 65 | "radix": true, 66 | "semicolon": [true, "always"], 67 | "switch-default": true, 68 | 69 | "trailing-comma": [false], 70 | 71 | "triple-equals": [ true, "allow-null-check" ], 72 | "typedef": [ 73 | true, 74 | "parameter", 75 | "property-declaration" 76 | ], 77 | "typedef-whitespace": [ 78 | true, 79 | { 80 | "call-signature": "nospace", 81 | "index-signature": "nospace", 82 | "parameter": "nospace", 83 | "property-declaration": "nospace", 84 | "variable-declaration": "nospace" 85 | } 86 | ], 87 | "variable-name": [true, "ban-keywords", "check-format", "allow-leading-underscore", "allow-pascal-case"], 88 | "whitespace": [ 89 | true, 90 | "check-branch", 91 | "check-decl", 92 | "check-module", 93 | "check-operator", 94 | "check-separator", 95 | "check-type", 96 | "check-typecast" 97 | ] 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /examples/counterTypeScript/src/components/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | 3 | import { setupCreateUIState } from 'redux-ui-state/lib/createUIState'; 4 | 5 | import { 6 | CounterUtilTransformedPropsStaticId, 7 | CounterUtilTranformedPropsDynamicId, 8 | CounterUtilRawPropsStaticId, 9 | CounterUtilsRawPropsDynamicId, 10 | } from './Counters.container'; 11 | 12 | import { 13 | renderPropUnmapped, 14 | renderPropMapped, 15 | utilTransformedDynamic1, 16 | utilTransformedDynamic2, 17 | utilRawDynamic1, 18 | utilRawDynamic2, 19 | } from '../uiState'; 20 | 21 | interface UIState { 22 | index: number; 23 | } 24 | 25 | export interface TransformedProps { 26 | index: number; 27 | increment: () => void; 28 | decrement: () => void; 29 | } 30 | 31 | const createUIState = setupCreateUIState(); 32 | 33 | export const UIStateUnmapped = createUIState(renderPropUnmapped.key); 34 | export const UIStateMapped = createUIState( 35 | renderPropMapped.key, 36 | ({ uiState, setUIState }) => ({ 37 | index: uiState.index, 38 | increment: () => setUIState({ index: uiState.index + 1 }), 39 | decrement: () => setUIState({ index: uiState.index - 1 }) 40 | }) 41 | ); 42 | 43 | class App extends React.Component<{}, {}> { 44 | 45 | increment = () => { 46 | this.setState({}); 47 | } 48 | 49 | render() { 50 | return ( 51 |
52 |

Render Prop Implementations

53 |

Unmapped render props

54 | 55 | {({ uiState: { index }, setUIState }) => ( 56 |
57 |
Value: {index}
58 |
59 | 60 | 61 |
62 |
63 | )} 64 |
65 |
66 |

Unmapped render props

67 | 68 | {({ index, increment, decrement }) => ( 69 |
70 |
Value: {index}
71 |
72 | 73 | 74 |
75 |
76 | )} 77 |
78 |
79 |

Higher Order Component Implementations

80 |

Transformed props, static id

81 | 82 | 83 |
84 |

Transformed props, dynamic id

85 | 86 | 87 |
88 | 89 |

Raw props, static id

90 | 91 | 92 |
93 | 94 |

Raw props, dynamic id

95 | 96 | 97 |
98 | 99 |
100 | ); 101 | } 102 | } 103 | 104 | export default App; 105 | -------------------------------------------------------------------------------- /src/connectUIState.ts: -------------------------------------------------------------------------------- 1 | import { ComponentClass } from 'react'; 2 | import { connect } from 'react-redux'; 3 | import { 4 | WrappedComponentWithDefaultProps, 5 | WrappedComponentWithMappedProps, 6 | DefaultStoreState, 7 | Id, 8 | uiStateSelector, 9 | setUIStateSelector, 10 | defaultUIStateBranchSelector, 11 | UIStateBranchSelector, 12 | Props, 13 | StateProps, 14 | DispatchProps, 15 | } from './utils'; 16 | 17 | // tslint:disable-next-line:class-name 18 | export interface __IMPORT_FIX { 19 | UIStateBranchSelector: UIStateBranchSelector<{}>; 20 | } 21 | 22 | export type MapConnectUIStateProps = ( 23 | props: StateProps & DispatchProps, 24 | ownProps: Readonly, 25 | ) => TTransformedProps; 26 | 27 | export const defaultMapper = (props: Props) => props; 28 | 29 | /** 30 | * A higher order component responsible for injecting Redux UI State props (uiState and setUIState) into a Component 31 | * @param id A string or function that accepts component props and returns a string 32 | * @param mapProps A function that maps raw props into a nicer more contextually relevant shape 33 | */ 34 | export interface ConnectUIState { 35 | (id: Id): ( 36 | Component: WrappedComponentWithDefaultProps 37 | ) => ComponentClass; 38 | 39 | ( 40 | id: Id, 41 | mapProps: MapConnectUIStateProps< 42 | TUIState, 43 | TMappedProps, 44 | TProps 45 | > 46 | ): ( 47 | Component: WrappedComponentWithMappedProps< 48 | TUIState, 49 | TProps, 50 | TMappedProps 51 | > 52 | ) => ComponentClass; 53 | } 54 | 55 | /** 56 | * A higher order component factory that passes UI state related properties and functions to the wrapped component. 57 | * The first function should always be called only once during the life of an application as shown below, with the 58 | * result being a standard HOC. 59 | * 60 | * // utils.ts 61 | * const connectUIState = createConnectUIState(state => state.ui); 62 | * 63 | * // Counter.ts 64 | * ... 65 | * export default connectUIState('counter')(Counter); 66 | * 67 | * @param uiStateBranchSelector The function that selects the uiState branch from the store 68 | */ 69 | export const setupConnectUIState = ( 70 | uiStateBranchSelector = defaultUIStateBranchSelector 71 | ): ConnectUIState => < 72 | TUIState, 73 | TProps extends {}, 74 | TMappedProps, 75 | TAppState 76 | >( 77 | id: Id, 78 | mapProps?: MapConnectUIStateProps< 79 | TUIState, 80 | TMappedProps, 81 | TProps 82 | > 83 | ) => ( 84 | Component: 85 | | WrappedComponentWithDefaultProps 86 | | WrappedComponentWithMappedProps // tslint:disable-line:max-line-length 87 | ): ComponentClass => 88 | connect( 89 | (state: TAppState, props: TProps) => ({ 90 | uiState: uiStateSelector( 91 | state, 92 | Object.assign({ uiStateId: id, uiStateBranchSelector }, props) 93 | ) as TUIState 94 | }), 95 | (dispatch, props: TProps) => ({ 96 | setUIState: setUIStateSelector(dispatch, Object.assign({ uiStateId: id }, props)), 97 | }), 98 | (stateProps, dispatchProps, ownProps) => mapProps 99 | ? mapProps(Object.assign({}, stateProps, dispatchProps), ownProps) 100 | : Object.assign({}, stateProps, dispatchProps, ownProps) 101 | )( 102 | // This any is in place because the function is overloaded - function interface variants will 103 | // catch errors relating to passing mismatching components and mapping functions 104 | // tslint:disable-next-line:no-any 105 | Component as any 106 | ); 107 | 108 | export const defaultConnectUIState = setupConnectUIState( 109 | defaultUIStateBranchSelector 110 | ); 111 | -------------------------------------------------------------------------------- /examples/counterTypeScript/src/registerServiceWorker.ts: -------------------------------------------------------------------------------- 1 | // tslint:disable:no-console 2 | // In production, we register a service worker to serve assets from local cache. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on the 'N+1' visit to a page, since previously 7 | // cached resources are updated in the background. 8 | 9 | // To learn more about the benefits of this model, read https://goo.gl/KwvDNy. 10 | // This link also includes instructions on opting out of this behavior. 11 | 12 | const isLocalhost = Boolean( 13 | window.location.hostname === 'localhost' || 14 | // [::1] is the IPv6 localhost address. 15 | window.location.hostname === '[::1]' || 16 | // 127.0.0.1/8 is considered localhost for IPv4. 17 | window.location.hostname.match( 18 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 19 | ) 20 | ); 21 | 22 | export default function register() { 23 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 24 | // The URL constructor is available in all browsers that support SW. 25 | const publicUrl = new URL( 26 | process.env.PUBLIC_URL!, 27 | window.location.toString() 28 | ); 29 | if (publicUrl.origin !== window.location.origin) { 30 | // Our service worker won't work if PUBLIC_URL is on a different origin 31 | // from what our page is served on. This might happen if a CDN is used to 32 | // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 33 | return; 34 | } 35 | 36 | window.addEventListener('load', () => { 37 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 38 | 39 | if (!isLocalhost) { 40 | // Is not local host. Just register service worker 41 | registerValidSW(swUrl); 42 | } else { 43 | // This is running on localhost. Lets check if a service worker still exists or not. 44 | checkValidServiceWorker(swUrl); 45 | } 46 | }); 47 | } 48 | } 49 | 50 | function registerValidSW(swUrl: string) { 51 | navigator.serviceWorker 52 | .register(swUrl) 53 | .then(registration => { 54 | registration.onupdatefound = () => { 55 | const installingWorker = registration.installing; 56 | if (installingWorker) { 57 | installingWorker.onstatechange = () => { 58 | if (installingWorker.state === 'installed') { 59 | if (navigator.serviceWorker.controller) { 60 | // At this point, the old content will have been purged and 61 | // the fresh content will have been added to the cache. 62 | // It's the perfect time to display a 'New content is 63 | // available; please refresh.' message in your web app. 64 | console.log('New content is available; please refresh.'); 65 | } else { 66 | // At this point, everything has been precached. 67 | // It's the perfect time to display a 68 | // 'Content is cached for offline use.' message. 69 | console.log('Content is cached for offline use.'); 70 | } 71 | } 72 | }; 73 | } 74 | }; 75 | }) 76 | .catch(error => { 77 | console.error('Error during service worker registration:', error); 78 | }); 79 | } 80 | 81 | function checkValidServiceWorker(swUrl: string) { 82 | // Check if the service worker can be found. If it can't reload the page. 83 | fetch(swUrl) 84 | .then(response => { 85 | // Ensure service worker exists, and that we really are getting a JS file. 86 | if ( 87 | response.status === 404 || 88 | response.headers.get('content-type')!.indexOf('javascript') === -1 89 | ) { 90 | // No service worker found. Probably a different app. Reload the page. 91 | navigator.serviceWorker.ready.then(registration => { 92 | registration.unregister().then(() => { 93 | window.location.reload(); 94 | }); 95 | }); 96 | } else { 97 | // Service worker found. Proceed as normal. 98 | registerValidSW(swUrl); 99 | } 100 | }) 101 | .catch(() => { 102 | console.log( 103 | 'No internet connection found. App is running in offline mode.' 104 | ); 105 | }); 106 | } 107 | 108 | export function unregister() { 109 | if ('serviceWorker' in navigator) { 110 | navigator.serviceWorker.ready.then(registration => { 111 | registration.unregister(); 112 | }); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/__tests__/connectUIState.test.tsx: -------------------------------------------------------------------------------- 1 | import * as reactRedux from 'react-redux'; 2 | import * as utils from '../utils'; 3 | import * as React from 'react'; 4 | import { setupConnectUIState } from '../connectUIState'; 5 | import { 6 | Props as ReduxUIStateProps, 7 | defaultUIStateBranchSelector, 8 | } from '../utils'; 9 | import { MappedProps, UIState } from './componentTestUtils'; 10 | 11 | export interface CounterProps { 12 | prefix: string; 13 | } 14 | 15 | export type RawProps = CounterProps & ReduxUIStateProps; 16 | 17 | export const CounterMapped: React.StatelessComponent = ({ 18 | message, 19 | increment, 20 | decrement 21 | }) => 22 |
23 |
24 | {message} 25 |
26 |
27 | 28 | 29 |
30 |
; 31 | 32 | export const CounterRaw: React.StatelessComponent = ({ 33 | prefix, 34 | uiState, 35 | setUIState 36 | }) => 37 |
38 |
39 | {prefix}{uiState.index} 40 |
41 |
42 | 45 | 48 |
49 |
; 50 | 51 | export const uiStateId = 'counter'; 52 | export const initialState = { 53 | [uiStateId]: 0 54 | }; 55 | 56 | const uiStateSelectorMockOutput = { index: 0 }; 57 | const setUIStateSelectorMockOutput = () => undefined; 58 | 59 | const restoreMocks = (mocks: { [key: string]: jest.Mock | jest.SpyInstance }) => // tslint:disable-line:no-any 60 | Object.keys(mocks).forEach(key => (mocks[key] as any).mockRestore()); // tslint:disable-line:no-any 61 | 62 | describe('setupConnectUIState', () => { 63 | 64 | interface UniversalAssertionMocks { 65 | connect: jest.SpyInstance; 66 | uiStateSelector: jest.Mock; 67 | setUIStateSelector: jest.Mock; 68 | } 69 | 70 | const runUniversalAssertions = (mocks: UniversalAssertionMocks) => { 71 | const [mapStateToProps, mapDispatchToProps] = jest.spyOn(reactRedux, 'connect').mock.calls[0]; 72 | 73 | expect(mocks.connect).toHaveBeenCalledTimes(1); 74 | 75 | expect(mapStateToProps()) 76 | .toEqual({ uiState: uiStateSelectorMockOutput }); 77 | 78 | expect(mocks.uiStateSelector) 79 | .toBeCalledWith( 80 | undefined, 81 | { 82 | uiStateBranchSelector: defaultUIStateBranchSelector, 83 | uiStateId 84 | } 85 | ); 86 | 87 | expect(mapDispatchToProps()) 88 | .toEqual({ 89 | setUIState: setUIStateSelectorMockOutput 90 | }); 91 | expect(mocks.setUIStateSelector) 92 | .toBeCalledWith(undefined, { uiStateId }); 93 | }; 94 | 95 | it('should pass correct mapping functions to connect for raw props', () => { 96 | const mocks = { 97 | connect: jest.spyOn(reactRedux, 'connect'), 98 | uiStateSelector: jest.spyOn(utils, 'uiStateSelector').mockReturnValue(uiStateSelectorMockOutput), 99 | setUIStateSelector: jest.spyOn(utils, 'setUIStateSelector').mockReturnValue(setUIStateSelectorMockOutput), 100 | }; 101 | 102 | setupConnectUIState(defaultUIStateBranchSelector)(uiStateId)( 103 | CounterRaw 104 | ); 105 | 106 | runUniversalAssertions(mocks); 107 | 108 | restoreMocks(mocks); 109 | }); 110 | 111 | it('should pass the correct mapping functions to connect for mapped props', () => { 112 | const mocks = { 113 | connect: jest.spyOn(reactRedux, 'connect'), 114 | uiStateSelector: jest.spyOn(utils, 'uiStateSelector').mockReturnValue(uiStateSelectorMockOutput), 115 | setUIStateSelector: jest.spyOn(utils, 'setUIStateSelector').mockReturnValue(setUIStateSelectorMockOutput), 116 | }; 117 | 118 | const mapPropsOutput = { message: 'I have been mapped' }; 119 | const mapProps = jest.fn().mockReturnValue(mapPropsOutput); 120 | setupConnectUIState(defaultUIStateBranchSelector)(uiStateId, mapProps)(CounterMapped); 121 | 122 | runUniversalAssertions(mocks); 123 | const [mapStateToProps, mapDispatchToProps, mergeProps] = jest.spyOn(reactRedux, 'connect').mock.calls[0]; 124 | 125 | const ownProps = { someOtherValue: 'Hello World!' }; 126 | const mergedProps = mergeProps(mapStateToProps(), mapDispatchToProps(), ownProps); 127 | 128 | expect(mapProps.mock.calls[0]).toEqual([ 129 | { ...mapStateToProps(), ...mapDispatchToProps() }, 130 | ownProps 131 | ]); 132 | 133 | expect(mergedProps).toEqual(mapPropsOutput); 134 | 135 | restoreMocks(mocks); 136 | }); 137 | }); 138 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Redux UI State 2 | 3 | [![version](https://img.shields.io/npm/v/redux-ui-state.svg)](https://npmjs.com/package/redux-ui-state) 4 | [![licence](https://img.shields.io/github/license/jamiecopeland/redux-ui-state.svg)](https://github.com/jamiecopeland/redux-ui-state/blob/master/LICENSE.md) 5 | ![build](https://img.shields.io/travis/jamiecopeland/redux-ui-state.svg) 6 | ![gzip size](http://img.badgesize.io/https://unpkg.com/redux-ui-state/dist/redux-ui-state.min.js?compression=gzip&label=size%20gzipped) 7 | ![size](http://img.badgesize.io/https://unpkg.com/redux-ui-state/dist/redux-ui-state.min.js?label=size%20ungzipped) 8 | [![downloads](https://img.shields.io/npm/dm/redux-ui-state.svg)](https://npmjs.com/package/redux-ui-state) 9 | 10 | 11 | UI state management for Redux applications. 12 | 13 | Makes storing UI state in the Redux store and sharing it between components simple, safe and transparent. 14 | 15 | *WARNING: This should only be used for storing small amounts of UI data. Almost all of your application's data should be managed using standard reducers.* 16 | 17 | ## Installation 18 | 19 | ``` 20 | npm install redux-ui-state 21 | ``` 22 | 23 | Redux UI State is written in TypeScript, so the typings are automatically included and always up to date 🎉 24 | 25 | ## Getting started 26 | 27 | NOTE: This is a simple implementation. For more complex implementations (e.g. custom Redux state shape and a dynamic config id), see the [example](https://github.com/jamiecopeland/redux-ui-state/tree/master/examples) folder. 28 | 29 | ### 1. Create the reducer for your app: 30 | 31 | Your root reducer should look this: 32 | 33 | ```typescript 34 | // rootReducer.js 35 | 36 | import { combineReducers } from 'redux'; 37 | import { createReducer, DEFAULT_BRANCH_NAME } from 'redux-ui-state'; 38 | 39 | const initialState = { 40 | counter: { 41 | index: 0 42 | }, 43 | } 44 | 45 | export default combineReducers({ 46 | ... 47 | [DEFAULT_BRANCH_NAME]: createReducer(initialState), 48 | ... 49 | }); 50 | ``` 51 | 52 | ### 2. Use the data in your UI: 53 | 54 | **Render Prop implementation** 55 | 56 | Use the `setupCreateUIState` higher order component to inject `uiState` (to be used in place of `this.state`) and 57 | `setUIState` (to be used in place of `this.setState`) into your render prop. 58 | 59 | ```typescript 60 | ////////////////////////////////////////////////// 61 | // UIState.js 62 | 63 | // This setupCcreateUIState higher order function allows a custom selector for the ui branch of the 64 | // redux store to be passed in if the ui branch is not named 'ui' and at the root. The call to 65 | // setupConnectUIState should only be done once in your application and the connection function 66 | // should be exported. 67 | const createUIState = setupConnectUIState(); 68 | 69 | ////////////////////////////////////////////////// 70 | // CounterUIState.js 71 | 72 | // Either create a render prop component that maps the data into nicely structured props (preferred) 73 | export const CounterUIStateMapped = createUIState( 74 | 'counter', 75 | ({ uiState, setUIState }) => ({ 76 | index: uiState.index, 77 | increment: () => setUIState({ index: uiState.index + 1 }), 78 | decrement: () => setUIState({ index: uiState.index - 1 }) 79 | }) 80 | ); 81 | 82 | // Or create a render prop component that recieves the raw props 83 | export const CounterUIStateUnmapped = createUIState('counter'); 84 | 85 | ////////////////////////////////////////////////// 86 | // App.js 87 | import React from 'react'; 88 | import Counter from './Counter'; 89 | 90 | const App = () => ( 91 |
92 | 93 | 94 | {({ index, increment, decrement }) => ( 95 |
96 |
Value: {index}
97 |
98 | 99 | 100 |
101 |
102 | )} 103 |
104 | 105 | 106 | {({ uiState: { index }, setUIState }) => ( 107 |
108 |
Value: {index}
109 |
110 | 111 | 112 |
113 |
114 | )} 115 |
116 | 117 |
118 | ); 119 | ``` 120 | 121 | #### Higner order component implementation 122 | 123 | Use the `setupConnectUIState` higher order component to inject `uiState` (to be used in place of `this.state`) and 124 | `setUIState` (to be used in place of `this.setState`) into your component. 125 | 126 | ```typescript 127 | ////////////////////////////////////////////////// 128 | // UIState.js 129 | 130 | // This setupConnectUIState higher order function allows a custom selector for the ui branch of the 131 | // redux store to be passed in if the ui branch is not named 'ui' and at the root. The call to 132 | // setupConnectUIState should only be done once in your application and the connection function 133 | // should be exported. 134 | const connectUIState = setupConnectUIState(); 135 | 136 | ////////////////////////////////////////////////// 137 | // Counter.js 138 | import React from 'react'; 139 | import { defaultConnectUIState as connectUIState } from 'redux-ui-state'; 140 | 141 | const Counter = ({ indexMessage, increment, decrement }) => ( 142 |
143 |
144 | {indexMessage} 145 |
146 |
147 | 148 | 149 |
150 |
151 | ); 152 | 153 | export default connectUIState( 154 | 'counter', 155 | ({ index }, { setUIState }, { prefix }) = ({ 156 | indexMessage: `${prefix}${index}`, 157 | decrement: () => setUIState({ index: index - 1 }), 158 | increment: () => setUIState({ index: index + 1 }), 159 | }) 160 | )(Counter); 161 | 162 | ////////////////////////////////////////////////// 163 | // App.js 164 | import React from 'react'; 165 | import Counter from './Counter'; 166 | 167 | const App = () => ( 168 |
169 | 170 |
171 | ); 172 | ``` 173 | 174 | ## Rationale 175 | 176 | ### Shorter practical answer 🔨 177 | 178 | Sharing UI state between components usually means either: 179 | - Adding state to a parent component that shouldn't really be concerned with it and passing it through view layers that also shouldn't be concerned with it. 180 | - Creating a custom UI state reducer with specific actions for each atom of state that will change. 181 | 182 | Redux UI State replaces these overly complex, error prone solutions with a reducer and a higher order component that provides clean access to UI state held in the Redux store. 183 | 184 | ### Longer theoretical answer 🤓 185 | 186 | #### Single state atom 187 | Redux is a predictable, easy to undertand state container primarly because it has a single state object. This allows developers to inspect the entire state of an application at any given time and create powerful dev tools that enable magical things like time travel debugging. Keeping everything in one place is a large part of what drove Redux to win out over the traditional multi store Flux architecture yet most React applications let multiple data stores in through the back door by using `this.setState` in components. 188 | 189 | As soon as this happens the single state atom principle breaks down, the entire application state cannot be inspected and full state serialization / time travel debugging becomes impossible. 190 | 191 | #### Sharing state with siblings 192 | 193 | Sibling components sometimes need to share their UI state. This can be achieved by moving that state up into the parent component, but this is often not something the parent should be concerned with, which means increased complexity, confusing APIs, less reusability and the system as a whole being more prone to errors. 194 | 195 | #### Sharing state with children 196 | 197 | In situations where it does make sense for a parent to hold a piece of UI state, that data may be needed several layers down in the view hierarchy, meaning intermediate components, unconcerned with the data in question, need to include it in their APIs, again creating unnecessary complexity, which results in confusing APIs and a greater likelihood of errors cropping up. 198 | 199 | ### A solution 200 | 201 | Redux UI State replaces these overly complex, error prone solutions with a higher order component that provides clean access to UI state held in the Redux store. 202 | 203 | ## TODO / Roadmap 204 | * Add Github pages page 205 | * Add documentation for advanced implementations 206 | * Add plain JavaScript examples 207 | * Add flow type definitions 208 | 209 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { Dispatch, Action } from 'redux'; 3 | import { createSelector, ParametricSelector } from 'reselect'; 4 | import { setUIState } from './actions'; 5 | 6 | ////////////////////////////////////////////////// 7 | // Id interfaces and functions 8 | 9 | /** 10 | * A string or a function accepting the props as an argument and returning a string 11 | */ 12 | export type IdFunction = (props: TProps) => string; 13 | export type Id = string | IdFunction; 14 | 15 | /** 16 | * A type guard guaranteeing id is a string; 17 | */ 18 | export const idIsString = (id: Id): id is string => typeof id === 'string'; 19 | 20 | /** 21 | * A type guard guaranteeing id is a function that accepts props and returns a string 22 | */ 23 | export const idIsFunction = (id: Id): id is IdFunction => typeof id === 'function'; 24 | 25 | /** 26 | * Returns a string or undefined from the union type of (string | function that returns string) 27 | */ 28 | export const getStringFromId = (id: Id, props: TProps): string | undefined => { 29 | if (idIsString(id)) { return id; } 30 | if (idIsFunction(id)) { return id(props); } 31 | return undefined; 32 | }; 33 | 34 | ////////////////////////////////////////////////// 35 | // Interfaces 36 | 37 | /** 38 | * The default shape of a store containing the uiState reducer 39 | */ 40 | export interface DefaultStoreState { 41 | // This is slightly gross and involves repetition of the value in DEFAULT_BRANCH_NAME, but 42 | // TypeScript doesn't currently allow computed property names in interfaces - [DEFAULT_BRANCH_NAME]: UIStateBranch; 43 | ui: UIStateBranch; 44 | } 45 | 46 | /** 47 | * The branch of the Redux store governed by reduxUIState's reducer 48 | */ 49 | export type UIStateBranch = Record; 50 | 51 | /** 52 | * The state props passed into a component wrapped by addReduxUIState 53 | */ 54 | export interface StateProps { 55 | uiState: TUIState; 56 | } 57 | 58 | /** 59 | * The dispatch props passed into a component wrapped by addReduxUIState 60 | */ 61 | export interface DispatchProps { 62 | setUIState: (state: Partial) => void; 63 | } 64 | 65 | /** 66 | * All the props props passed into a component wrapped by addReduxUIState 67 | */ 68 | export type Props = StateProps & DispatchProps; 69 | 70 | /** 71 | * The component passed into addReduxUIState 72 | */ 73 | export type AbstractWrappedComponent = React.StatelessComponent | React.ComponentClass; 74 | 75 | /** 76 | * A component being passed into addReduxUIState that accepts the default props 77 | */ 78 | export type WrappedComponentWithDefaultProps = AbstractWrappedComponent>; 79 | 80 | /** 81 | * A component being passed into addReduxUIState that accepts mapped props 82 | */ 83 | export type WrappedComponentWithMappedProps = AbstractWrappedComponent; // tslint:disable-line:max-line-length 84 | 85 | /** 86 | * A Selector that accepts the full application state and returns the Redux UI State branch 87 | */ 88 | // export type UIStateBranchSelector = (appState: TAppState) => UIStateBranch; 89 | // This looks weird, but the standard type definition (commented out above) causes a Reselect import error 90 | export interface UIStateBranchSelector extends ParametricSelector { 91 | (appState: TAppState): UIStateBranch; 92 | } 93 | 94 | /** 95 | * The props representing the key of the UI state data in the store 96 | */ 97 | export interface UIStateIdProps { 98 | uiStateId: Id; 99 | } 100 | 101 | /** 102 | * The function used to make changes to the state 103 | */ 104 | export type SetUIState = (state: Partial) => void; 105 | 106 | ////////////////////////////////////////////////// 107 | // Constants 108 | 109 | export const DEFAULT_BRANCH_NAME = 'ui'; 110 | export const UNDEFINED_KEY = 'REDUX_UI_STATE_UNDEFINED_KEY'; 111 | 112 | ////////////////////////////////////////////////// 113 | // Selectors 114 | 115 | export const stateSelector = (state: TAppState) => state; 116 | export const propsSelector = (_: any, props: TProps) => props; // tslint:disable-line:no-any 117 | 118 | /** 119 | * Selects the ui state branch from the default location in the Redux store 120 | */ 121 | export const defaultUIStateBranchSelector: UIStateBranchSelector = ( 122 | state: DefaultStoreState 123 | ): UIStateBranch => state[DEFAULT_BRANCH_NAME]; 124 | 125 | /** 126 | * The props containing the selector for the uiState branch. 127 | */ 128 | export interface UIStateBranchSelectorSelectorProps { 129 | uiStateBranchSelector?: UIStateBranchSelector; 130 | } 131 | 132 | /** 133 | * Selects the uiState branch selector, returning defaultUIStateBranchSelector if a custom is not found in the props 134 | */ 135 | export const uiStateBranchSelectorSelector = ( 136 | _: any, // tslint:disable-line:no-any 137 | props: UIStateBranchSelectorSelectorProps 138 | ) => { 139 | const uiStateBranchSelector = props && props.uiStateBranchSelector; 140 | 141 | if (!uiStateBranchSelector) { 142 | throw new Error( 143 | 'redux-ui-state Couldn\'t find uiStateBranchSelector in props - this is most likely because ' + 144 | 'createConnectUIState was called without an argument'); 145 | } 146 | 147 | return uiStateBranchSelector; 148 | }; 149 | 150 | export const uiStateBranchSelector = createSelector( 151 | uiStateBranchSelectorSelector, 152 | stateSelector, 153 | (selector, state) => { 154 | const branch = selector(state); 155 | if (!branch) { 156 | throw new Error( 157 | 'redux-ui-state Could not select UI state branch from the store - this is either because the reducer has not' + 158 | 'been composed properly or the selector is looking in the wrong location.' 159 | ); 160 | } 161 | return branch; 162 | } 163 | ); 164 | 165 | export const idSelector = ( 166 | _: any, // tslint:disable-line:no-any 167 | props: TProps & Partial> 168 | ) => { 169 | if (!props.uiStateId) { 170 | throw new Error( 171 | 'Couldn\'t find uiStateId prop for idSelector in Redux UI State - this usually occurs because the id passed ' + 172 | 'into connectUIState is undefined, or the uiStateId prop being passed into a component is undefined.' 173 | ); 174 | } 175 | return getStringFromId(props.uiStateId, props); 176 | }; 177 | 178 | export const UI_STATE_SELECTOR_WARNING_MESSAGE = 'redux-ui-state state key is undefined'; 179 | export const createUIStateSelectorWarningMessage = (id?: string) => ( 180 | `redux-ui-state uiStateSelector found undefined state for key: ${id}.\n` + 181 | `This is most often due to the value not being initialized in createReducer.` 182 | ); 183 | 184 | export const uiStateSelector = createSelector( 185 | uiStateBranchSelector, 186 | idSelector, 187 | (uiStateBranch, id) => { 188 | if (!id) { 189 | console.warn(UI_STATE_SELECTOR_WARNING_MESSAGE); 190 | } 191 | const uiState = uiStateBranch[id || UNDEFINED_KEY]; 192 | if (!uiState) { 193 | console.warn(createUIStateSelectorWarningMessage(id)); 194 | } 195 | // Since the branch in the store does not contain the types for each of the sub-branches 196 | // uiState is cast to any. This is recast to the UIState state generic in createUIState 197 | // connectUIState 198 | // tslint:disable-next-line:no-any 199 | return uiState as any; 200 | } 201 | ); 202 | 203 | export const SET_UI_STATE_SELECTOR_WARNING_MESSAGE = 204 | 'redux-ui-state - state key is undefined in setUIStateSelector\n' + 205 | 'This is due to an id not being passed via the props'; 206 | export const SET_UI_STATE_WARNING_MESSAGE = 207 | 'redux-ui-state - state key is undefined in setUIStateSelector\n' + 208 | 'This is due to an id not being passed via the props'; 209 | 210 | /** 211 | * Selects the setUIState function. 212 | * This differs from normal selectors in that it is a dispatch selector, meaning that it expects dispatch as the first 213 | * function and returns a function capable of dispatching through the Redux store. 214 | * @param dispatch The dispatch function of the Redux store 215 | * @param props The component's props 216 | */ 217 | export const setUIStateSelector = >( 218 | dispatch: Dispatch, 219 | props: TProps 220 | ) => { 221 | const id = idSelector(undefined, props); 222 | if (!id) { 223 | console.warn(SET_UI_STATE_SELECTOR_WARNING_MESSAGE); 224 | return (state: Partial) => { 225 | console.warn(SET_UI_STATE_WARNING_MESSAGE); 226 | }; 227 | } 228 | return (state: Partial) => { 229 | dispatch(setUIState>({ id, state })); 230 | }; 231 | }; 232 | -------------------------------------------------------------------------------- /src/__tests__/utils.test.ts: -------------------------------------------------------------------------------- 1 | import { setUIState as setUIStateActionCreator } from '../actions'; 2 | 3 | import { 4 | Id, 5 | UIStateIdProps, 6 | DefaultStoreState, 7 | UIStateBranch, 8 | UIStateBranchSelectorSelectorProps, 9 | 10 | idIsString, 11 | idIsFunction, 12 | getStringFromId, 13 | stateSelector, 14 | propsSelector, 15 | defaultUIStateBranchSelector, 16 | uiStateBranchSelectorSelector, 17 | uiStateBranchSelector, 18 | idSelector, 19 | uiStateSelector, 20 | setUIStateSelector, 21 | SET_UI_STATE_SELECTOR_WARNING_MESSAGE, 22 | SET_UI_STATE_WARNING_MESSAGE, 23 | UI_STATE_SELECTOR_WARNING_MESSAGE, 24 | createUIStateSelectorWarningMessage, 25 | } from '../utils'; 26 | 27 | ////////////////////////////////////////////////// 28 | // Fixtures 29 | 30 | const componentId = 'thing'; 31 | 32 | const getUIState = (): UIStateBranch => ({ 33 | components: { 34 | [componentId]: { 35 | counter: 0, 36 | } 37 | } 38 | }); 39 | 40 | const getDefaultAppState = (): DefaultStoreState => ({ 41 | ui: getUIState(), 42 | }); 43 | 44 | interface CustomStoreState { 45 | vendors: { 46 | ui: UIStateBranch; 47 | }; 48 | } 49 | 50 | const getCustomAppState = (): CustomStoreState => ({ 51 | vendors: { 52 | ui: getUIState(), 53 | } 54 | }); 55 | 56 | const customSelector = (state: CustomStoreState) => state.vendors.ui; 57 | 58 | const getPropsWithCustomSelector: UIStateBranchSelectorSelectorProps = { 59 | uiStateBranchSelector: customSelector 60 | }; 61 | 62 | ////////////////////////////////////////////////// 63 | // Tests 64 | 65 | describe('utils', () => { 66 | 67 | describe('idIsString', () => { 68 | it('should return true if id is string', () => { 69 | expect( 70 | idIsString(componentId) 71 | ).toBe(true); 72 | }); 73 | 74 | it('should return false if id is not a string', () => { 75 | expect( 76 | idIsString(() => componentId) 77 | ).toBe(false); 78 | expect( 79 | idIsString(({ uiStateId }) => uiStateId) 80 | ).toBe(false); 81 | expect( 82 | idIsString(undefined) 83 | ).toBe(false); 84 | }); 85 | }); 86 | 87 | describe('idIsFunction', () => { 88 | it('should return true if id is function', () => { 89 | expect( 90 | idIsFunction(({ uiStateId }) => uiStateId) 91 | ).toBe(true); 92 | }); 93 | 94 | it('should return false if id is not a function', () => { 95 | expect( 96 | idIsFunction(componentId) 97 | ).toBe(false); 98 | }); 99 | 100 | it('should return false if id is not a function', () => { 101 | expect( 102 | idIsFunction(undefined) 103 | ).toBe(false); 104 | }); 105 | }); 106 | 107 | describe('getStringFromId', () => { 108 | interface Props { uiStateId?: string; } 109 | 110 | const getId: Id = ({ uiStateId }) => uiStateId; 111 | const populatedProps: Props = { uiStateId: componentId }; 112 | const unpopulatedProps: Props = {}; 113 | 114 | it('should return value passed in for a string', () => { 115 | expect( 116 | getStringFromId(componentId, unpopulatedProps) 117 | ).toBe(componentId); 118 | 119 | expect( 120 | getStringFromId(componentId, populatedProps) 121 | ).toBe(componentId); 122 | }); 123 | 124 | it('should return value contained in props via function', () => { 125 | expect( 126 | getStringFromId(getId, populatedProps) 127 | ).toBe(componentId); 128 | 129 | expect( 130 | getStringFromId(getId, unpopulatedProps) 131 | ).toBeUndefined(); 132 | }); 133 | }); 134 | 135 | describe('stateSeletor', () => { 136 | it('should return props when props are present', () => { 137 | const state: DefaultStoreState = { ui: { components: { } } }; 138 | expect( 139 | stateSelector(state) 140 | ).toBe(state); 141 | }); 142 | 143 | it('should return undefined when props are not present', () => { 144 | expect( 145 | stateSelector(undefined) 146 | ).toBeUndefined(); 147 | }); 148 | }); 149 | 150 | describe('propsSelector', () => { 151 | it('should return props when props are present', () => { 152 | const props = { uiStateId: componentId }; 153 | expect( 154 | propsSelector(undefined, props) 155 | ).toBe(props); 156 | }); 157 | 158 | it('should return undefined when props are not present', () => { 159 | expect( 160 | propsSelector(undefined, undefined) 161 | ).toBeUndefined(); 162 | }); 163 | }); 164 | 165 | describe('defaultUIStateBranchSelector', () => { 166 | it('should select branch from populated state', () => { 167 | expect( 168 | defaultUIStateBranchSelector(getDefaultAppState()) 169 | ).toEqual(getUIState()); 170 | }); 171 | 172 | it('should select undefined from unpopulated state', () => { 173 | expect( 174 | defaultUIStateBranchSelector({} as any) // tslint:disable-line:no-any 175 | ).toBeUndefined(); 176 | }); 177 | }); 178 | 179 | describe('uiStateBranchSelectorSelector', () => { 180 | it('should return a selector if props are populated', () => { 181 | expect( 182 | uiStateBranchSelectorSelector({}, { 183 | uiStateBranchSelector: customSelector 184 | }) 185 | ).toBe(customSelector); 186 | }); 187 | 188 | it('should return the undefined if props are empty', () => { 189 | expect( 190 | () => uiStateBranchSelectorSelector({}, {}) 191 | ).toThrowError(); 192 | }); 193 | }); 194 | 195 | describe('defaultUIStateBranchSelector', () => { 196 | it('should select branch from populated default state', () => { 197 | expect( 198 | defaultUIStateBranchSelector(getDefaultAppState()) 199 | ).toEqual(getUIState()); 200 | }); 201 | 202 | it('should select undefined from unpopulated state', () => { 203 | expect( 204 | defaultUIStateBranchSelector({} as any) // tslint:disable-line:no-any 205 | ).toBeUndefined(); 206 | }); 207 | }); 208 | 209 | describe('uiStateBranchSelector', () => { 210 | it('should select the uiState branch if it is present', () => { 211 | const appState = getDefaultAppState(); 212 | expect( 213 | uiStateBranchSelector.resultFunc(defaultUIStateBranchSelector, appState) 214 | ).toBe(appState.ui); 215 | }); 216 | 217 | it('should select undefined if uiState branch is not present', () => { 218 | expect( 219 | () => uiStateBranchSelector({}, {}) 220 | ).toThrow(); 221 | }); 222 | }); 223 | 224 | describe('idSelector', () => { 225 | it('should select the id from the props if id is a string', () => { 226 | expect( 227 | idSelector({}, { 228 | uiStateId: componentId 229 | }) 230 | ).toBe(componentId); 231 | }); 232 | 233 | it('should select the id from the props if id is a function and correct props are present', () => { 234 | interface Props extends UIStateIdProps { 235 | customId: string; 236 | } 237 | expect( 238 | idSelector({}, { 239 | customId: componentId, 240 | uiStateId: ({ customId }) => customId 241 | }) 242 | ).toBe(componentId); 243 | }); 244 | 245 | it('should select undefined if id is a function and dynamic id props is missing', () => { 246 | interface Props extends UIStateIdProps { 247 | customId?: string; 248 | } 249 | expect( 250 | idSelector({}, { 251 | uiStateId: ({ customId }) => customId 252 | }) 253 | ).toBeUndefined(); 254 | }); 255 | 256 | }); 257 | 258 | describe('uiStateSelector', () => { 259 | it('should return the UI state for an identified component if present', () => { 260 | const appState = getDefaultAppState(); 261 | expect( 262 | uiStateSelector.resultFunc(appState.ui.components, componentId) 263 | ).toBe(appState.ui.components[componentId]); 264 | }); 265 | 266 | it('should return undefined if value is not present', () => { 267 | const spy = jest.spyOn(console, 'warn'); 268 | const appState = getDefaultAppState(); 269 | const id = 'notAThing'; 270 | expect( 271 | uiStateSelector.resultFunc(appState.ui.components, id) 272 | ).toBeUndefined(); 273 | expect(spy.mock.calls[0][0]).toBe(createUIStateSelectorWarningMessage(id)); 274 | spy.mockRestore(); 275 | }); 276 | 277 | it('should call console.warn if uiStateId is undefined', () => { 278 | const spy = jest.spyOn(console, 'warn'); 279 | const appState = getDefaultAppState(); 280 | 281 | const output = uiStateSelector.resultFunc(appState.ui.components, undefined); 282 | expect(spy.mock.calls[0][0]).toBe(UI_STATE_SELECTOR_WARNING_MESSAGE); 283 | expect(output).toBeUndefined(); 284 | 285 | spy.mockRestore(); 286 | }); 287 | }); 288 | 289 | describe('setUIStateSelector', () => { 290 | interface UIState { 291 | index: number; 292 | otherValue?: string; 293 | } 294 | 295 | const createWrapper = () => { 296 | const dispatch = jest.fn(); 297 | const setUIState = setUIStateSelector>(dispatch, { uiStateId: componentId }); 298 | return { dispatch, setUIState }; 299 | }; 300 | 301 | it('should return the setUIState function', () => { 302 | const { dispatch, setUIState } = createWrapper(); 303 | const newState: UIState = { index: 13 }; 304 | setUIState(newState); 305 | expect(dispatch).toHaveBeenCalledTimes(1); 306 | expect(dispatch).toHaveBeenCalledWith(setUIStateActionCreator({ 307 | id: componentId, 308 | state: newState 309 | })); 310 | }); 311 | 312 | it('should call console.warn if uiStateId is undefined', () => { 313 | const spy = jest.spyOn(console, 'warn'); 314 | 315 | const output = setUIStateSelector>( 316 | jest.fn(), { uiStateId: () => undefined } 317 | ); 318 | expect(spy.mock.calls[0][0]).toBe(SET_UI_STATE_SELECTOR_WARNING_MESSAGE); 319 | 320 | // Call setUIState function 321 | output({}); 322 | expect(spy.mock.calls[1][0]).toBe(SET_UI_STATE_WARNING_MESSAGE); 323 | 324 | spy.mockRestore(); 325 | }); 326 | }); 327 | 328 | }); 329 | -------------------------------------------------------------------------------- /examples/counterTypeScript/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). 2 | 3 | Below you will find some information on how to perform common tasks.
4 | You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). 5 | 6 | ## Table of Contents 7 | 8 | - [Updating to New Releases](#updating-to-new-releases) 9 | - [Sending Feedback](#sending-feedback) 10 | - [Folder Structure](#folder-structure) 11 | - [Available Scripts](#available-scripts) 12 | - [npm start](#npm-start) 13 | - [npm test](#npm-test) 14 | - [npm run build](#npm-run-build) 15 | - [npm run eject](#npm-run-eject) 16 | - [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) 17 | - [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) 18 | - [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) 19 | - [Debugging in the Editor](#debugging-in-the-editor) 20 | - [Formatting Code Automatically](#formatting-code-automatically) 21 | - [Changing the Page ``](#changing-the-page-title) 22 | - [Installing a Dependency](#installing-a-dependency) 23 | - [Importing a Component](#importing-a-component) 24 | - [Code Splitting](#code-splitting) 25 | - [Adding a Stylesheet](#adding-a-stylesheet) 26 | - [Post-Processing CSS](#post-processing-css) 27 | - [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) 28 | - [Adding Images, Fonts, and Files](#adding-images-fonts-and-files) 29 | - [Using the `public` Folder](#using-the-public-folder) 30 | - [Changing the HTML](#changing-the-html) 31 | - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) 32 | - [When to Use the `public` Folder](#when-to-use-the-public-folder) 33 | - [Using Global Variables](#using-global-variables) 34 | - [Adding Bootstrap](#adding-bootstrap) 35 | - [Using a Custom Theme](#using-a-custom-theme) 36 | - [Adding Flow](#adding-flow) 37 | - [Adding Custom Environment Variables](#adding-custom-environment-variables) 38 | - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) 39 | - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) 40 | - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) 41 | - [Can I Use Decorators?](#can-i-use-decorators) 42 | - [Integrating with an API Backend](#integrating-with-an-api-backend) 43 | - [Node](#node) 44 | - [Ruby on Rails](#ruby-on-rails) 45 | - [Proxying API Requests in Development](#proxying-api-requests-in-development) 46 | - ["Invalid Host Header" Errors After Configuring Proxy](#invalid-host-header-errors-after-configuring-proxy) 47 | - [Configuring the Proxy Manually](#configuring-the-proxy-manually) 48 | - [Configuring a WebSocket Proxy](#configuring-a-websocket-proxy) 49 | - [Using HTTPS in Development](#using-https-in-development) 50 | - [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) 51 | - [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) 52 | - [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) 53 | - [Running Tests](#running-tests) 54 | - [Filename Conventions](#filename-conventions) 55 | - [Command Line Interface](#command-line-interface) 56 | - [Version Control Integration](#version-control-integration) 57 | - [Writing Tests](#writing-tests) 58 | - [Testing Components](#testing-components) 59 | - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) 60 | - [Initializing Test Environment](#initializing-test-environment) 61 | - [Focusing and Excluding Tests](#focusing-and-excluding-tests) 62 | - [Coverage Reporting](#coverage-reporting) 63 | - [Continuous Integration](#continuous-integration) 64 | - [Disabling jsdom](#disabling-jsdom) 65 | - [Snapshot Testing](#snapshot-testing) 66 | - [Editor Integration](#editor-integration) 67 | - [Developing Components in Isolation](#developing-components-in-isolation) 68 | - [Getting Started with Storybook](#getting-started-with-storybook) 69 | - [Getting Started with Styleguidist](#getting-started-with-styleguidist) 70 | - [Making a Progressive Web App](#making-a-progressive-web-app) 71 | - [Opting Out of Caching](#opting-out-of-caching) 72 | - [Offline-First Considerations](#offline-first-considerations) 73 | - [Progressive Web App Metadata](#progressive-web-app-metadata) 74 | - [Analyzing the Bundle Size](#analyzing-the-bundle-size) 75 | - [Deployment](#deployment) 76 | - [Static Server](#static-server) 77 | - [Other Solutions](#other-solutions) 78 | - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) 79 | - [Building for Relative Paths](#building-for-relative-paths) 80 | - [Azure](#azure) 81 | - [Firebase](#firebase) 82 | - [GitHub Pages](#github-pages) 83 | - [Heroku](#heroku) 84 | - [Netlify](#netlify) 85 | - [Now](#now) 86 | - [S3 and CloudFront](#s3-and-cloudfront) 87 | - [Surge](#surge) 88 | - [Advanced Configuration](#advanced-configuration) 89 | - [Troubleshooting](#troubleshooting) 90 | - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) 91 | - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) 92 | - [`npm run build` exits too early](#npm-run-build-exits-too-early) 93 | - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) 94 | - [`npm run build` fails to minify](#npm-run-build-fails-to-minify) 95 | - [Moment.js locales are missing](#momentjs-locales-are-missing) 96 | - [Something Missing?](#something-missing) 97 | 98 | ## Updating to New Releases 99 | 100 | Create React App is divided into two packages: 101 | 102 | * `create-react-app` is a global command-line utility that you use to create new projects. 103 | * `react-scripts` is a development dependency in the generated projects (including this one). 104 | 105 | You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. 106 | 107 | When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. 108 | 109 | To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. 110 | 111 | In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. 112 | 113 | We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. 114 | 115 | ## Sending Feedback 116 | 117 | We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). 118 | 119 | ## Folder Structure 120 | 121 | After creation, your project should look like this: 122 | 123 | ``` 124 | my-app/ 125 | README.md 126 | node_modules/ 127 | package.json 128 | public/ 129 | index.html 130 | favicon.ico 131 | src/ 132 | App.css 133 | App.js 134 | App.test.js 135 | index.css 136 | index.js 137 | logo.svg 138 | ``` 139 | 140 | For the project to build, **these files must exist with exact filenames**: 141 | 142 | * `public/index.html` is the page template; 143 | * `src/index.js` is the JavaScript entry point. 144 | 145 | You can delete or rename the other files. 146 | 147 | You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> 148 | You need to **put any JS and CSS files inside `src`**, otherwise Webpack won’t see them. 149 | 150 | Only files inside `public` can be used from `public/index.html`.<br> 151 | Read instructions below for using assets from JavaScript and HTML. 152 | 153 | You can, however, create more top-level directories.<br> 154 | They will not be included in the production build so you can use them for things like documentation. 155 | 156 | ## Available Scripts 157 | 158 | In the project directory, you can run: 159 | 160 | ### `npm start` 161 | 162 | Runs the app in the development mode.<br> 163 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 164 | 165 | The page will reload if you make edits.<br> 166 | You will also see any lint errors in the console. 167 | 168 | ### `npm test` 169 | 170 | Launches the test runner in the interactive watch mode.<br> 171 | See the section about [running tests](#running-tests) for more information. 172 | 173 | ### `npm run build` 174 | 175 | Builds the app for production to the `build` folder.<br> 176 | It correctly bundles React in production mode and optimizes the build for the best performance. 177 | 178 | The build is minified and the filenames include the hashes.<br> 179 | Your app is ready to be deployed! 180 | 181 | See the section about [deployment](#deployment) for more information. 182 | 183 | ### `npm run eject` 184 | 185 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 186 | 187 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 188 | 189 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 190 | 191 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 192 | 193 | ## Supported Language Features and Polyfills 194 | 195 | This project supports a superset of the latest JavaScript standard.<br> 196 | In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: 197 | 198 | * [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). 199 | * [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). 200 | * [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). 201 | * [Dynamic import()](https://github.com/tc39/proposal-dynamic-import) (stage 3 proposal) 202 | * [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal). 203 | * [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. 204 | 205 | Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). 206 | 207 | While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. 208 | 209 | Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: 210 | 211 | * [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). 212 | * [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). 213 | * [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). 214 | 215 | If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. 216 | 217 | ## Syntax Highlighting in the Editor 218 | 219 | To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. 220 | 221 | ## Displaying Lint Output in the Editor 222 | 223 | >Note: this feature is available with `react-scripts@0.2.0` and higher.<br> 224 | >It also only works with npm 3 or higher. 225 | 226 | Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. 227 | 228 | They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. 229 | 230 | You would need to install an ESLint plugin for your editor first. Then, add a file called `.eslintrc` to the project root: 231 | 232 | ```js 233 | { 234 | "extends": "react-app" 235 | } 236 | ``` 237 | 238 | Now your editor should report the linting warnings. 239 | 240 | Note that even if you edit your `.eslintrc` file further, these changes will **only affect the editor integration**. They won’t affect the terminal and in-browser lint output. This is because Create React App intentionally provides a minimal set of rules that find common mistakes. 241 | 242 | If you want to enforce a coding style for your project, consider using [Prettier](https://github.com/jlongster/prettier) instead of ESLint style rules. 243 | 244 | ## Debugging in the Editor 245 | 246 | **This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) and [WebStorm](https://www.jetbrains.com/webstorm/).** 247 | 248 | Visual Studio Code and WebStorm support debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. 249 | 250 | ### Visual Studio Code 251 | 252 | You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. 253 | 254 | Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. 255 | 256 | ```json 257 | { 258 | "version": "0.2.0", 259 | "configurations": [{ 260 | "name": "Chrome", 261 | "type": "chrome", 262 | "request": "launch", 263 | "url": "http://localhost:3000", 264 | "webRoot": "${workspaceRoot}/src", 265 | "userDataDir": "${workspaceRoot}/.vscode/chrome", 266 | "sourceMapPathOverrides": { 267 | "webpack:///src/*": "${webRoot}/*" 268 | } 269 | }] 270 | } 271 | ``` 272 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 273 | 274 | 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. 275 | 276 | ### WebStorm 277 | 278 | 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. 279 | 280 | 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. 281 | 282 | >Note: the URL may be different if you've made adjustments via the [HOST or PORT environment variables](#advanced-configuration). 283 | 284 | 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. 285 | 286 | The same way you can debug your application in IntelliJ IDEA Ultimate, PhpStorm, PyCharm Pro, and RubyMine. 287 | 288 | ## Formatting Code Automatically 289 | 290 | 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/). 291 | 292 | To format our code whenever we make a commit in git, we need to install the following dependencies: 293 | 294 | ```sh 295 | npm install --save husky lint-staged prettier 296 | ``` 297 | 298 | Alternatively you may use `yarn`: 299 | 300 | ```sh 301 | yarn add husky lint-staged prettier 302 | ``` 303 | 304 | * `husky` makes it easy to use githooks as if they are npm scripts. 305 | * `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). 306 | * `prettier` is the JavaScript formatter we will run before commits. 307 | 308 | Now we can make sure every file is formatted correctly by adding a few lines to the `package.json` in the project root. 309 | 310 | Add the following line to `scripts` section: 311 | 312 | ```diff 313 | "scripts": { 314 | + "precommit": "lint-staged", 315 | "start": "react-scripts start", 316 | "build": "react-scripts build", 317 | ``` 318 | 319 | Next we add a 'lint-staged' field to the `package.json`, for example: 320 | 321 | ```diff 322 | "dependencies": { 323 | // ... 324 | }, 325 | + "lint-staged": { 326 | + "src/**/*.{js,jsx,json,css}": [ 327 | + "prettier --single-quote --write", 328 | + "git add" 329 | + ] 330 | + }, 331 | "scripts": { 332 | ``` 333 | 334 | Now, whenever you make a commit, Prettier will format the changed files automatically. You can also run `./node_modules/.bin/prettier --single-quote --write "src/**/*.{js,jsx}"` to format your entire project for the first time. 335 | 336 | Next you might want to integrate Prettier in your favorite editor. Read the section on [Editor Integration](https://github.com/prettier/prettier#editor-integration) on the Prettier GitHub page. 337 | 338 | ## Changing the Page `<title>` 339 | 340 | You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. 341 | 342 | 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. 343 | 344 | 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. 345 | 346 | 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). 347 | 348 | ## Installing a Dependency 349 | 350 | 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`: 351 | 352 | ```sh 353 | npm install --save react-router 354 | ``` 355 | 356 | Alternatively you may use `yarn`: 357 | 358 | ```sh 359 | yarn add react-router 360 | ``` 361 | 362 | This works for any library, not just `react-router`. 363 | 364 | ## Importing a Component 365 | 366 | This project setup supports ES6 modules thanks to Babel.<br> 367 | 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. 368 | 369 | For example: 370 | 371 | ### `Button.js` 372 | 373 | ```js 374 | import React, { Component } from 'react'; 375 | 376 | class Button extends Component { 377 | render() { 378 | // ... 379 | } 380 | } 381 | 382 | export default Button; // Don’t forget to use export default! 383 | ``` 384 | 385 | ### `DangerButton.js` 386 | 387 | 388 | ```js 389 | import React, { Component } from 'react'; 390 | import Button from './Button'; // Import a component from another file 391 | 392 | class DangerButton extends Component { 393 | render() { 394 | return <Button color="red" />; 395 | } 396 | } 397 | 398 | export default DangerButton; 399 | ``` 400 | 401 | 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. 402 | 403 | 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'`. 404 | 405 | 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. 406 | 407 | Learn more about ES6 modules: 408 | 409 | * [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) 410 | * [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) 411 | * [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) 412 | 413 | ## Code Splitting 414 | 415 | 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. 416 | 417 | 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. 418 | 419 | Here is an example: 420 | 421 | ### `moduleA.js` 422 | 423 | ```js 424 | const moduleA = 'Hello'; 425 | 426 | export { moduleA }; 427 | ``` 428 | ### `App.js` 429 | 430 | ```js 431 | import React, { Component } from 'react'; 432 | 433 | class App extends Component { 434 | handleClick = () => { 435 | import('./moduleA') 436 | .then(({ moduleA }) => { 437 | // Use moduleA 438 | }) 439 | .catch(err => { 440 | // Handle failure 441 | }); 442 | }; 443 | 444 | render() { 445 | return ( 446 | <div> 447 | <button onClick={this.handleClick}>Load</button> 448 | </div> 449 | ); 450 | } 451 | } 452 | 453 | export default App; 454 | ``` 455 | 456 | This will make `moduleA.js` and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. 457 | 458 | You can also use it with `async` / `await` syntax if you prefer it. 459 | 460 | ### With React Router 461 | 462 | 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). 463 | 464 | ## Adding a Stylesheet 465 | 466 | 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**: 467 | 468 | ### `Button.css` 469 | 470 | ```css 471 | .Button { 472 | padding: 20px; 473 | } 474 | ``` 475 | 476 | ### `Button.js` 477 | 478 | ```js 479 | import React, { Component } from 'react'; 480 | import './Button.css'; // Tell Webpack that Button.js uses these styles 481 | 482 | class Button extends Component { 483 | render() { 484 | // You can use them as regular CSS styles 485 | return <div className="Button" />; 486 | } 487 | } 488 | ``` 489 | 490 | **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. 491 | 492 | 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. 493 | 494 | 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. 495 | 496 | ## Post-Processing CSS 497 | 498 | 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. 499 | 500 | For example, this: 501 | 502 | ```css 503 | .App { 504 | display: flex; 505 | flex-direction: row; 506 | align-items: center; 507 | } 508 | ``` 509 | 510 | becomes this: 511 | 512 | ```css 513 | .App { 514 | display: -webkit-box; 515 | display: -ms-flexbox; 516 | display: flex; 517 | -webkit-box-orient: horizontal; 518 | -webkit-box-direction: normal; 519 | -ms-flex-direction: row; 520 | flex-direction: row; 521 | -webkit-box-align: center; 522 | -ms-flex-align: center; 523 | align-items: center; 524 | } 525 | ``` 526 | 527 | If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). 528 | 529 | ## Adding a CSS Preprocessor (Sass, Less etc.) 530 | 531 | 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 `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). 532 | 533 | Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. 534 | 535 | First, let’s install the command-line interface for Sass: 536 | 537 | ```sh 538 | npm install --save node-sass-chokidar 539 | ``` 540 | 541 | Alternatively you may use `yarn`: 542 | 543 | ```sh 544 | yarn add node-sass-chokidar 545 | ``` 546 | 547 | Then in `package.json`, add the following lines to `scripts`: 548 | 549 | ```diff 550 | "scripts": { 551 | + "build-css": "node-sass-chokidar src/ -o src/", 552 | + "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 553 | "start": "react-scripts start", 554 | "build": "react-scripts build", 555 | "test": "react-scripts test --env=jsdom", 556 | ``` 557 | 558 | >Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. 559 | 560 | Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. 561 | 562 | To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. 563 | 564 | To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. 565 | 566 | ``` 567 | "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", 568 | "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", 569 | ``` 570 | 571 | This will allow you to do imports like 572 | 573 | ```scss 574 | @import 'styles/_colors.scss'; // assuming a styles directory under src/ 575 | @import 'nprogress/nprogress'; // importing a css file from the nprogress node module 576 | ``` 577 | 578 | At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. 579 | 580 | As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: 581 | 582 | ```sh 583 | npm install --save npm-run-all 584 | ``` 585 | 586 | Alternatively you may use `yarn`: 587 | 588 | ```sh 589 | yarn add npm-run-all 590 | ``` 591 | 592 | Then we can change `start` and `build` scripts to include the CSS preprocessor commands: 593 | 594 | ```diff 595 | "scripts": { 596 | "build-css": "node-sass-chokidar src/ -o src/", 597 | "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", 598 | - "start": "react-scripts-ts start", 599 | - "build": "react-scripts-ts build", 600 | + "start-js": "react-scripts-ts start", 601 | + "start": "npm-run-all -p watch-css start-js", 602 | + "build": "npm run build-css && react-scripts-ts build", 603 | "test": "react-scripts test --env=jsdom", 604 | "eject": "react-scripts eject" 605 | } 606 | ``` 607 | 608 | Now running `npm start` and `npm run build` also builds Sass files. 609 | 610 | **Why `node-sass-chokidar`?** 611 | 612 | `node-sass` has been reported as having the following issues: 613 | 614 | - `node-sass --watch` has been reported to have *performance issues* in certain conditions when used in a virtual machine or with docker. 615 | 616 | - Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939) 617 | 618 | - `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891) 619 | 620 | `node-sass-chokidar` is used here as it addresses these issues. 621 | 622 | ## Adding Images, Fonts, and Files 623 | 624 | With Webpack, using static assets like images and fonts works similarly to CSS. 625 | 626 | You can **`import` a file right in a TypeScript module**. This tells Webpack to include that file in the bundle. Unlike CSS imports, importing a file gives you a string value. This value is the final path you can reference in your code, e.g. as the `src` attribute of an image or the `href` of a link to a PDF. 627 | 628 | To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a [data URI](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png. SVG files are excluded due to [#1153](https://github.com/facebookincubator/create-react-app/issues/1153). 629 | 630 | Before getting started, you must define each type of asset as a valid module format. Otherwise, the TypeScript compiler will generate an error like this: 631 | 632 | >Cannot find module './logo.png'. 633 | 634 | To import asset files in TypeScript, create a new type definition file in your project, and name it something like `assets.d.ts`. Then, add a line for each type of asset that you need to import: 635 | 636 | ```ts 637 | declare module "*.gif"; 638 | declare module "*.jpg"; 639 | declare module "*.jpeg"; 640 | declare module "*.png"; 641 | declare module "*.svg"; 642 | ``` 643 | (you'll have to restart the compiler in order the changes to take place) 644 | 645 | In this case, we've added several image file extensions as valid module formats. 646 | 647 | Now that the compiler is configured, here is an example of importing an image file: 648 | 649 | ```js 650 | import React from 'react'; 651 | import logo from './logo.svg'; // Tell Webpack this JS file uses this image 652 | 653 | console.log(logo); // /logo.84287d09.png 654 | 655 | function Header() { 656 | // Import result is the URL of your image 657 | return <img src={logo} alt="Logo" />; 658 | } 659 | 660 | export default Header; 661 | ``` 662 | 663 | This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. 664 | 665 | This works in CSS too: 666 | 667 | ```css 668 | .Logo { 669 | background-image: url(./logo.png); 670 | } 671 | ``` 672 | 673 | Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. 674 | 675 | Please be advised that this is also a custom feature of Webpack. 676 | 677 | **It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> 678 | An alternative way of handling static assets is described in the next section. 679 | 680 | ## Using the `public` Folder 681 | 682 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 683 | 684 | ### Changing the HTML 685 | 686 | The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). 687 | The `<script>` tag with the compiled code will be added to it automatically during the build process. 688 | 689 | ### Adding Assets Outside of the Module System 690 | 691 | You can also add other assets to the `public` folder. 692 | 693 | Note that we normally encourage you to `import` assets in JavaScript files instead. 694 | For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). 695 | This mechanism provides a number of benefits: 696 | 697 | * Scripts and stylesheets get minified and bundled together to avoid extra network requests. 698 | * Missing files cause compilation errors instead of 404 errors for your users. 699 | * Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. 700 | 701 | However there is an **escape hatch** that you can use to add an asset outside of the module system. 702 | 703 | If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. 704 | 705 | Inside `index.html`, you can use it like this: 706 | 707 | ```html 708 | <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> 709 | ``` 710 | 711 | Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. 712 | 713 | When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. 714 | 715 | In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: 716 | 717 | ```js 718 | render() { 719 | // Note: this is an escape hatch and should be used sparingly! 720 | // Normally we recommend using `import` for getting asset URLs 721 | // as described in “Adding Images and Fonts” above this section. 722 | return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; 723 | } 724 | ``` 725 | 726 | Keep in mind the downsides of this approach: 727 | 728 | * None of the files in `public` folder get post-processed or minified. 729 | * Missing files will not be called at compilation time, and will cause 404 errors for your users. 730 | * Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. 731 | 732 | ### When to Use the `public` Folder 733 | 734 | Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. 735 | The `public` folder is useful as a workaround for a number of less common cases: 736 | 737 | * You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). 738 | * You have thousands of images and need to dynamically reference their paths. 739 | * You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. 740 | * Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. 741 | 742 | Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. 743 | 744 | ## Using Global Variables 745 | 746 | When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. 747 | 748 | You can avoid this by reading the global variable explicitly from the `window` object, for example: 749 | 750 | ```js 751 | const $ = window.$; 752 | ``` 753 | 754 | This makes it obvious you are using a global variable intentionally rather than because of a typo. 755 | 756 | Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. 757 | 758 | ## Adding Bootstrap 759 | 760 | You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: 761 | 762 | Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: 763 | 764 | ```sh 765 | npm install --save react-bootstrap bootstrap@3 766 | ``` 767 | 768 | Alternatively you may use `yarn`: 769 | 770 | ```sh 771 | yarn add react-bootstrap bootstrap@3 772 | ``` 773 | 774 | Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: 775 | 776 | ```js 777 | import 'bootstrap/dist/css/bootstrap.css'; 778 | import 'bootstrap/dist/css/bootstrap-theme.css'; 779 | // Put any other imports below so that CSS from your 780 | // components takes precedence over default styles. 781 | ``` 782 | 783 | Import required React Bootstrap components within ```src/App.js``` file or your custom component files: 784 | 785 | ```js 786 | import { Navbar, Jumbotron, Button } from 'react-bootstrap'; 787 | ``` 788 | 789 | Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. 790 | 791 | ### Using a Custom Theme 792 | 793 | Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> 794 | We suggest the following approach: 795 | 796 | * Create a new package that depends on the package you wish to customize, e.g. Bootstrap. 797 | * Add the necessary build steps to tweak the theme, and publish your package on npm. 798 | * Install your own theme npm package as a dependency of your app. 799 | 800 | Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. 801 | 802 | ## Adding Flow 803 | 804 | Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. 805 | 806 | Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. 807 | 808 | To add Flow to a Create React App project, follow these steps: 809 | 810 | 1. Run `npm install --save flow-bin` (or `yarn add flow-bin`). 811 | 2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. 812 | 3. Run `npm run flow init` (or `yarn flow init`) to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. 813 | 4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). 814 | 815 | Now you can run `npm run flow` (or `yarn flow`) to check the files for type errors. 816 | You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. 817 | In the future we plan to integrate it into Create React App even more closely. 818 | 819 | To learn more about Flow, check out [its documentation](https://flowtype.org/). 820 | 821 | ## Adding Custom Environment Variables 822 | 823 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 824 | 825 | Your project can consume variables declared in your environment as if they were declared locally in your JS files. By 826 | default you will have `NODE_ENV` defined for you, and any other environment variables starting with 827 | `REACT_APP_`. 828 | 829 | **The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. 830 | 831 | >Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. 832 | 833 | These environment variables will be defined for you on `process.env`. For example, having an environment 834 | variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. 835 | 836 | There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. 837 | 838 | These environment variables can be useful for displaying information conditionally based on where the project is 839 | deployed or consuming sensitive data that lives outside of version control. 840 | 841 | First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined 842 | in the environment inside a `<form>`: 843 | 844 | ```jsx 845 | render() { 846 | return ( 847 | <div> 848 | <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> 849 | <form> 850 | <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> 851 | </form> 852 | </div> 853 | ); 854 | } 855 | ``` 856 | 857 | During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. 858 | 859 | When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: 860 | 861 | ```html 862 | <div> 863 | <small>You are running this application in <b>development</b> mode.</small> 864 | <form> 865 | <input type="hidden" value="abcdef" /> 866 | </form> 867 | </div> 868 | ``` 869 | 870 | The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this 871 | value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in 872 | a `.env` file. Both of these ways are described in the next few sections. 873 | 874 | Having access to the `NODE_ENV` is also useful for performing actions conditionally: 875 | 876 | ```js 877 | if (process.env.NODE_ENV !== 'production') { 878 | analytics.disable(); 879 | } 880 | ``` 881 | 882 | When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. 883 | 884 | ### Referencing Environment Variables in the HTML 885 | 886 | >Note: this feature is available with `react-scripts@0.9.0` and higher. 887 | 888 | You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: 889 | 890 | ```html 891 | <title>%REACT_APP_WEBSITE_NAME% 892 | ``` 893 | 894 | Note that the caveats from the above section apply: 895 | 896 | * Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. 897 | * The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). 898 | 899 | ### Adding Temporary Environment Variables In Your Shell 900 | 901 | Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the 902 | life of the shell session. 903 | 904 | #### Windows (cmd.exe) 905 | 906 | ```cmd 907 | set REACT_APP_SECRET_CODE=abcdef&&npm start 908 | ``` 909 | 910 | (Note: the lack of whitespace is intentional.) 911 | 912 | #### Linux, macOS (Bash) 913 | 914 | ```bash 915 | REACT_APP_SECRET_CODE=abcdef npm start 916 | ``` 917 | 918 | ### Adding Development Environment Variables In `.env` 919 | 920 | >Note: this feature is available with `react-scripts@0.5.0` and higher. 921 | 922 | To define permanent environment variables, create a file called `.env` in the root of your project: 923 | 924 | ``` 925 | REACT_APP_SECRET_CODE=abcdef 926 | ``` 927 | 928 | `.env` files **should be** checked into source control (with the exclusion of `.env*.local`). 929 | 930 | #### What other `.env` files are can be used? 931 | 932 | >Note: this feature is **available with `react-scripts@1.0.0` and higher**. 933 | 934 | * `.env`: Default. 935 | * `.env.local`: Local overrides. **This file is loaded for all environments except test.** 936 | * `.env.development`, `.env.test`, `.env.production`: Environment-specific settings. 937 | * `.env.development.local`, `.env.test.local`, `.env.production.local`: Local overrides of environment-specific settings. 938 | 939 | Files on the left have more priority than files on the right: 940 | 941 | * `npm start`: `.env.development.local`, `.env.development`, `.env.local`, `.env` 942 | * `npm run build`: `.env.production.local`, `.env.production`, `.env.local`, `.env` 943 | * `npm test`: `.env.test.local`, `.env.test`, `.env` (note `.env.local` is missing) 944 | 945 | These variables will act as the defaults if the machine does not explicitly set them.
946 | Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. 947 | 948 | >Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need 949 | these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). 950 | 951 | ## Can I Use Decorators? 952 | 953 | Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
954 | Create React App doesn’t support decorator syntax at the moment because: 955 | 956 | * It is an experimental proposal and is subject to change. 957 | * The current specification version is not officially supported by Babel. 958 | * If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. 959 | 960 | However in many cases you can rewrite decorator-based code without decorators just as fine.
961 | Please refer to these two threads for reference: 962 | 963 | * [#214](https://github.com/facebookincubator/create-react-app/issues/214) 964 | * [#411](https://github.com/facebookincubator/create-react-app/issues/411) 965 | 966 | Create React App will add decorator support when the specification advances to a stable stage. 967 | 968 | ## Integrating with an API Backend 969 | 970 | These tutorials will help you to integrate your app with an API backend running on another port, 971 | using `fetch()` to access it. 972 | 973 | ### Node 974 | Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). 975 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). 976 | 977 | ### Ruby on Rails 978 | 979 | Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). 980 | You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). 981 | 982 | ## Proxying API Requests in Development 983 | 984 | >Note: this feature is available with `react-scripts@0.2.3` and higher. 985 | 986 | People often serve the front-end React app from the same host and port as their backend implementation.
987 | For example, a production setup might look like this after the app is deployed: 988 | 989 | ``` 990 | / - static server returns index.html with React app 991 | /todos - static server returns index.html with React app 992 | /api/todos - server handles any /api/* requests using the backend implementation 993 | ``` 994 | 995 | Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. 996 | 997 | To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: 998 | 999 | ```js 1000 | "proxy": "http://localhost:4000", 1001 | ``` 1002 | 1003 | This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. 1004 | 1005 | Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: 1006 | 1007 | ``` 1008 | Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 1009 | ``` 1010 | 1011 | Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. 1012 | 1013 | The `proxy` option supports HTTP, HTTPS and WebSocket connections.
1014 | If the `proxy` option is **not** flexible enough for you, alternatively you can: 1015 | 1016 | * [Configure the proxy yourself](#configuring-the-proxy-manually) 1017 | * Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). 1018 | * Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. 1019 | 1020 | ### "Invalid Host Header" Errors After Configuring Proxy 1021 | 1022 | When you enable the `proxy` option, you opt into a more strict set of host checks. This is necessary because leaving the backend open to remote hosts makes your computer vulnerable to DNS rebinding attacks. The issue is explained in [this article](https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a) and [this issue](https://github.com/webpack/webpack-dev-server/issues/887). 1023 | 1024 | This shouldn’t affect you when developing on `localhost`, but if you develop remotely like [described here](https://github.com/facebookincubator/create-react-app/issues/2271), you will see this error in the browser after enabling the `proxy` option: 1025 | 1026 | >Invalid Host header 1027 | 1028 | To work around it, you can specify your public development host in a file called `.env.development` in the root of your project: 1029 | 1030 | ``` 1031 | HOST=mypublicdevhost.com 1032 | ``` 1033 | 1034 | If you restart the development server now and load the app from the specified host, it should work. 1035 | 1036 | If you are still having issues or if you’re using a more exotic environment like a cloud editor, you can bypass the host check completely by adding a line to `.env.development.local`. **Note that this is dangerous and exposes your machine to remote code execution from malicious websites:** 1037 | 1038 | ``` 1039 | # NOTE: THIS IS DANGEROUS! 1040 | # It exposes your machine to attacks from the websites you visit. 1041 | DANGEROUSLY_DISABLE_HOST_CHECK=true 1042 | ``` 1043 | 1044 | We don’t recommend this approach. 1045 | 1046 | ### Configuring the Proxy Manually 1047 | 1048 | >Note: this feature is available with `react-scripts@1.0.0` and higher. 1049 | 1050 | If the `proxy` option is **not** flexible enough for you, you can specify an object in the following form (in `package.json`).
1051 | You may also specify any configuration value [`http-proxy-middleware`](https://github.com/chimurai/http-proxy-middleware#options) or [`http-proxy`](https://github.com/nodejitsu/node-http-proxy#options) supports. 1052 | ```js 1053 | { 1054 | // ... 1055 | "proxy": { 1056 | "/api": { 1057 | "target": "", 1058 | "ws": true 1059 | // ... 1060 | } 1061 | } 1062 | // ... 1063 | } 1064 | ``` 1065 | 1066 | All requests matching this path will be proxies, no exceptions. This includes requests for `text/html`, which the standard `proxy` option does not proxy. 1067 | 1068 | If you need to specify multiple proxies, you may do so by specifying additional entries. 1069 | You may also narrow down matches using `*` and/or `**`, to match the path exactly or any subpath. 1070 | ```js 1071 | { 1072 | // ... 1073 | "proxy": { 1074 | // Matches any request starting with /api 1075 | "/api": { 1076 | "target": "", 1077 | "ws": true 1078 | // ... 1079 | }, 1080 | // Matches any request starting with /foo 1081 | "/foo": { 1082 | "target": "", 1083 | "ssl": true, 1084 | "pathRewrite": { 1085 | "^/foo": "/foo/beta" 1086 | } 1087 | // ... 1088 | }, 1089 | // Matches /bar/abc.html but not /bar/sub/def.html 1090 | "/bar/*.html": { 1091 | "target": "", 1092 | // ... 1093 | }, 1094 | // Matches /baz/abc.html and /baz/sub/def.html 1095 | "/baz/**/*.html": { 1096 | "target": "" 1097 | // ... 1098 | } 1099 | } 1100 | // ... 1101 | } 1102 | ``` 1103 | 1104 | ### Configuring a WebSocket Proxy 1105 | 1106 | When setting up a WebSocket proxy, there are a some extra considerations to be aware of. 1107 | 1108 | If you’re using a WebSocket engine like [Socket.io](https://socket.io/), you must have a Socket.io server running that you can use as the proxy target. Socket.io will not work with a standard WebSocket server. Specifically, don't expect Socket.io to work with [the websocket.org echo test](http://websocket.org/echo.html). 1109 | 1110 | There’s some good documentation available for [setting up a Socket.io server](https://socket.io/docs/). 1111 | 1112 | Standard WebSockets **will** work with a standard WebSocket server as well as the websocket.org echo test. You can use libraries like [ws](https://github.com/websockets/ws) for the server, with [native WebSockets in the browser](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket). 1113 | 1114 | Either way, you can proxy WebSocket requests manually in `package.json`: 1115 | 1116 | ```js 1117 | { 1118 | // ... 1119 | "proxy": { 1120 | "/socket": { 1121 | // Your compatible WebSocket server 1122 | "target": "ws://", 1123 | // Tell http-proxy-middleware that this is a WebSocket proxy. 1124 | // Also allows you to proxy WebSocket requests without an additional HTTP request 1125 | // https://github.com/chimurai/http-proxy-middleware#external-websocket-upgrade 1126 | "ws": true 1127 | // ... 1128 | } 1129 | } 1130 | // ... 1131 | } 1132 | ``` 1133 | 1134 | ## Using HTTPS in Development 1135 | 1136 | >Note: this feature is available with `react-scripts@0.4.0` and higher. 1137 | 1138 | You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. 1139 | 1140 | To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: 1141 | 1142 | #### Windows (cmd.exe) 1143 | 1144 | ```cmd 1145 | set HTTPS=true&&npm start 1146 | ``` 1147 | 1148 | (Note: the lack of whitespace is intentional.) 1149 | 1150 | #### Linux, macOS (Bash) 1151 | 1152 | ```bash 1153 | HTTPS=true npm start 1154 | ``` 1155 | 1156 | Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. 1157 | 1158 | ## Generating Dynamic `` Tags on the Server 1159 | 1160 | Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: 1161 | 1162 | ```html 1163 | 1164 | 1165 | 1166 | 1167 | 1168 | ``` 1169 | 1170 | Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, 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! 1171 | 1172 | If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. 1173 | 1174 | ## Pre-Rendering into Static HTML Files 1175 | 1176 | If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. 1177 | 1178 | There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. 1179 | 1180 | The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. 1181 | 1182 | You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). 1183 | 1184 | ## Injecting Data from the Server into the Page 1185 | 1186 | Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: 1187 | 1188 | ```js 1189 | 1190 | 1191 | 1192 | 1195 | ``` 1196 | 1197 | Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** 1198 | 1199 | ## Running Tests 1200 | 1201 | >Note: this feature is available with `react-scripts@0.3.0` and higher.
1202 | >[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) 1203 | 1204 | Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. 1205 | 1206 | Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. 1207 | 1208 | While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. 1209 | 1210 | We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. 1211 | 1212 | ### Filename Conventions 1213 | 1214 | Jest will look for test files with any of the following popular naming conventions: 1215 | 1216 | * Files with `.js` suffix in `__tests__` folders. 1217 | * Files with `.test.js` suffix. 1218 | * Files with `.spec.js` suffix. 1219 | 1220 | The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. 1221 | 1222 | We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. 1223 | 1224 | ### Command Line Interface 1225 | 1226 | When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. 1227 | 1228 | The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: 1229 | 1230 | ![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) 1231 | 1232 | ### Version Control Integration 1233 | 1234 | By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests run fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. 1235 | 1236 | Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. 1237 | 1238 | Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. 1239 | 1240 | ### Writing Tests 1241 | 1242 | To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. 1243 | 1244 | Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: 1245 | 1246 | ```js 1247 | import sum from './sum'; 1248 | 1249 | it('sums numbers', () => { 1250 | expect(sum(1, 2)).toEqual(3); 1251 | expect(sum(2, 2)).toEqual(4); 1252 | }); 1253 | ``` 1254 | 1255 | All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
1256 | You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. 1257 | 1258 | ### Testing Components 1259 | 1260 | There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. 1261 | 1262 | Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: 1263 | 1264 | ```ts 1265 | import * as React from 'react'; 1266 | import * as ReactDOM from 'react-dom'; 1267 | import App from './App'; 1268 | 1269 | it('renders without crashing', () => { 1270 | const div = document.createElement('div'); 1271 | ReactDOM.render(, div); 1272 | }); 1273 | ``` 1274 | 1275 | This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.tsx`. 1276 | 1277 | 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. 1278 | 1279 | If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). To install it, run: 1280 | 1281 | ```sh 1282 | npm install --save-dev enzyme @types/enzyme enzyme-adapter-react-16 @types/enzyme-adapter-react-16 react-test-renderer @types/react-test-renderer 1283 | ``` 1284 | 1285 | Alternatively you may use `yarn`: 1286 | 1287 | ```sh 1288 | yarn add --dev enzyme @types/enzyme enzyme-adapter-react-16 @types/enzyme-adapter-react-16 react-test-renderer @types/react-test-renderer 1289 | ``` 1290 | 1291 | #### `src/setupTests.ts` 1292 | ```ts 1293 | import * as Enzyme from 'enzyme'; 1294 | import * as Adapter from 'enzyme-adapter-react-16'; 1295 | 1296 | Enzyme.configure({ adapter: new Adapter() }); 1297 | ``` 1298 | 1299 | You can write a smoke test with it too: 1300 | 1301 | ```ts 1302 | import * as React from 'react'; 1303 | import { shallow } from 'enzyme'; 1304 | import App from './App'; 1305 | 1306 | it('renders without crashing', () => { 1307 | shallow(); 1308 | }); 1309 | ``` 1310 | 1311 | Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a `