├── .gitignore ├── LICENSE ├── README.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html └── manifest.json ├── src ├── App.js ├── Components │ ├── Forms │ │ └── FormAddEdit.js │ ├── Modals │ │ └── Modal.js │ └── Tables │ │ └── DataTable.js ├── index.css ├── index.js └── serviceWorker.js └── template.png /.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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Jamie Uttariello 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CRUD Starter Frontend 2 | 3 | ![image](https://github.com/olinations/crud-starter-frontend/blob/master/template.png) 4 | 5 | This is the React frontend that goes with the [CRUD Starter API backend](https://github.com/olinations/crud-starter-api). It can, however, be used as a starter for any app that features get, post, put and delete requests. 6 | 7 | It uses Bootstrap styles and reactstrap, which creates Bootstrap components, to create a responsive data table that displays all data from a table in a database. It has a modal form for adding and editing items, a delete and edit button in each item row, and a button to download the entire database table into a CSV file. 8 | 9 | It uses react-csv to create the CSV download button. 10 | 11 | ## Instructions 12 | 13 | **1. Clone this repo** 14 | 15 | ``` 16 | git clone https://github.com/olinations/crud-starter-frontend.git 17 | ``` 18 | 19 | **2. NPM install React and dependencies** 20 | 21 | ``` 22 | npm install 23 | ``` 24 | 25 | ## Notes 26 | 27 | For full details on every piece of code in this CRUD Starter Frontend visit the companion [Medium article here](https://medium.com/@olinations/build-a-crud-template-using-react-bootstrap-express-postgres-9f84cc444438?source=friends_link&sk=51028bf98ff92bc659d3edbb539a82bb). -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cp1-frontend", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "bootstrap": "^4.3.1", 7 | "react": "^16.8.5", 8 | "react-csv": "^1.1.1", 9 | "react-dom": "^16.8.5", 10 | "react-scripts": "2.1.8", 11 | "reactstrap": "^7.1.0" 12 | }, 13 | "scripts": { 14 | "start": "react-scripts start", 15 | "build": "react-scripts build", 16 | "test": "react-scripts test", 17 | "eject": "react-scripts eject" 18 | }, 19 | "eslintConfig": { 20 | "extends": "react-app" 21 | }, 22 | "browserslist": [ 23 | ">0.2%", 24 | "not dead", 25 | "not ie <= 11", 26 | "not op_mini all" 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/olinations/crud-starter-frontend/f73bd869d6f9abbbc85e8dc6687a674c125f4119/public/favicon.ico -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 16 | 25 | React App 26 | 27 | 28 | 29 |
30 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /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": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { Container, Row, Col } from 'reactstrap' 3 | import ModalForm from './Components/Modals/Modal' 4 | import DataTable from './Components/Tables/DataTable' 5 | import { CSVLink } from "react-csv" 6 | 7 | class App extends Component { 8 | state = { 9 | items: [] 10 | } 11 | 12 | getItems(){ 13 | fetch('http://localhost:3000/crud') 14 | .then(response => response.json()) 15 | .then(items => this.setState({items})) 16 | .catch(err => console.log(err)) 17 | } 18 | 19 | addItemToState = (item) => { 20 | this.setState(prevState => ({ 21 | items: [...prevState.items, item] 22 | })) 23 | } 24 | 25 | updateState = (item) => { 26 | const itemIndex = this.state.items.findIndex(data => data.id === item.id) 27 | const newArray = [ 28 | // destructure all items from beginning to the indexed item 29 | ...this.state.items.slice(0, itemIndex), 30 | // add the updated item to the array 31 | item, 32 | // add the rest of the items to the array from the index after the replaced item 33 | ...this.state.items.slice(itemIndex + 1) 34 | ] 35 | this.setState({ items: newArray }) 36 | } 37 | 38 | deleteItemFromState = (id) => { 39 | const updatedItems = this.state.items.filter(item => item.id !== id) 40 | this.setState({ items: updatedItems }) 41 | } 42 | 43 | componentDidMount(){ 44 | this.getItems() 45 | } 46 | 47 | render() { 48 | return ( 49 | 50 | 51 | 52 |

CRUD Database

53 | 54 |
55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 68 | Download CSV 69 | 70 | 71 | 72 | 73 |
74 | ) 75 | } 76 | } 77 | 78 | export default App -------------------------------------------------------------------------------- /src/Components/Forms/FormAddEdit.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Button, Form, FormGroup, Label, Input } from 'reactstrap'; 3 | 4 | class AddEditForm extends React.Component { 5 | state = { 6 | id: 0, 7 | first: '', 8 | last: '', 9 | email: '', 10 | phone: '', 11 | location: '', 12 | hobby: '' 13 | } 14 | 15 | onChange = e => { 16 | this.setState({[e.target.name]: e.target.value}) 17 | } 18 | 19 | submitFormAdd = e => { 20 | e.preventDefault() 21 | fetch('http://localhost:3000/crud', { 22 | method: 'post', 23 | headers: { 24 | 'Content-Type': 'application/json' 25 | }, 26 | body: JSON.stringify({ 27 | first: this.state.first, 28 | last: this.state.last, 29 | email: this.state.email, 30 | phone: this.state.phone, 31 | location: this.state.location, 32 | hobby: this.state.hobby 33 | }) 34 | }) 35 | .then(response => response.json()) 36 | .then(item => { 37 | if(Array.isArray(item)) { 38 | this.props.addItemToState(item[0]) 39 | this.props.toggle() 40 | } else { 41 | console.log('failure') 42 | } 43 | }) 44 | .catch(err => console.log(err)) 45 | } 46 | 47 | submitFormEdit = e => { 48 | e.preventDefault() 49 | fetch('http://localhost:3000/crud', { 50 | method: 'put', 51 | headers: { 52 | 'Content-Type': 'application/json' 53 | }, 54 | body: JSON.stringify({ 55 | id: this.state.id, 56 | first: this.state.first, 57 | last: this.state.last, 58 | email: this.state.email, 59 | phone: this.state.phone, 60 | location: this.state.location, 61 | hobby: this.state.hobby 62 | }) 63 | }) 64 | .then(response => response.json()) 65 | .then(item => { 66 | if(Array.isArray(item)) { 67 | // console.log(item[0]) 68 | this.props.updateState(item[0]) 69 | this.props.toggle() 70 | } else { 71 | console.log('failure') 72 | } 73 | }) 74 | .catch(err => console.log(err)) 75 | } 76 | 77 | componentDidMount(){ 78 | // if item exists, populate the state with proper data 79 | if(this.props.item){ 80 | const { id, first, last, email, phone, location, hobby } = this.props.item 81 | this.setState({ id, first, last, email, phone, location, hobby }) 82 | } 83 | } 84 | 85 | render() { 86 | return ( 87 |
88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 |
114 | ); 115 | } 116 | } 117 | 118 | export default AddEditForm -------------------------------------------------------------------------------- /src/Components/Modals/Modal.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { Button, Modal, ModalHeader, ModalBody } from 'reactstrap' 3 | import AddEditForm from '../Forms/FormAddEdit' 4 | 5 | class ModalForm extends Component { 6 | constructor(props) { 7 | super(props) 8 | this.state = { 9 | modal: false 10 | } 11 | } 12 | 13 | toggle = () => { 14 | this.setState(prevState => ({ 15 | modal: !prevState.modal 16 | })) 17 | } 18 | 19 | render() { 20 | const closeBtn = 21 | 22 | const label = this.props.buttonLabel 23 | 24 | let button = '' 25 | let title = '' 26 | 27 | if(label === 'Edit'){ 28 | button = 33 | title = 'Edit Item' 34 | } else { 35 | button = 40 | title = 'Add New Item' 41 | } 42 | 43 | 44 | return ( 45 |
46 | {button} 47 | 48 | {title} 49 | 50 | 55 | 56 | 57 |
58 | ) 59 | } 60 | } 61 | 62 | export default ModalForm -------------------------------------------------------------------------------- /src/Components/Tables/DataTable.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from 'react' 2 | import { Table, Button } from 'reactstrap'; 3 | import ModalForm from '../Modals/Modal' 4 | 5 | class DataTable extends Component { 6 | 7 | deleteItem = id => { 8 | let confirmDelete = window.confirm('Delete item forever?') 9 | if(confirmDelete){ 10 | fetch('http://localhost:3000/crud', { 11 | method: 'delete', 12 | headers: { 13 | 'Content-Type': 'application/json' 14 | }, 15 | body: JSON.stringify({ 16 | id 17 | }) 18 | }) 19 | .then(response => response.json()) 20 | .then(item => { 21 | this.props.deleteItemFromState(id) 22 | }) 23 | .catch(err => console.log(err)) 24 | } 25 | 26 | } 27 | 28 | render() { 29 | 30 | const items = this.props.items.map(item => { 31 | return ( 32 | 33 | {item.id} 34 | {item.first} 35 | {item.last} 36 | {item.email} 37 | {item.phone} 38 | {item.location} 39 | {item.hobby} 40 | 41 |
42 | 43 | {' '} 44 | 45 |
46 | 47 | 48 | ) 49 | }) 50 | 51 | return ( 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | {items} 67 | 68 |
IDFirstLastEmailPhoneLocationHobbyActions
69 | ) 70 | } 71 | } 72 | 73 | export default DataTable -------------------------------------------------------------------------------- /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 | table th, table td { white-space: nowrap; } 12 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | import 'bootstrap/dist/css/bootstrap.min.css'; 7 | 8 | ReactDOM.render(, document.getElementById('root')); 9 | 10 | // If you want your app to work offline and load faster, you can change 11 | // unregister() to register() below. Note this comes with some pitfalls. 12 | // Learn more about service workers: https://bit.ly/CRA-PWA 13 | serviceWorker.unregister(); 14 | -------------------------------------------------------------------------------- /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 https://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 https://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 https://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 | -------------------------------------------------------------------------------- /template.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/olinations/crud-starter-frontend/f73bd869d6f9abbbc85e8dc6687a674c125f4119/template.png --------------------------------------------------------------------------------