├── .env ├── README.md ├── package-lock.json └── react-hooks ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public ├── favicon.ico ├── index.html ├── logo192.png ├── logo512.png ├── manifest.json └── robots.txt ├── src ├── App.js ├── App.test.js ├── Components │ ├── Counters │ │ ├── classCounter.jsx │ │ ├── hookCounter.jsx │ │ └── hookCounterWithReducer.jsx │ ├── DataFetch │ │ ├── classFetchData.jsx │ │ ├── functionFetchData.jsx │ │ └── modal.jsx │ ├── Forms │ │ ├── abstractHookForm.jsx │ │ ├── calendarForm.jsx │ │ ├── classForm.jsx │ │ ├── hookForm.jsx │ │ └── refactoredHookForm.jsx │ ├── Search │ │ └── search.jsx │ └── ToDos │ │ └── toDoHooks.jsx ├── StyleSheets │ ├── App.css │ └── index.css ├── index.js ├── logo.svg └── serviceWorker.js └── yarn.lock /.env: -------------------------------------------------------------------------------- 1 | REACT_APP_NASA_API_KEY=Twc8x8c9cA57VmYOa3boYeqTce88Oig9md5mhjmC -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React-Hooks 2 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "lockfileVersion": 1 3 | } 4 | -------------------------------------------------------------------------------- /react-hooks/.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 | #key 9 | .env 10 | 11 | # testing 12 | /coverage 13 | 14 | # production 15 | /build 16 | 17 | # misc 18 | .DS_Store 19 | .env.local 20 | .env.development.local 21 | .env.test.local 22 | .env.production.local 23 | 24 | npm-debug.log* 25 | yarn-debug.log* 26 | yarn-error.log* 27 | -------------------------------------------------------------------------------- /react-hooks/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 | ### `yarn 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 | ### `yarn 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 | ### `yarn 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 | ### `yarn 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 | ### `yarn 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 | -------------------------------------------------------------------------------- /react-hooks/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-hooks", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "bootstrap": "^4.3.1", 7 | "dotenv": "^8.2.0", 8 | "react": "^16.11.0", 9 | "react-bootstrap": "^1.0.0-beta.14", 10 | "react-dom": "^16.11.0", 11 | "react-scripts": "3.2.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 | "production": [ 24 | ">0.2%", 25 | "not dead", 26 | "not op_mini all" 27 | ], 28 | "development": [ 29 | "last 1 chrome version", 30 | "last 1 firefox version", 31 | "last 1 safari version" 32 | ] 33 | }, 34 | "devDependencies": { 35 | "eslint": "^6.6.0" 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /react-hooks/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrestonElliott/React-Hooks/c6d31df37508b7d9ad696bdb7efca1ea21bda455/react-hooks/public/favicon.ico -------------------------------------------------------------------------------- /react-hooks/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /react-hooks/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrestonElliott/React-Hooks/c6d31df37508b7d9ad696bdb7efca1ea21bda455/react-hooks/public/logo192.png -------------------------------------------------------------------------------- /react-hooks/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrestonElliott/React-Hooks/c6d31df37508b7d9ad696bdb7efca1ea21bda455/react-hooks/public/logo512.png -------------------------------------------------------------------------------- /react-hooks/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 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /react-hooks/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /react-hooks/src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Fragment } from 'react'; 2 | import './StyleSheets/App.css'; 3 | 4 | // import ClassForm from './Components/Forms/classForm' 5 | // import HookForm from './Components/Forms/hookForm'; 6 | // import RefactoredHookForm from './Components/Forms/refactoredHookForm' 7 | // import AbstractHookForm from './Components/Forms/abstractHookForm' 8 | // import CalendarForm from './Components/Forms/calendarForm' 9 | 10 | // import ClassCounter from './Components/Counters/classCounter' 11 | // import HookCounter from './Components/Counters/hookCounter' 12 | // import HookReducerCounter from './Components/Counters/hookCounterWithReducer' 13 | 14 | // import ToDoHook from './Components/ToDos/toDoHooks' 15 | 16 | // import FunctionDailyPic from './Components/DataFetch/functionFetchData' 17 | // import ClassDailyPic from './Components/DataFetch/classFetchData' 18 | 19 | // import DetailsModal from './Components/DataFetch/modal' 20 | 21 | import Search from './Components/Search/search' 22 | 23 | 24 | import 'bootstrap/dist/css/bootstrap.min.css'; 25 | 26 | function App() { 27 | return ( 28 | 29 |
30 | 31 | {/* */} 32 | {/* */} 33 | {/* */} 34 | {/* */} 35 | {/* */} 36 | {/* */} 37 | {/* 38 | */} 39 | {/* 40 | 41 | 42 | */} 43 |
44 |
45 | ); 46 | } 47 | 48 | export default App; 49 | -------------------------------------------------------------------------------- /react-hooks/src/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 | -------------------------------------------------------------------------------- /react-hooks/src/Components/Counters/classCounter.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { Button } from 'react-bootstrap' 3 | 4 | export default class ClassCounter extends React.Component { 5 | // COUNTER CLASS COMPONENT 6 | 7 | // SET INITIAL STATE 8 | state = { 9 | count: 0 10 | } 11 | 12 | // COUNT EVENT HANDLER 13 | handleCounter = () => { 14 | this.setState({ ...this.state, count: this.state.count + 1 }) 15 | } 16 | 17 | // CREATE EFFECT - UPDATES BROWSER TAB TEXT 18 | componentDidMount() { 19 | document.title = `Count: ${this.state.count}` 20 | } 21 | 22 | componentDidUpdate() { 23 | document.title = `Count: ${this.state.count}` 24 | } 25 | 26 | // RENDERS COMPONENT 27 | render() { 28 | return( 29 |
30 |

31 | You clicked the button {this.state.count} times. 32 |

33 | 34 | 40 |
41 | ) 42 | } 43 | } -------------------------------------------------------------------------------- /react-hooks/src/Components/Counters/hookCounter.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react' 2 | import { Button } from 'react-bootstrap' 3 | 4 | export default function Counter() { 5 | // COUNTER FUNCTION COMPONENT - USING REACT HOOKS 6 | 7 | // SET INITIAL STATE 8 | const [count, setCount] = useState(0) 9 | useBrowserTabEffect(count) 10 | 11 | // COUNT EVENT HANDLER 12 | function handleCounter () { 13 | setCount(count + 1) 14 | } 15 | 16 | // RENDERS COMPONENT 17 | return ( 18 |
19 |

20 | You clicked the button {count} times. 21 |

22 | 23 | 29 |
30 | ) 31 | } 32 | 33 | // REFACTORED INTO CUSTOM EFFECT HOOK - useBrowserTabEffect 34 | function useBrowserTabEffect(count) { 35 | useEffect(() => { 36 | document.title = `You clicked ${count} times.` 37 | }, [count]) 38 | } -------------------------------------------------------------------------------- /react-hooks/src/Components/Counters/hookCounterWithReducer.jsx: -------------------------------------------------------------------------------- 1 | import React, { useReducer } from 'react' 2 | import { Button } from 'react-bootstrap' 3 | 4 | export default function Counter() { 5 | const initialState = { count: 0 } 6 | 7 | // ROUTES ACTIONS TO UPDATE STATE 8 | const reducer = (state, action) => { 9 | switch(action.type) { 10 | case "INCREASE": { 11 | return { count: state.count + 1 } 12 | } 13 | case "DECREASE": { 14 | return { count: state.count - 1 } 15 | } 16 | case "RESET": { 17 | return { count: state.count = 0 } 18 | } 19 | default: 20 | return state.count 21 | } 22 | } 23 | 24 | // state UPDATES VIA dispatch 25 | // useReducer TAKES IN THE reducer FUNCTION AND initialState 26 | const [state, dispatch] = useReducer(reducer, initialState) 27 | 28 | // RENDERS COUNT COMPONENT 29 | return ( 30 |
31 |

32 | Count: {state.count} 33 |

34 | 35 | 42 | 43 | 50 | 51 | 58 |
59 | ) 60 | } -------------------------------------------------------------------------------- /react-hooks/src/Components/DataFetch/classFetchData.jsx: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import { Image, Button, Modal, Jumbotron } from 'react-bootstrap' 3 | 4 | export default class ClassDailyPic extends React.Component { 5 | 6 | state = { 7 | nasaData: { }, 8 | showModal: false 9 | } 10 | 11 | async componentDidMount() { 12 | const res = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY`) 13 | const data = await res.json() 14 | this.setState({ nasaData: data }) 15 | } 16 | 17 | handleShow = () => this.setState({showModal: true}) 18 | 19 | handleHide = () => this.setState({showModal: false}) 20 | 21 | render() { 22 | return ( 23 | <> 24 |
25 | 26 |

{this.state.nasaData.title}

27 | 30 |
31 |
32 | 33 | 51 | 52 | ) 53 | } 54 | } -------------------------------------------------------------------------------- /react-hooks/src/Components/DataFetch/functionFetchData.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from 'react' 2 | import { Image, Button, Modal, Jumbotron } from 'react-bootstrap' 3 | 4 | export default function FunctionDailyPic() { 5 | 6 | const [nasaData, setData] = useState({ }) 7 | const [showModal, setModal] = useState(false) 8 | 9 | async function fetchData() { 10 | const res = await fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY`) 11 | const data = await res.json() 12 | setData(data) 13 | } 14 | 15 | useEffect(() => { fetchData() }, []) 16 | 17 | return ( 18 | <> 19 |
20 | 21 |

{nasaData.title}

22 | 25 |
26 |
27 | 28 | 45 | 46 | ) 47 | } -------------------------------------------------------------------------------- /react-hooks/src/Components/DataFetch/modal.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react' 2 | import { Button, Modal } from 'react-bootstrap' 3 | 4 | export default function DetailsModal() { 5 | const [show, setShow] = useState(false) 6 | 7 | const handleClose = () => setShow(false) 8 | const handleShow = () => setShow(true) 9 | 10 | return ( 11 | <> 12 | 15 | 16 | 17 | 18 | Modal heading 19 | 20 | Woohoo, you're reading this text in a modal! 21 | 22 | 25 | 26 | 27 | 28 | ) 29 | } 30 | -------------------------------------------------------------------------------- /react-hooks/src/Components/Forms/abstractHookForm.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, Fragment } from 'react' 2 | import { Form, Button, Jumbotron } from 'react-bootstrap' 3 | 4 | export default function AbstractHookForm() { 5 | // ABSTRACT REACT HOOKS - FUNCTION COMPONENT 6 | 7 | // CREATE OBJECTS TO PASS AS ARGUMENTS INTO FUNCTION useFormUpdate 8 | // CALL CUSTOM HOOK useBrowserTabEffect 9 | const firstName = useFormUpdate() 10 | const lastName = useFormUpdate() 11 | const email = useFormUpdate() 12 | useBrowserTabEffect(firstName.value + ' ' + lastName.value) 13 | 14 | // ABSTRACT REACT HOOKS - FORM SUBMIT EVENT HANDLER 15 | const handleSubmit = (e) => { 16 | console.log(firstName.value) 17 | e.preventDefault() 18 | 19 | fetch('http://localhost:3000/users', { 20 | method: 'POST', 21 | headers: { 22 | Accept: 'application/json', 23 | 'Content-Type':'application/json' }, 24 | body: JSON.stringify({ 25 | user: { 26 | firstName: firstName.value, 27 | lastName: lastName.value, 28 | email: email.value 29 | } 30 | }) 31 | }) 32 | } 33 | 34 | // ABSTRACT REACT HOOKS - RENDERS COMPONENT 35 | return ( 36 | 37 | 38 |
42 | 43 | 44 | More Abstract React Hooks - Sign Up Form 45 | 46 | 47 | 54 | 55 | 62 | 63 | 70 | 71 | 78 | 79 |
80 |
81 | ) 82 | } 83 | 84 | // ABSTRACT REACT HOOKS - CAN MOVE FUNCTIONS TO BOTTOM OF FILE 85 | function useFormUpdate(initialValue) { 86 | const [value, formValue] = useState(initialValue) 87 | 88 | function handleChange(e) { 89 | formValue(e.target.value) 90 | } 91 | 92 | return { 93 | value, 94 | onChange: handleChange 95 | } 96 | } 97 | 98 | // ABSTRACT REACT EFFECT HOOK - UPDATES BROWSER TAB TEXT 99 | function useBrowserTabEffect(name) { 100 | useEffect(() => { 101 | document.title = name 102 | }) 103 | } 104 | 105 | 106 | // SHOW HOW TO REMOVE EFFECT AFTER ITS USED 107 | // OPTIONAL RETURN STATEMENT IN USE EFFECT 108 | 109 | -------------------------------------------------------------------------------- /react-hooks/src/Components/Forms/calendarForm.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react' 2 | import { Form, Button, Jumbotron } from 'react-bootstrap' 3 | 4 | export default function CalendarForm() { 5 | 6 | // CREATE OBJECTS TO PASS AS ARGUMENTS INTO FUNCTION useFormUpdate 7 | const firstName = useFormUpdate() 8 | const lastName = useFormUpdate() 9 | const email = useFormUpdate() 10 | 11 | // REFACTORED REACT HOOKS - FORM FIELDS EVENT HANDLER 12 | // CUSTOM REACT HOOK useFormUpdate - WORKS FOR ALL FORM FIELDS 13 | function useFormUpdate(initialValue) { 14 | const [value, formValue] = useState(initialValue) 15 | 16 | function handleChange(e) { 17 | formValue(e.target.value) 18 | } 19 | 20 | return { 21 | value, 22 | onChange: handleChange 23 | } 24 | } 25 | 26 | // REFACTORED REACT HOOKS - FORM SUBMIT EVENT HANDLER 27 | const handleSubmit = (e) => { 28 | e.preventDefault() 29 | 30 | fetch('http://localhost:3000/users', { 31 | method: 'POST', 32 | headers: { 33 | Accept: 'application/json', 34 | 'Content-Type':'application/json' }, 35 | body: JSON.stringify({ 36 | user: { 37 | firstName: firstName.value, 38 | lastName: lastName.value, 39 | email: email.value 40 | } 41 | }) 42 | }) 43 | } 44 | 45 | return ( 46 | <> 47 | 48 |
49 | 50 | 51 | Sign Up Form 52 | 53 | 54 | 61 | 62 | 69 | 70 | 77 | 78 | 81 | 82 |
83 | 84 | ) 85 | } 86 | 87 | // ON SUBMIT - DISPLAY A MODAL WITH Thank you {name}! Your sign up was successful! 88 | -------------------------------------------------------------------------------- /react-hooks/src/Components/Forms/classForm.jsx: -------------------------------------------------------------------------------- 1 | import React, { Fragment } from 'react' 2 | import { Form, Button, Jumbotron } from 'react-bootstrap' 3 | 4 | export default class ClassSignUpForm extends React.Component { 5 | // CLASS COMPONENT - FORM USING STATE 6 | 7 | // SET INITIAL STATE 8 | state = { 9 | firstName: "First Name", 10 | lastName: "", 11 | email: "" 12 | } 13 | 14 | // CLASS COMPONENT - FORM FIELDS EVENT HANDLERS 15 | handleFirstNameUpdate = (e) => { 16 | this.setState({ 17 | ...this.state, firstName: e.target.value 18 | }) 19 | } 20 | 21 | handleLastNameUpdate = (e) => { 22 | this.setState({ 23 | ...this.state, lastName: e.target.value 24 | }) 25 | } 26 | 27 | handleEmailUpdate = (e) => { 28 | this.setState({ 29 | ...this.state, email: e.target.value 30 | }) 31 | } 32 | 33 | // CLASS COMPONENT - FORM SUBMIT EVENT HANDLER 34 | handleSubmit = (e) => { 35 | e.preventDefault() 36 | 37 | fetch('http://localhost:3000/users', { 38 | method: 'POST', 39 | headers: { 40 | Accept: 'application/json', 41 | 'Content-Type':'application/json' }, 42 | body: JSON.stringify({ 43 | user: { 44 | firstName: this.state.firstName, 45 | lastName: this.state.lastName, 46 | email: this.state.email 47 | } 48 | }) 49 | }) 50 | } 51 | 52 | // RENDERS CLASS COMPONENT 53 | render() { 54 | return ( 55 | 56 | 57 |
61 | 62 | 63 | Class Component - Sign Up Form 64 | 65 | 66 | 75 | 76 | 85 | 86 | 95 | 96 | 103 | 104 | 105 |
106 |
107 | ) 108 | } 109 | 110 | } -------------------------------------------------------------------------------- /react-hooks/src/Components/Forms/hookForm.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, Fragment } from 'react' 2 | import { Form, Button, Jumbotron } from 'react-bootstrap' 3 | 4 | export default function HookSignUpForm() { 5 | // FUNCTION COMPONENT WITH REACT HOOKS 6 | 7 | // SET INITIAL STATE 8 | const [firstName, formFirstName] = useState("First Name ") 9 | const [lastName, formLastName] = useState() 10 | const [email, formEmail] = useState() 11 | 12 | // REACT HOOKS - FORM FIELDS EVENT HANDLERS 13 | function handleFirstNameUpdate(e) { 14 | formFirstName(e.target.value) 15 | } 16 | 17 | function handleLastNameUpdate(e) { 18 | formLastName(e.target.value) 19 | } 20 | 21 | function handleEmailUpdate(e) { 22 | formEmail(e.target.value) 23 | } 24 | 25 | // REACT HOOKS - FORM SUBMIT EVENT HANDLER 26 | const handleSubmit = (e) => { 27 | e.preventDefault() 28 | 29 | console.log(firstName) 30 | 31 | fetch('http://localhost:3000/users', { 32 | method: 'POST', 33 | headers: { 34 | Accept: 'application/json', 35 | 'Content-Type':'application/json' }, 36 | body: JSON.stringify({ 37 | user: { 38 | firstName: firstName, 39 | lastName: lastName, 40 | email: email 41 | } 42 | }) 43 | }) 44 | } 45 | 46 | // REFACTORED REACT EFFECT HOOK - UPDATES BROWSER TAB TEXT 47 | useEffect(() => { 48 | document.title = firstName + ' ' + lastName 49 | }) 50 | 51 | // REACT HOOKS - RENDERS COMPONENT 52 | return ( 53 | 54 | 55 |
59 | 60 | 61 | React Hooks - Sign Up Form 62 | 63 | 64 | 72 | 73 | 81 | 82 | 90 | 91 | 98 | 99 | 100 |
101 |
102 | ) 103 | } 104 | 105 | -------------------------------------------------------------------------------- /react-hooks/src/Components/Forms/refactoredHookForm.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, Fragment } from 'react' 2 | import { Form, Button, Jumbotron } from 'react-bootstrap' 3 | 4 | export default function RefactoredSignUpForm() { 5 | // REFACTORED REACT HOOKS - FUNCTION COMPONENT 6 | 7 | // CREATE OBJECTS TO PASS AS ARGUMENTS INTO FUNCTION useFormUpdate 8 | const firstName = useFormUpdate() 9 | const lastName = useFormUpdate() 10 | const email = useFormUpdate() 11 | 12 | // REFACTORED REACT HOOKS - FORM FIELDS EVENT HANDLER 13 | // CUSTOM REACT HOOK useFormUpdate - WORKS FOR ALL FORM FIELDS 14 | function useFormUpdate(initialValue) { 15 | const [value, formValue] = useState(initialValue) 16 | 17 | function handleChange(e) { 18 | formValue(e.target.value) 19 | } 20 | 21 | return { 22 | value, 23 | onChange: handleChange 24 | } 25 | } 26 | 27 | // REFACTORED REACT HOOKS - FORM SUBMIT EVENT HANDLER 28 | const handleSubmit = (e) => { 29 | console.log(firstName.value) 30 | e.preventDefault() 31 | 32 | fetch('http://localhost:3000/users', { 33 | method: 'POST', 34 | headers: { 35 | Accept: 'application/json', 36 | 'Content-Type':'application/json' }, 37 | body: JSON.stringify({ 38 | user: { 39 | firstName: firstName.value, 40 | lastName: lastName.value, 41 | email: email.value 42 | } 43 | }) 44 | }) 45 | } 46 | 47 | // REFACTORED REACT EFFECT HOOK - UPDATES BROWSER TAB TEXT 48 | useEffect(() => { 49 | document.title = firstName.value + ' ' + lastName.value 50 | }) 51 | 52 | // REFACTORED REACT HOOKS - RENDERS COMPONENT 53 | return ( 54 | 55 | 56 |
60 | 61 | 62 | Refactored React Hooks - Sign Up Form 63 | 64 | 65 | 72 | 73 | 80 | 81 | 88 | 89 | 96 | 97 |
98 |
99 | ) 100 | } 101 | 102 | -------------------------------------------------------------------------------- /react-hooks/src/Components/Search/search.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, useRef } from 'react' 2 | import { Form, ListGroup, Jumbotron } from 'react-bootstrap' 3 | 4 | export default function Search() { 5 | 6 | // SET INITIAL STATE FOR query AND jokes 7 | // CREATE REF FOR SEARCH INPUT 8 | const [query, setQuery] = useState('') 9 | const [jokes, setJokes] = useState([]) 10 | const focusSearch = useRef(null) 11 | 12 | // useEffect - FOCUS ON SEARCH INPUT 13 | useEffect(() => {focusSearch.current.focus()}, []) 14 | 15 | // FETCH API DATA 16 | const getJokes = async (query) => { 17 | const results = await fetch(`https://icanhazdadjoke.com/search?term=${query}`, { 18 | headers: {'accept': 'application/json'} 19 | }) 20 | const jokesData = await results.json() 21 | return jokesData.results 22 | } 23 | 24 | // PREVENTS RERENDER FLICKERING AS USER TYPES IN SEARCH 25 | const sleep = (ms) => { 26 | return new Promise(resolve => setTimeout(resolve, ms)) 27 | } 28 | 29 | // useEffect - ONLY RERENDERS WHEN query IS CHANGED 30 | useEffect(() => { 31 | let currentQuery = true 32 | const controller = new AbortController() 33 | 34 | const loadJokes = async () => { 35 | if (!query) return setJokes([]) 36 | 37 | await sleep(350) 38 | if (currentQuery) { 39 | const jokes = await getJokes(query, controller) 40 | setJokes(jokes) 41 | } 42 | } 43 | loadJokes() 44 | 45 | return () => { 46 | currentQuery = false 47 | controller.abort() 48 | } 49 | }, [query]) 50 | 51 | // RENDER JOKES 52 | let jokeComponents = jokes.map((joke, index) => { 53 | return ( 54 | 55 | {joke.joke} 56 | 57 | ) 58 | }) 59 | 60 | // RENDER COMPONENT 61 | return ( 62 | <> 63 | 64 |
65 |

Dad Jokes

66 | setQuery(e.target.value)} 71 | value={query} 72 | /> 73 | 74 | 75 | 76 | {jokeComponents} 77 | 78 |
79 | 80 | ) 81 | } -------------------------------------------------------------------------------- /react-hooks/src/Components/ToDos/toDoHooks.jsx: -------------------------------------------------------------------------------- 1 | import React, { Fragment, useRef, useReducer } from 'react' 2 | import { Form, Button } from 'react-bootstrap' 3 | 4 | export default function Todos() { 5 | // TO-DO INPUT INITIAL STATE IS BLANK 6 | // CREATE REF FOR TO-DO INPUT 7 | const todoText = useRef() 8 | 9 | // todoList UPDATES VIA dispatch 10 | // todoList INITIAL STATE SET TO EMPTY ARRAY ON LINE 33 11 | const [todoList, dispatch] = useReducer((state, action) => { 12 | switch(action.type) { 13 | case "ADD_ITEM": { 14 | return [ 15 | ...state, 16 | { 17 | text: action.text, 18 | id: action.id 19 | } 20 | ] 21 | } 22 | case "DELETE_ITEM": { 23 | return state.filter((todo, index) => 24 | index !== action.index 25 | ) 26 | } 27 | case "CLEAR_ITEMS": { 28 | return [] 29 | } 30 | default: 31 | return state 32 | } 33 | }, []) 34 | 35 | // FORM SUBMIT EVENT HANDLER 36 | function handleSubmit(e) { 37 | e.preventDefault() 38 | dispatch({ 39 | type: "ADD_ITEM", 40 | text: todoText.current.value 41 | }) 42 | todoText.current.value = "" 43 | } 44 | 45 | // RENDER TO-DO COMPONENT 46 | return ( 47 | 48 |
49 |
50 |

To-Do List

51 | 52 | 55 |
56 | 57 |
    58 | {todoList.map((todo, index) => 59 |
  • 60 | {todo.text} 61 | 68 |
  • 69 | )} 70 |
71 |
72 |
73 | ) 74 | } 75 | -------------------------------------------------------------------------------- /react-hooks/src/StyleSheets/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | height: 40vmin; 7 | } 8 | 9 | .App-header { 10 | background-color: #282c34; 11 | min-height: 100vh; 12 | display: flex; 13 | flex-direction: column; 14 | align-items: center; 15 | justify-content: center; 16 | font-size: calc(10px + 2vmin); 17 | color: white; 18 | } 19 | 20 | .App-link { 21 | color: #09d3ac; 22 | } 23 | -------------------------------------------------------------------------------- /react-hooks/src/StyleSheets/index.css: -------------------------------------------------------------------------------- 1 | /* SEARCH */ 2 | #search-form { 3 | margin: auto; 4 | text-align: center; 5 | width: 50%; 6 | padding: 1%; 7 | border-radius: 5%; 8 | } 9 | 10 | #search-input { 11 | margin: .5%; 12 | padding: 1.36%; 13 | border-radius: 5%; 14 | } 15 | 16 | #jokes-list { 17 | margin: auto; 18 | text-align: auto; 19 | padding: 2%; 20 | list-style-position: outside; 21 | } 22 | 23 | 24 | 25 | /* TO DO STYLING */ 26 | #to-do-form { 27 | margin: auto; 28 | text-align: center; 29 | width: 50%; 30 | padding: 1%; 31 | border-radius: 5%; 32 | } 33 | 34 | #to-do-form-input { 35 | margin: .5%; 36 | padding: 1.36%; 37 | border-radius: 5%; 38 | } 39 | 40 | .to-do-items { 41 | margin: auto; 42 | text-align: center; 43 | padding: 2%; 44 | list-style-position: inside; 45 | } 46 | 47 | .to-do-delete { 48 | margin: 1%; 49 | padding: 2%; 50 | border-radius: 5%; 51 | text-align: center; 52 | } 53 | 54 | /* NASA DAILY PIC */ 55 | #jumbo-photo { 56 | display: block; 57 | margin-left: auto; 58 | margin-right: auto; 59 | width: 50%; 60 | padding: 1%; 61 | } 62 | 63 | #pic-sub-title { 64 | text-align: auto; 65 | padding: 2%; 66 | } 67 | 68 | #landing-page-title { 69 | padding: 2%; 70 | } 71 | 72 | #pic-title { 73 | text-align: auto; 74 | padding: 2%; 75 | } 76 | 77 | #pic-info { 78 | text-align: center; 79 | padding: 2%; 80 | } 81 | 82 | #jumbo-div { 83 | text-align: center; 84 | padding: 1%; 85 | margin: 2%; 86 | } 87 | 88 | #modal-div { 89 | text-align: center; 90 | padding: 2%; 91 | } 92 | 93 | #pic-summary { 94 | height: 75px; 95 | overflow-y: scroll; 96 | } 97 | 98 | /* COUNTER STYLING */ 99 | .counter { 100 | margin: auto; 101 | text-align: auto; 102 | width: 50%; 103 | padding: 3%; 104 | } 105 | 106 | .counter-button { 107 | padding: 2%; 108 | margin: 2%; 109 | text-align: auto; 110 | } 111 | 112 | /* FORMS STYLING */ 113 | .sign-up-form { 114 | margin: auto; 115 | text-align: center; 116 | width: 50%; 117 | } 118 | 119 | .form-header { 120 | font-weight: bold; 121 | font-size: 125%; 122 | text-align: auto; 123 | color: whitesmoke; 124 | } 125 | 126 | .form-fields { 127 | padding: 2%; 128 | margin: 2%; 129 | text-align: auto; 130 | } 131 | 132 | .submit-button { 133 | padding: 2%; 134 | margin: 2%; 135 | text-align: center; 136 | } 137 | 138 | #class-form { 139 | background: rgb(109, 109, 109); 140 | } 141 | 142 | #hook-form-1 { 143 | background: rgb(1, 41, 48); 144 | } 145 | 146 | #hook-form-2 { 147 | background: rgb(4, 63, 43); 148 | } 149 | 150 | #hook-form-3 { 151 | background: rgb(39, 19, 3); 152 | } 153 | 154 | body { 155 | margin: 0; 156 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 157 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 158 | sans-serif; 159 | -webkit-font-smoothing: antialiased; 160 | -moz-osx-font-smoothing: grayscale; 161 | } 162 | 163 | code { 164 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 165 | monospace; 166 | } 167 | -------------------------------------------------------------------------------- /react-hooks/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './StyleSheets/index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /react-hooks/src/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /react-hooks/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 | --------------------------------------------------------------------------------