30 | )
31 |
32 | ReactDOM.render(templateTwo, document.getElementById('root'))
33 | }
34 |
35 | renderCounterApp()
36 |
37 | // If you want your app to work offline and load faster, you can change
38 | // unregister() to register() below. Note this comes with some pitfalls.
39 | // Learn more about service workers: https://bit.ly/CRA-PWA
40 | serviceWorker.unregister();
41 |
--------------------------------------------------------------------------------
/01-contador/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/01-contador/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 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/.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 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/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 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "my-app",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "react": "^16.8.6",
7 | "react-dom": "^16.8.6",
8 | "react-scripts": "3.0.1"
9 | },
10 | "scripts": {
11 | "start": "react-scripts start",
12 | "build": "react-scripts build",
13 | "test": "react-scripts test",
14 | "eject": "react-scripts eject"
15 | },
16 | "eslintConfig": {
17 | "extends": "react-app"
18 | },
19 | "browserslist": {
20 | "production": [
21 | ">0.2%",
22 | "not dead",
23 | "not op_mini all"
24 | ],
25 | "development": [
26 | "last 1 chrome version",
27 | "last 1 firefox version",
28 | "last 1 safari version"
29 | ]
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/reprograma/T7-react-I/811d48baf14716bf29d798b7825848d778e73ed1/02-comentarios-componentes/public/favicon.ico
--------------------------------------------------------------------------------
/02-comentarios-componentes/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 | React App
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/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 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/src/App.css:
--------------------------------------------------------------------------------
1 | @import url('https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap');
2 |
3 | * {
4 | box-sizing: border-box;
5 | }
6 |
7 | .comentario {
8 | font-family: 'Roboto', Arial, Helvetica, sans-serif;
9 | border-radius: 10px;
10 | background-color: #f3f3f3;
11 | padding: 25px;
12 | display: flex;
13 | max-width: 960px;
14 | margin: 50px auto;
15 | }
16 |
17 | .comentario__perfil {
18 | width: 100%;
19 | max-width: 200px;
20 | margin-right: 50px;
21 | border-radius: 10px;
22 | }
23 |
24 | .comentario__nome {
25 | margin: 0;
26 | font-size: 24px;
27 | }
28 |
29 | .comentario__subtitulo {
30 | margin: 0;
31 | margin-bottom: 15px;
32 | font-weight: normal;
33 | font-size: 20px;
34 | }
35 |
36 | .comentario hr {
37 | max-width: 200px;
38 | margin-left: 0;
39 | }
40 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import './App.css';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | class Comentario extends React.Component {
8 | render() {
9 | return (
10 |
41 | )
42 | }
43 | }
44 |
45 | ReactDOM.render(, document.getElementById('root'));
46 |
47 | // If you want your app to work offline and load faster, you can change
48 | // unregister() to register() below. Note this comes with some pitfalls.
49 | // Learn more about service workers: https://bit.ly/CRA-PWA
50 | serviceWorker.unregister();
51 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/02-comentarios-componentes/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 |
--------------------------------------------------------------------------------
/03-esconde-aparece/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 |
--------------------------------------------------------------------------------
/03-esconde-aparece/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "previsao-tempo",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "react": "^16.8.6",
7 | "react-dom": "^16.8.6",
8 | "react-scripts": "3.0.1"
9 | },
10 | "scripts": {
11 | "start": "react-scripts start",
12 | "build": "react-scripts build",
13 | "test": "react-scripts test",
14 | "eject": "react-scripts eject"
15 | },
16 | "eslintConfig": {
17 | "extends": "react-app"
18 | },
19 | "browserslist": {
20 | "production": [
21 | ">0.2%",
22 | "not dead",
23 | "not op_mini all"
24 | ],
25 | "development": [
26 | "last 1 chrome version",
27 | "last 1 firefox version",
28 | "last 1 safari version"
29 | ]
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/03-esconde-aparece/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/reprograma/T7-react-I/811d48baf14716bf29d798b7825848d778e73ed1/03-esconde-aparece/public/favicon.ico
--------------------------------------------------------------------------------
/03-esconde-aparece/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
26 |
27 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/03-esconde-aparece/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 |
--------------------------------------------------------------------------------
/03-esconde-aparece/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 40vmin;
8 | pointer-events: none;
9 | }
10 |
11 | .App-header {
12 | background-color: #282c34;
13 | min-height: 100vh;
14 | display: flex;
15 | flex-direction: column;
16 | align-items: center;
17 | justify-content: center;
18 | font-size: calc(10px + 2vmin);
19 | color: white;
20 | }
21 |
22 | .App-link {
23 | color: #61dafb;
24 | }
25 |
26 | @keyframes App-logo-spin {
27 | from {
28 | transform: rotate(0deg);
29 | }
30 | to {
31 | transform: rotate(360deg);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/03-esconde-aparece/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import logo from './logo.svg';
3 | import './App.css';
4 |
5 | function App() {
6 | return (
7 |
35 | )
36 | }
37 | }
38 |
39 | ReactDOM.render(, document.getElementById('root'));
40 |
41 |
42 | // If you want your app to work offline and load faster, you can change
43 | // unregister() to register() below. Note this comes with some pitfalls.
44 | // Learn more about service workers: https://bit.ly/CRA-PWA
45 | serviceWorker.unregister();
46 |
--------------------------------------------------------------------------------
/03-esconde-aparece/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/03-esconde-aparece/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 |
--------------------------------------------------------------------------------
/04-previsao-tempo-map/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 |
--------------------------------------------------------------------------------
/04-previsao-tempo-map/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "previsao-tempo",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "react": "^16.8.6",
7 | "react-dom": "^16.8.6",
8 | "react-scripts": "3.0.1"
9 | },
10 | "scripts": {
11 | "start": "react-scripts start",
12 | "build": "react-scripts build",
13 | "test": "react-scripts test",
14 | "eject": "react-scripts eject"
15 | },
16 | "eslintConfig": {
17 | "extends": "react-app"
18 | },
19 | "browserslist": {
20 | "production": [
21 | ">0.2%",
22 | "not dead",
23 | "not op_mini all"
24 | ],
25 | "development": [
26 | "last 1 chrome version",
27 | "last 1 firefox version",
28 | "last 1 safari version"
29 | ]
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/04-previsao-tempo-map/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/reprograma/T7-react-I/811d48baf14716bf29d798b7825848d778e73ed1/04-previsao-tempo-map/public/favicon.ico
--------------------------------------------------------------------------------
/04-previsao-tempo-map/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
26 |
27 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/04-previsao-tempo-map/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 |
--------------------------------------------------------------------------------
/04-previsao-tempo-map/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 40vmin;
8 | pointer-events: none;
9 | }
10 |
11 | .App-header {
12 | background-color: #282c34;
13 | min-height: 100vh;
14 | display: flex;
15 | flex-direction: column;
16 | align-items: center;
17 | justify-content: center;
18 | font-size: calc(10px + 2vmin);
19 | color: white;
20 | }
21 |
22 | .App-link {
23 | color: #61dafb;
24 | }
25 |
26 | @keyframes App-logo-spin {
27 | from {
28 | transform: rotate(0deg);
29 | }
30 | to {
31 | transform: rotate(360deg);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/04-previsao-tempo-map/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import logo from './logo.svg';
3 | import './App.css';
4 |
5 | function App() {
6 | return (
7 |
61 | )
62 | }
63 | }
64 |
65 | ReactDOM.render(, document.getElementById('root'));
66 |
67 | // If you want your app to work offline and load faster, you can change
68 | // unregister() to register() below. Note this comes with some pitfalls.
69 | // Learn more about service workers: https://bit.ly/CRA-PWA
70 | serviceWorker.unregister();
71 |
--------------------------------------------------------------------------------
/04-previsao-tempo-map/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/04-previsao-tempo-map/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 |
--------------------------------------------------------------------------------
/05-app-final/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 |
--------------------------------------------------------------------------------
/05-app-final/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "app-exemplo",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "react": "^16.8.6",
7 | "react-dom": "^16.8.6",
8 | "react-scripts": "3.0.1"
9 | },
10 | "scripts": {
11 | "start": "react-scripts start",
12 | "build": "react-scripts build",
13 | "test": "react-scripts test",
14 | "eject": "react-scripts eject"
15 | },
16 | "eslintConfig": {
17 | "extends": "react-app"
18 | },
19 | "browserslist": {
20 | "production": [
21 | ">0.2%",
22 | "not dead",
23 | "not op_mini all"
24 | ],
25 | "development": [
26 | "last 1 chrome version",
27 | "last 1 firefox version",
28 | "last 1 safari version"
29 | ]
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/05-app-final/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/reprograma/T7-react-I/811d48baf14716bf29d798b7825848d778e73ed1/05-app-final/public/favicon.ico
--------------------------------------------------------------------------------
/05-app-final/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
22 | React App
23 |
24 |
25 |
26 |
27 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/05-app-final/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 |
--------------------------------------------------------------------------------
/05-app-final/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | animation: App-logo-spin infinite 20s linear;
7 | height: 40vmin;
8 | pointer-events: none;
9 | }
10 |
11 | .App-header {
12 | background-color: #282c34;
13 | min-height: 100vh;
14 | display: flex;
15 | flex-direction: column;
16 | align-items: center;
17 | justify-content: center;
18 | font-size: calc(10px + 2vmin);
19 | color: white;
20 | }
21 |
22 | .App-link {
23 | color: #61dafb;
24 | }
25 |
26 | @keyframes App-logo-spin {
27 | from {
28 | transform: rotate(0deg);
29 | }
30 | to {
31 | transform: rotate(360deg);
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/05-app-final/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import logo from './logo.svg';
3 | import './App.css';
4 |
5 | function App() {
6 | return (
7 |
57 | )
58 | }
59 | }
60 |
61 | ReactDOM.render(, document.getElementById('root'));
62 |
63 | // If you want your app to work offline and load faster, you can change
64 | // unregister() to register() below. Note this comes with some pitfalls.
65 | // Learn more about service workers: https://bit.ly/CRA-PWA
66 | serviceWorker.unregister();
67 |
--------------------------------------------------------------------------------
/05-app-final/src/logo.svg:
--------------------------------------------------------------------------------
1 |
8 |
--------------------------------------------------------------------------------
/05-app-final/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # React I - Conteúdo de aula
2 |
3 | > Conteúdo de aula ministrado entre os dias 10/06/2019 a 14/06/2019, sobre fundamentos de React.
4 |
5 |
6 | -----------------
7 |
8 |
9 | ## Issues - como utilizar nesse repositório
10 |
11 | As issues neste repositório podem ser usadas como formas de enviar perguntas e sugestões acerca do assunto da semana de React I. Para fazer a sua pergunta, basta escrever um resumo dela na área do título e uma descrição sobre problema ou dúvida.
12 |
13 | Na descrição, é recomendável ser o mais específica possível. Se possível, colocar **partes do seu código** ou **link para o seu repositório** para referência. Especificar também o navegador utilizado e o tamanho de tela. Para documentação de formatação de textos do Github, acesse esse [link](https://guides.github.com/features/mastering-markdown/).
14 |
15 |
16 | ---------------
17 |
18 | ## Exercícios - Como usar
19 |
20 | Baixe todo este repositório. Caso queira inicializar um dos exercícios, navegue com o `cdm` ou `Git Bash` para a pasta do exercício escolhido. Dentro dela, rode os comandos:
21 | ```javascript
22 | npm install // instalar dependências
23 | npm start // iniciar aplicativo
24 | ```
25 |
26 | -------------
27 |
28 | ## Importante - Documentação oficial
29 | A documentação do React é a sua maior aliada no processo de aprendizagem de React. Ela é detalhada e atualizada. Recentemente, houve uma movimentação para a tradução da documentação para vários idiomas, incluindo o Português do Brasil.
30 |
31 | [Documentação Oficial React - Português BR](https://pt-br.reactjs.org/)
32 |
33 | --------------
34 |
35 | ## Conceitos - O que é React?
36 |
37 | Segundo sua documentação oficial, o React é:
38 | > Uma biblioteca JavaScript para criar interfaces de usuário
39 |
40 | Foi criado por desenvolvedores de software do Facebook e é mantido por uma comunidade ativa. É performático e otimizado para criação de *Single Page Applications* (SPA), ou aplicações de uma página só (tradução livre do inglês). Além disso, é considerada de fácil aprendizagem (baixa curva de aprendizado).
41 |
42 | #### Biblioteca vs. Framework
43 | Há diversas discussões sobre as diferenças entre esses dois conceitos. No nosso caso, vamos levar em consideração as seguintes definições:
44 |
45 | - **Framework**: Conjunto de bibliotecas; toda arquitetura é desenvolvida ao redor do framework.
46 | - **Library**: a arquitetura não é modificada, só chama métodos e elementos conforme a necessidade.
47 |
48 | Em linhas gerais, há a necessidade de pensar toda a estrutura do software antes de implementar um framework. A biblioteca, por outro lado, não é tão invasiva, podendo se adequar à estrutura existente do software.
49 |
50 | -----------------
51 |
52 | ## Setup - O que preciso para começar minha aplicação em React?
53 |
54 | Para o setup manual, vamos precisar de:
55 | - Biblioteca React ([CDN](https://reactjs.org/docs/cdn-links.html));
56 | - Compilador ([Babel](https://babeljs.io/));
57 | - "Simulador" de servidor ([Live-server](https://www.npmjs.com/package/live-server)).
58 |
59 | *Biblioteca React*: precisamos importar para o nosso projeto para desfrutar de todas as funcionalidades dela.
60 |
61 | *Compilador*: por estarmos usando sintaxes e métodos novos, precisamos transformar (ou traduzir) esse código para um que nosso navegador entenda. O compilador faz essa transformação. Para criação do nosso projeto em React, vamos usar o Babel, porém existem outros compiladores, para linguagens diferentes.
62 |
63 | *Servidor*: em algumas situações, o conteúdo será carregado a partir do Javascript e com isso o protocolo `file://` usado para sites estáticos não funciona. Por isso, devemos simular um servidor local, para mudar o protocolo.
64 |
65 | ### Create React App
66 | O setup pode ser demorado e parecer uma perda de tempo. Por isso, foi criado um "atalho". Trata-se do [Create React App](https://facebook.github.io/create-react-app/), um comando que instala todas as dependências necessárias para rodar um aplicativo em React.
67 |
68 | Para instalar, você deve ter o **Node** instalado na sua máquina. Em seguida, dentro da pasta que quer iniciar um projeto, rode o comando:
69 |
70 | ```javascript
71 | npx create-react-app nome-da-pasta
72 | cd nome-da-pasta
73 | npm start
74 | ```
75 |
76 | Será criada uma pasta chamada `noma-da-pasta` dentro do diretório em que você está rodando o comando e lá estará todos os arquivos criados pelo Create React App.
77 |
78 | Toda a documentação e detalhes do que acontece por debaixo dos panos, você pode conferir [neste link](https://facebook.github.io/create-react-app/docs/getting-started).
79 |
80 | --------------
81 |
82 | ## JSX
83 | Em React, conseguimos usar uma sintaxe de Javascript que se chama JSX, ou "Javascript XML" (nome não oficial). É como se colocássemos elementos HTML no Javascript. O uso do JSX não é obrigatório para programarmos em React, porém facilita nosso trabalho.
84 |
85 |
86 | Um exemplo é:
87 | ```JSX
88 | const template =
React na Reprograma
89 | ```
90 | Estamos declarando que `template` é uma constante, que é um objeto em React. Observando a compilação, podemos ver que um método da biblioteca React é chamado:
91 | ```javascript
92 | // const template =
React na Reprograma
93 | var template = React.createElement("h1", null, "React na Reprograma");
94 | ```
95 | E esse método, `React.createElement()` retorna um *objeto* em React. Vale lembrar que...
96 |
97 | > **Tudo** é um objeto em Javascript
98 |
99 | Para quem quiser saber mais sobre JSX, vejam [este link](https://medium.com/reactbrasil/jsx-de6f43b06f41).
100 |
101 |
102 | ### JSX - Funcionalidades
103 |
104 | Sendo uma sintaxe de Javascript, ele também pode ser utilizado com sua lógica. Por exemplo, é possível renderizar variáveis dentro do template HTML. Coloca-se a variável entre `{ }` dentro do template.
105 |
106 | ```JSX
107 | const name = "Jessica"
108 |
109 | const template =
110 |
React App -- Introdução
111 |
Olá, {name}
112 |
113 |
114 | ```
115 |
116 | > Atenção: o retorno do JSX deve conter **1 filho** só. Isso quer dizer que, se houver mais elementos HTML a serem renderizados, você deve englobá-los dentro de um elemento, como em uma div.
117 |
118 | Também há a possibilidade de renderizar o **retorno de uma função**.
119 |
120 | ```JSX
121 | const name = {
122 | primeiroNome: "Jessica",
123 | sobreNome: "Silva"
124 | }
125 |
126 | function formatarNome(nome) {
127 | return nome.primeiroNome + ' ' + nome.sobreNome;
128 | }
129 |
130 | const template =
131 |
React App -- Introdução
132 |
Olá, {formatarNome(name)}
133 |
134 | ```
135 |
136 | Da mesma forma, chamamos a função entre `{ }`, podendo passar parâmetros dentro dela.
137 |
138 | Dentro da função pode haver estruturas lógicas, contanto que se retorne algo, que pode também ser um objeto em React.
139 |
140 | ```JSX
141 | const name = {
142 | primeiroNome: "Jessica",
143 | sobreNome: "Silva"
144 | }
145 |
146 | function formatarNome(nome) {
147 | return nome.primeiroNome + ' ' + nome.sobreNome;
148 | }
149 |
150 | function saudacao(usuaria) {
151 | if (usuaria) {
152 | return
Como está, {formatarNome(usuaria)}?
153 | } else {
154 | return
Como está, desconhecida?
155 | }
156 |
157 | const template =
158 |
React App -- Introdução
159 | {saudacao(name)}
160 |
161 | ```
162 |
163 | ### ReactDOM.render()
164 |
165 | Só declarando a variável não conseguimos fazer com que o elemento apareça na página. Pra isso, devemos usar um método da biblioteca React DOM, que é o `render()`.
166 |
167 | O [ReactDOM.render()](https://pt-br.reactjs.org/docs/react-dom.html#render) é um método que renderiza os elementos indicados dentro de um container.
168 |
169 | Para renderizar o `template` acima criado no nosso navegador, devemos chamar o `render()`
170 |
171 | ```JSX
172 | ReactDOM.render(template, document.getElementById('root'));
173 | ```
174 |
175 | Perceba: o `render()` é um método que recebe **dois** parâmetros: **o que** (elemento ou componente) e **onde** (container ou elemento div, normalmente no index.html na pasta public/) será renderizado.
176 |
177 |
178 | --------------
179 |
180 | ## Elementos
181 | Até agora, estamos criando elementos em React. **Elementos** são *imutáveis*, ou seja, uma vez renderizados, não conseguimos modificar seus atributos e conteúdo.
182 |
183 | [Referência na Documentação - Rendering elements](https://pt-br.reactjs.org/docs/rendering-elements.html)
184 |
185 | Para modificar nossas páginas e conteúdos, utilizamos outras ferramentas do React.
186 |
187 | ---------------
188 |
189 | ## Componentes e Props
190 |
191 | **Componentes** são a parte mais importante do React. React é uma biblioteca de interface e ele lida como se cada pedaço dessa interface fosse um componente. Elas são partes *reutilizáveis* de um todo. Podemos ver uma página sendo dividida em componentes na imagem abaixo:
192 |
193 | 
194 | _Fonte: [Qcode](https://www.qcode.in/learn-react-by-creating-a-comment-app/)_
195 |
196 |
197 | O layout é igual para todas as pessoas, mas as informações, conteúdos ou *propriedades* de cada componente é diferente. O meu nome e meus comentários são customizadas para a minha experiência, ao mesmo tempo que o cabeçalho e outros elementos são iguais para todos os usuários.
198 |
199 | **Qual a diferença então entre Componente e Elemento?**
200 |
201 | Componentes são customizáveis, são compostos por elementos e são reutilizáveis.
202 |
203 | Para criar um Componente, criamos uma função com um parâmetro único, que retorna um elemento React. É isso que define um Componente em React.
204 |
205 | ```JSX
206 | function BemVinda(props) {
207 | return
Hello, {props.nome}
;
208 | }
209 | ```
210 |
211 | > ATENÇÃO: o nome do componente tem que ter **sempre** sua primeira letra maiúscula (por exemplo, **B**emVinda, não bemvinda)
212 |
213 | Essa é a estrutura básica de um componente. De novo, componente em React é definido por:
214 | - Uma **função** (ou classe);
215 | - Recebe um **único parâmetro** (`props`);
216 | - Retorna um **elemento JSX**.
217 |
218 | Para chamar um componente, fazemos como se ele fosse uma "tag" HTML. No exemplo acima, o componente a ser chamado seria:
219 | ```JSX
220 |
221 | ```
222 |
223 | [Referência Documentação - Componentes e Props](https://pt-br.reactjs.org/docs/components-and-props.html)
224 |
225 |
226 | ### Props
227 | `props` é um parâmetro que é um **objeto**, que podemos inserir _propriedades_ e _valores_ que quisermos.
228 |
229 | ```JSX
230 | function BemVinda(props) {
231 | return
Hello, {props.nome}
;
232 | }
233 |
234 | ReactDOM.render(,
240 | appRoot
241 | )
242 | ```
243 |
244 | Para passar `props` para um componente, inserimos a sua _propriedade_ e _valor_ como se fossem "atributos" em HTML. No exemplo acima, é como se estivéssemos passando como `props` para o componente BemVinda:
245 | ```javascript
246 | const props = {
247 | nome: "Mellina",
248 | profissao: "Desenvolvedora Front-End",
249 | apelido: "mell",
250 | comida: "lasanha"
251 | }
252 | ```
253 | Essa `props` não é explicitamente mostrada para nós, mas enviada para o componente nos bastidores.
254 |
255 | Para acessar as _propriedades_ do nosso parâmetro e objeto `props`, usamos a sintaxe para acessar propriedades de um objeto que é `objeto.propriedade`. Se quisermos acessar a propriedade `profissao` da props, escreveríamos `props.profissao`.
256 |
257 | ```JSX
258 | function BemVinda(props) {
259 | return
Olá, {props.nome}, {props.profissao}
;
260 | }
261 |
262 | ReactDOM.render(,
268 | appRoot
269 | )
270 | ```
271 |
272 | > **ATENÇÃO**: componentes em React **NÃO** são elementos HTML. Sua sintaxe foi desenvolvida para parecer com a linguagem HTML, porém não devem ser confundidos.
273 |
274 | ### Componente Classe
275 | Há uma outra forma de declarar um componente, que é por meio de extensão da classe `React.Component`:
276 | ```JSX
277 | class BemVinda extends React.Component {
278 | render() {
279 | return (
280 | return
Olá, {props.nome}, {props.profissao}
;
281 | )
282 | }
283 | }
284 | ```
285 | Quando declaramos dessa forma, temos acesso a vários **métodos** da biblioteca React, sendo que somente o [`render()`](https://pt-br.reactjs.org/docs/react-component.html#render) é obrigatório a ser usado.
286 |
287 |
288 | Isso significa que estamos criando um objeto classe que é filho de React.Component.
289 |
290 | -----------------
291 |
292 | **Quando usar um componente Funcional e quando usar um componente Classe?**
293 |
294 | Os componentes **funcionais** também são chamados de **_Stateless Components_**, ou _componentes sem estado_.
295 |
296 | Os componentes de **classe** também são chamados de **_Stateful Components_**, ou _componentes com estados_.
297 |
298 | Entraremos no tópico de **states ou estados** em breve, mas já adiantando que, apesar de não haver regras para criar um componente funcional ou de classe, há uma condição que definir um componente classe é **obrigatório**: se esse componente tem estado ou *state*.
299 |
300 | -----------
301 |
302 | ## Estados e eventos
303 | Estados ou states são como props, porém são **atualizáveis e controladas pelo componente e privadas**. _States_ são objetos.
304 |
305 | [Referência Documentação - State e Lifecyle](https://pt-br.reactjs.org/docs/state-and-lifecycle.html)
306 |
307 | Como antes citado, _states_ só existem dentro de componentes de classe. Para criar _states_, devemos defini-las dentro do _constructor()_ da nossa Classe.
308 |
309 | ```JSX
310 | class EscondeAparece extends React.Component {
311 | constructor(props){
312 | super(props);
313 | this.state = {
314 | visibilidade: true
315 | }
316 | }
317 | render() {
318 | return (
319 |
320 |
Esconde-Aparece
321 | {this.state.visibilidade ?
Voces sao maravilhosas
: ''}
322 |
323 | )
324 | }
325 | ```
326 |
327 | O _constructor()_ é um método nativo da classe que é chamado antes de criar o componente. Um estado não é passado de mãe pra filha, como acontece com _props_ - ele é definido, criado e manipulado dentro do próprio componente. Por esse motivo, dizemos que um estado é _privado_.
328 |
329 | > Saber o que é uma Classe em Javascript é importante para entender a estrutura do React. Para saber mais, leia na [documentação do MDN sobre Classes](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Classes).
330 |
331 |
332 | ### Eventos e o setState()
333 |
334 | Para modificar um estado, é preciso chamar um método especial, o `setState()`. Ele recebe um parâmetro que é uma função, que deve retornar o novo valor do estado, ou seja um _objeto_.
335 |
336 | Essa função pode receber um parâmetro, que é o **estado no momento que a mudança é aplicada**, ou o **estado anterior**.
337 |
338 | ```javascript
339 | setState((estadoAnterior) => {
340 | return { estadoUm: estadoAnterior.estadoUm + 1 } )
341 | }
342 | ```
343 |
344 | [Referência Documentação - setState()](https://pt-br.reactjs.org/docs/react-component.html#setstate)
345 |
346 | O `setState()` pode ser chamado dentro de um outr método, definido dentro do nosso componente Classe. No nosso exemplo, podemos criar um método para modificar o estado de visibilidade do componente `EscondeAparece`.
347 |
348 | ```JSX
349 | mudarVisibilidade = () => {
350 | this.setState((estadoAnterior) => (
351 | { visibilidade: !estadoAnterior.visibilidade }
352 | )
353 | )
354 | }
355 | ```
356 |
357 | Toda vez que o `mudarVisibilidade()` for chamado, ele mudará o estado do componente.
358 |
359 | O que resta é conectar essa ação (método) com um gatilho (evento).
360 |
361 | [Referência Documentação - Eventos](https://pt-br.reactjs.org/docs/handling-events.html)
362 |
363 | A maneira como o React lida com eventos é bem parecido com os _eventos inline_. No componente que queremos inserir um escutador de evento (_event listener_), inserimos o evento e a função que é acionada, como se fossem "atributos" deste componente.
364 |
365 | ```JSX
366 |