├── src ├── App │ ├── App.css │ ├── index.js │ ├── App.test.js │ └── App.js ├── Todo │ ├── index.js │ ├── Todo.css │ ├── Todo.module.scss │ ├── __snapshots__ │ │ └── Todo.test.js.snap │ ├── Todo.test.js │ └── Todo.js ├── Divider │ ├── index.js │ ├── Divider.scss │ └── Divider.js ├── NewTodo │ ├── index.js │ ├── NewTodo.css │ ├── __snapshots__ │ │ └── NewTodo.test.js.snap │ ├── NewTodo.js │ └── NewTodo.test.js ├── TodoList │ ├── index.js │ ├── TodoList.css │ ├── __snapshots__ │ │ └── TodoList.test.js.snap │ ├── TodoList.test.js │ └── TodoList.js ├── setupTests.js ├── shared.scss ├── index.css ├── index.js ├── TodoService.js ├── logo.svg └── serviceWorker.js ├── public ├── favicon.ico ├── manifest.json └── index.html ├── .gitignore ├── package.json ├── server.js └── README.md /src/App/App.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/App/index.js: -------------------------------------------------------------------------------- 1 | import App from "./App"; 2 | export default App; 3 | -------------------------------------------------------------------------------- /src/Todo/index.js: -------------------------------------------------------------------------------- 1 | import Todo from "./Todo"; 2 | export default Todo; 3 | -------------------------------------------------------------------------------- /src/Divider/index.js: -------------------------------------------------------------------------------- 1 | import Divider from "./Divider"; 2 | export default Divider; 3 | -------------------------------------------------------------------------------- /src/NewTodo/index.js: -------------------------------------------------------------------------------- 1 | import NewTodo from "./NewTodo"; 2 | export default NewTodo; 3 | -------------------------------------------------------------------------------- /src/TodoList/index.js: -------------------------------------------------------------------------------- 1 | import TodoList from "./TodoList"; 2 | export default TodoList; 3 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/parussimov/Create-React-App-2-Quick-Start-Guide/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /src/Divider/Divider.scss: -------------------------------------------------------------------------------- 1 | @import "../shared"; 2 | 3 | hr { 4 | border: 0; 5 | height: 1px; 6 | background-image: $fancy-gradient; 7 | } 8 | -------------------------------------------------------------------------------- /src/TodoList/TodoList.css: -------------------------------------------------------------------------------- 1 | .TodoList { 2 | margin: 20px; 3 | padding: 20px; 4 | border: 2px solid #00d8ff; 5 | background: #ddeeff; 6 | } 7 | -------------------------------------------------------------------------------- /src/NewTodo/NewTodo.css: -------------------------------------------------------------------------------- 1 | .NewTodo { 2 | margin: 20px; 3 | padding: 20px; 4 | border: 2px solid #00ffd8; 5 | background: #ddffee; 6 | text-align: center; 7 | } 8 | -------------------------------------------------------------------------------- /src/setupTests.js: -------------------------------------------------------------------------------- 1 | // setup file 2 | import { configure } from "enzyme"; 3 | import Adapter from "enzyme-adapter-react-16"; 4 | 5 | configure({ adapter: new Adapter() }); 6 | -------------------------------------------------------------------------------- /src/Todo/Todo.css: -------------------------------------------------------------------------------- 1 | .Todo { 2 | border: 2px solid black; 3 | text-align: center; 4 | background: #f5f5f5; 5 | color: #333; 6 | margin: 20px; 7 | padding: 20px; 8 | } 9 | 10 | .Done { 11 | background: #f58888; 12 | } 13 | -------------------------------------------------------------------------------- /src/shared.scss: -------------------------------------------------------------------------------- 1 | $todo-critical: #f5a5a5; 2 | $todo-normal: #a5a5f5; 3 | $todo-complete: #a5f5a5; 4 | $fancy-gradient: linear-gradient( 5 | to right, 6 | rgba(0, 0, 0, 0), 7 | rgba(0, 0, 0, 0.8), 8 | rgba(0, 0, 0, 0) 9 | ); 10 | -------------------------------------------------------------------------------- /src/Divider/Divider.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import "./Divider.scss"; 3 | 4 | function Divider() { 5 | return React.createElement( 6 | "div", 7 | { className: "Divider" }, 8 | React.createElement("hr") 9 | ); 10 | } 11 | 12 | export default Divider; 13 | -------------------------------------------------------------------------------- /src/App/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "Todos", 3 | "name": "Best Todoifier", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": "/", 12 | "display": "standalone", 13 | "theme_color": "#343a40", 14 | "background_color": "#a5a5f5" 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/Todo/Todo.module.scss: -------------------------------------------------------------------------------- 1 | @import "../shared"; 2 | 3 | .todo { 4 | border: 2px solid black; 5 | text-align: center; 6 | background: $todo-normal; 7 | color: #333; 8 | margin: 20px; 9 | padding: 20px; 10 | } 11 | 12 | .done { 13 | background: $todo-complete; 14 | } 15 | 16 | .hr { 17 | border: 2px solid red; 18 | } 19 | 20 | .critical { 21 | composes: todo; 22 | background: $todo-critical; 23 | } 24 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 6 | sans-serif; 7 | -webkit-font-smoothing: antialiased; 8 | -moz-osx-font-smoothing: grayscale; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 13 | monospace; 14 | } 15 | 16 | /* dev */ -------------------------------------------------------------------------------- /src/App/App.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { Navbar, NavbarBrand } from "reactstrap"; 3 | 4 | import "./App.css"; 5 | import TodoList from "../TodoList"; 6 | 7 | const headerTitle = "Todoifier"; 8 | 9 | const headerDisplay = title => ( 10 | 11 | {title} 12 | 13 | ); 14 | 15 | const App = () => ( 16 |
17 | {headerDisplay(headerTitle)} 18 |
19 | 20 |
21 | ); 22 | 23 | export default App; 24 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | 4 | import "bootstrap/dist/css/bootstrap.css"; 5 | 6 | import "./index.css"; 7 | import App from "./App"; 8 | import * as serviceWorker from "./serviceWorker"; 9 | 10 | ReactDOM.render(, document.getElementById("root")); 11 | 12 | // If you want your app to work offline and load faster, you can change 13 | // unregister() to register() below. Note this comes with some pitfalls. 14 | // Learn more about service workers: http://bit.ly/CRA-PWA 15 | serviceWorker.register(); 16 | -------------------------------------------------------------------------------- /src/NewTodo/__snapshots__/NewTodo.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`NewTodo renders and matches our snapshot 1`] = ` 4 |
7 |
10 | 17 | 25 |
26 |
27 | `; 28 | -------------------------------------------------------------------------------- /src/TodoList/__snapshots__/TodoList.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`TodoList renders and matches our snapshot 1`] = ` 4 |
7 |
10 |
13 | 20 | 28 |
29 |
30 |

31 | Still Loading... 32 |

33 |
34 | `; 35 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "todoifier", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "bootstrap": "4", 7 | "express": "^4.16.4", 8 | "node-sass": "^4.11.0", 9 | "react": "^16.8.1", 10 | "react-dom": "^16.8.1", 11 | "react-scripts": "2.1.5", 12 | "reactstrap": "6.5.0" 13 | }, 14 | "scripts": { 15 | "start": "react-scripts start", 16 | "build": "react-scripts build", 17 | "test": "react-scripts test", 18 | "eject": "react-scripts eject", 19 | "backend": "node server.js" 20 | }, 21 | "eslintConfig": { 22 | "extends": "react-app" 23 | }, 24 | "browserslist": [ 25 | ">0.2%", 26 | "not dead", 27 | "not ie <= 11", 28 | "not op_mini all" 29 | ], 30 | "devDependencies": { 31 | "enzyme": "^3.8.0", 32 | "enzyme-adapter-react-16": "^1.9.1", 33 | "react-test-renderer": "^16.8.1" 34 | }, 35 | "proxy": "http://localhost:4000" 36 | } 37 | -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | const express = require("express"); 2 | const app = express(); 3 | const port = 4000; 4 | 5 | const todos = [ 6 | { id: 1, description: "Write some code", done: false, critical: false }, 7 | { id: 2, description: "Change the world", done: false, critical: false }, 8 | { id: 3, description: "Eat a cookie", done: false, critical: false } 9 | ]; 10 | 11 | app.use(express.json()); 12 | 13 | app.get("/", (req, res) => res.json({})); 14 | 15 | app.listen(port, () => 16 | console.log(`Simulated backend listening on port ${port}!`) 17 | ); 18 | 19 | app.get("/api/todos", (req, res) => res.json({ todos: todos })); 20 | 21 | app.post("/api/todos", (req, res) => { 22 | const body = { id: todos.length + 1, ...req.body }; 23 | res.json({ todos: [...todos, body] }); 24 | }); 25 | 26 | app.delete("/api/todos/:id", (req, res) => { 27 | const todoId = parseInt(req.params.id); 28 | res.json({ todos: todos.filter(t => t.id !== todoId) }); 29 | }); 30 | -------------------------------------------------------------------------------- /src/Todo/__snapshots__/Todo.test.js.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Todo renders and matches our snapshot 1`] = ` 4 |
7 | Yo 8 |
9 |
12 |
16 | 24 | 32 | 40 |
41 |
42 | `; 43 | -------------------------------------------------------------------------------- /src/TodoService.js: -------------------------------------------------------------------------------- 1 | const fetchTodos = async () => { 2 | const res = await fetch("/api/todos", { accept: "application/json" }); 3 | const json = await res.json(); 4 | return { status: res.status, todos: json.todos }; 5 | }; 6 | 7 | const createTodo = async description => { 8 | const res = await fetch("/api/todos", { 9 | method: "POST", 10 | headers: { accept: "application/json", "content-type": "application/json" }, 11 | body: JSON.stringify({ 12 | description: description, 13 | critical: false, 14 | done: false 15 | }) 16 | }); 17 | const json = await res.json(); 18 | return { status: res.status, todos: json.todos }; 19 | }; 20 | 21 | const deleteTodo = async todoId => { 22 | const res = await fetch(`/api/todos/${todoId}`, { 23 | method: "DELETE", 24 | headers: { accept: "application/json", "content-type": "application/json" } 25 | }); 26 | const json = await res.json(); 27 | return { status: res.status, todos: json.todos }; 28 | }; 29 | 30 | export { fetchTodos, createTodo, deleteTodo }; 31 | -------------------------------------------------------------------------------- /src/NewTodo/NewTodo.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Button, Input, InputGroup } from "reactstrap"; 3 | import "./NewTodo.css"; 4 | 5 | class NewTodo extends Component { 6 | constructor(props) { 7 | super(props); 8 | this.state = { item: "" }; 9 | this.handleUpdate = this.handleUpdate.bind(this); 10 | this.addTodo = this.addTodo.bind(this); 11 | } 12 | addTodo() { 13 | this.props.addTodo(this.state.item); 14 | this.setState({ item: "" }); 15 | } 16 | handleUpdate(event) { 17 | this.setState({ item: event.target.value }); 18 | } 19 | render() { 20 | return ( 21 |
22 | 23 | 29 | 32 | 33 |
34 | ); 35 | } 36 | } 37 | 38 | export default NewTodo; 39 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 16 | 25 | React App 26 | 27 | 28 | 29 |
30 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/Todo/Todo.test.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import { shallow } from "enzyme"; 4 | import renderer from "react-test-renderer"; 5 | 6 | import Todo from "./Todo"; 7 | 8 | describe(Todo, () => { 9 | const description = "New Todo"; 10 | const mockRemoveTodo = jest.fn(); 11 | const component = shallow( 12 | 19 | ); 20 | 21 | it("renders without crashing", () => { 22 | const div = document.createElement("div"); 23 | ReactDOM.render(, div); 24 | ReactDOM.unmountComponentAtNode(div); 25 | }); 26 | 27 | it("renders and matches our snapshot", () => { 28 | const component = renderer.create(); 29 | const tree = component.toJSON(); 30 | expect(tree).toMatchSnapshot(); 31 | }); 32 | 33 | it("renders a Todo component", () => { 34 | expect(component.contains(
)); 35 | }); 36 | 37 | it("contains the description", () => { 38 | expect(component.text()).toContain(description); 39 | }); 40 | 41 | it("marks the Todo as done", () => { 42 | component.find("Button.MarkDone").simulate("click"); 43 | expect(component.state("done")).toEqual(true); 44 | }); 45 | 46 | it("calls the mock remove function", () => { 47 | component.find("Button.RemoveTodo").simulate("click"); 48 | expect(mockRemoveTodo).toHaveBeenCalled(); 49 | }); 50 | 51 | it("marks the Todo as critical", () => { 52 | expect(component.state("critical")).toEqual(false); 53 | component.find("Button.MarkCritical").simulate("click"); 54 | expect(component.state("critical")).toEqual(true); 55 | }); 56 | }); 57 | -------------------------------------------------------------------------------- /src/NewTodo/NewTodo.test.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import { shallow } from "enzyme"; 4 | import renderer from "react-test-renderer"; 5 | 6 | import NewTodo from "./NewTodo"; 7 | 8 | describe(NewTodo, () => { 9 | const mockAddTodo = jest.fn(); 10 | const component = shallow(); 11 | 12 | it("renders without crashing", () => { 13 | const div = document.createElement("div"); 14 | ReactDOM.render(, div); 15 | ReactDOM.unmountComponentAtNode(div); 16 | }); 17 | 18 | it("renders and matches our snapshot", () => { 19 | const component = renderer.create(); 20 | const tree = component.toJSON(); 21 | expect(tree).toMatchSnapshot(); 22 | }); 23 | 24 | it("renders a Todo component", () => { 25 | expect(component.contains(
)); 26 | }); 27 | 28 | it("contains the form", () => { 29 | expect(component.find("Input")).toHaveLength(1); 30 | expect(component.find("Button")).toHaveLength(1); 31 | }); 32 | 33 | it("calls the passed in addTodo function when add button is clicked", () => { 34 | component.find("Button").simulate("click"); 35 | expect(mockAddTodo).toBeCalled(); 36 | }); 37 | 38 | it("updates the form when keys are pressed", () => { 39 | const updateKey = "New Todo"; 40 | component.instance().handleUpdate({ target: { value: updateKey } }); 41 | expect(component.state("item")).toEqual(updateKey); 42 | }); 43 | 44 | it("blanks out the Todo Name when the button is clicked", () => { 45 | const updateKey = "I should be empty"; 46 | component.instance().handleUpdate({ target: { value: updateKey } }); 47 | expect(component.state("item")).toEqual(updateKey); 48 | component.find("Button").simulate("click"); 49 | expect(component.state("item")).toHaveLength(0); 50 | }); 51 | }); 52 | -------------------------------------------------------------------------------- /src/Todo/Todo.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import { Button, ButtonGroup } from "reactstrap"; 3 | import styles from "./Todo.module.scss"; 4 | 5 | class Todo extends Component { 6 | constructor(props) { 7 | super(props); 8 | this.state = { 9 | done: props.done, 10 | critical: props.critical 11 | }; 12 | 13 | this.markAsDone = this.markAsDone.bind(this); 14 | this.removeTodo = this.removeTodo.bind(this); 15 | this.markCritical = this.markCritical.bind(this); 16 | } 17 | markCritical() { 18 | this.setState({ critical: true }); 19 | } 20 | markAsDone() { 21 | this.setState({ done: true }); 22 | } 23 | removeTodo() { 24 | this.props.removeTodo(this.props.id); 25 | } 26 | cssClasses() { 27 | let classes = []; 28 | if (this.state.critical) { 29 | classes = [styles.critical]; 30 | } else { 31 | classes = [styles.todo]; 32 | } 33 | if (this.state.done) { 34 | classes = [...classes, styles.done]; 35 | } 36 | return classes.join(" "); 37 | } 38 | render() { 39 | return ( 40 |
41 | {this.props.description} 42 |
43 |
44 | 45 | 52 | 59 | 66 | 67 |
68 | ); 69 | } 70 | } 71 | 72 | export default Todo; 73 | -------------------------------------------------------------------------------- /src/TodoList/TodoList.test.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import ReactDOM from "react-dom"; 3 | import { shallow } from "enzyme"; 4 | import renderer from "react-test-renderer"; 5 | 6 | import TodoList from "./TodoList"; 7 | import NewTodo from "../NewTodo"; 8 | import Todo from "../Todo"; 9 | 10 | jest.mock("../TodoService", () => ({ 11 | fetchTodos: jest.fn().mockReturnValue({ status: 200, todos: [] }), 12 | createTodo: jest.fn().mockReturnValue({ status: 200, todos: [] }), 13 | deleteTodo: jest.fn().mockReturnValue({ status: 200, todos: [] }) 14 | })); 15 | 16 | describe(TodoList, () => { 17 | const component = shallow(); 18 | 19 | it("renders without crashing", () => { 20 | const div = document.createElement("div"); 21 | ReactDOM.render(, div); 22 | ReactDOM.unmountComponentAtNode(div); 23 | }); 24 | 25 | it("renders and matches our snapshot", () => { 26 | const component = renderer.create(); 27 | const tree = component.toJSON(); 28 | expect(tree).toMatchSnapshot(); 29 | }); 30 | 31 | it("renders a TodoList component", () => { 32 | expect(component.contains(
)); 33 | }); 34 | 35 | it("includes a NewTodo component", () => { 36 | expect(component.find(NewTodo)).toHaveLength(1); 37 | }); 38 | 39 | it("renders the correct number of Todo components", () => { 40 | const todoCount = component.state("items").length; 41 | expect(component.find(Todo)).toHaveLength(todoCount); 42 | }); 43 | 44 | it("adds another Todo when the addTodo function is called", async () => { 45 | const before = component.find(Todo).length; 46 | await component.instance().addTodo("New Item"); 47 | component.update(); 48 | const after = component.find(Todo).length; 49 | expect(after).toBeGreaterThan(before); 50 | }); 51 | 52 | it("removes a Todo from the list when the remove Todo function is called", async () => { 53 | const before = component.find(Todo).length; 54 | const removeMe = component.state("items")[0]; 55 | await component.instance().removeTodo(removeMe.id); 56 | component.update(); 57 | const after = component.find(Todo).length; 58 | expect(after).toBeLessThan(before); 59 | }); 60 | }); 61 | -------------------------------------------------------------------------------- /src/TodoList/TodoList.js: -------------------------------------------------------------------------------- 1 | import React, { Fragment, Component } from "react"; 2 | import Todo from "../Todo/Todo"; 3 | import "./TodoList.css"; 4 | 5 | import NewTodo from "../NewTodo"; 6 | import Divider from "../Divider"; 7 | 8 | import { fetchTodos, createTodo, deleteTodo } from "../TodoService"; 9 | 10 | class TodoList extends Component { 11 | constructor(props) { 12 | super(props); 13 | 14 | this.state = { 15 | items: [], 16 | loaded: false 17 | }; 18 | 19 | this.addTodo = this.addTodo.bind(this); 20 | this.removeTodo = this.removeTodo.bind(this); 21 | } 22 | async componentDidMount() { 23 | const { todos } = await fetchTodos(); 24 | this.setState({ items: todos, loaded: true }); 25 | } 26 | async addTodo(description) { 27 | const { status } = await createTodo(description); 28 | if (status === 200) { 29 | const newItem = { 30 | id: this.state.items.length + 1, 31 | description: description, 32 | done: false, 33 | critical: false 34 | }; 35 | this.setState({ 36 | items: [...this.state.items, newItem] 37 | }); 38 | } 39 | } 40 | async removeTodo(todoId) { 41 | const { status } = await deleteTodo(todoId); 42 | if (status === 200) { 43 | const filteredItems = this.state.items.filter(todo => { 44 | return todo.id !== todoId; 45 | }); 46 | this.setState({ items: filteredItems }); 47 | } 48 | } 49 | renderItems() { 50 | if (this.state.loaded) { 51 | return this.state.items.map(todo => ( 52 | 53 | 61 | 62 | 63 | )); 64 | } else { 65 | return

Still Loading...

; 66 | } 67 | } 68 | render() { 69 | return ( 70 |
71 | 72 | {this.renderItems()} 73 |
74 | ); 75 | } 76 | } 77 | 78 | export default TodoList; 79 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 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 subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read http://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `npm start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `npm test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `npm run build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `npm run eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | 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. 35 | 36 | 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. 37 | 38 | 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. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `npm run build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | # Create React App 2 Quick Start Guide 70 | 71 | Create React App 2 Quick Start Guide 72 | 73 | This is the code repository for [Create React App 2 Quick Start Guide](https://www.packtpub.com/application-development/create-react-app-2-quick-start-guide), published by Packt. 74 | 75 | **Build React applications faster with Create React App** 76 | 77 | ## What is this book about? 78 | If you're a power user and you aren’t happy always reusing default configurations, from previous applications with each new application, then all you need is Create React App (CRA), a tool in the React ecosystem designed to help you create boilerplate code for building a web frontend. 79 | 80 | 81 | This book covers the following exciting features: 82 | * Become familiar with React by building applications with Create React App 83 | * Make your frontend development hassle free 84 | * Create interactive UIs exploring the latest features of CRA 2 85 | * Build modern, React projects with, SASS,and progressive web applications 86 | * Develop proxy backend servers and simulate interaction with a full backend 87 | * Keep your application fully tested and maintain confidence in your project 88 | 89 | 90 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/178995276X) today! 91 | 92 | https://www.packtpub.com/ 94 | 95 | ## Instructions and Navigations 96 | All of the code is organized into folders. For example, Chapter02. 97 | 98 | The code will look like the following: 99 | ``` 100 | const App = () => { 101 | return
Homepage!
; 102 | }; 103 | ``` 104 | 105 | **Following is what you need for this book:** 106 | The book is intended for the web developers who want to jump into building great frontend with React using easy templating solutions. 107 | 108 | With the following software and hardware list you can run all code files present in the book (Chapter 1-8). 109 | ### Software and Hardware List 110 | | Chapter | Software required | OS required | 111 | | -------- | ------------------------------------ | ----------------------------------- | 112 | | 1-8 | Node.js (>= 10.x, NPM >= 6.4.x) | Windows, Mac OS X, and Linux (Any) | 113 | 114 | We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](https://www.packtpub.com/sites/default/files/downloads/9781789952766_ColorImages.pdf). 115 | 116 | ### Related products 117 | * React and React Native [[Packt]](https://www.packtpub.com/web-development/react-and-react-native?utm_source=github&utm_medium=repository&utm_campaign=9781786465658 ) [[Amazon]](https://www.amazon.com/dp/1786465655) 118 | 119 | * Full-Stack React Projects [[Packt]](https://www.packtpub.com/web-development/full-stack-react-projects?utm_source=github&utm_medium=repository&utm_campaign=9781788835534 ) [[Amazon]](https://www.amazon.com/dp/1788835530) 120 | 121 | 122 | ## Get to Know the Author 123 | **Brandon Richey** 124 | is software engineer and React enthusiast who has written a large number of popular React tutorials. He has been doing professional and hobby programming projects spanning topics from healthcare, personal sites, recruiting, and game development for nearly 20 years! When not programming, Brandon enjoys spending time with his family, playing (and making) video games, and working on his drawings and paintings! 125 | 126 | 127 | 128 | ## Other books by the authors 129 | [Phoenix Web Development](https://www.packtpub.com/web-development/phoenix-web-development?utm_source=github&utm_medium=repository&utm_campaign=9781787284197 ) 130 | 131 | 132 | ### Suggestions and Feedback 133 | [Click here](https://docs.google.com/forms/d/e/1FAIpQLSdy7dATC6QmEL81FIUuymZ0Wy9vH1jHkvpY57OiMeKGqib_Ow/viewform) if you have any feedback or suggestions. 134 | 135 | 136 | --------------------------------------------------------------------------------