0% found this document useful (0 votes)
15 views20 pages

How To Code in React - Js 3

pages 21-40

Uploaded by

brokenwallnut
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views20 pages

How To Code in React - Js 3

pages 21-40

Uploaded by

brokenwallnut
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Start the project by typing the following command in the root of your project.

For this
tutorial, the root of your project is the digital-ocean-tutorial directory. Be sure to open
this in a separate terminal or tab, because this script will continue running as long as you
allow it:

npm start

You’ll see some placeholder text for a brief moment before the server starts up, giving this
output:

Output
Compiled successfully!

You can now view digital-ocean-tutorial in the browser.

http://localhost:3000

Note that the development build is not optimized.

To create a production build, use npm run build.

If you are running the script locally, it will open the project in your browser window and
shift the focus from the terminal to the browser.

If that doesn’t happen, you can visit http://localhost:3000/ to see the site in action. If
you already happen to have another server running on port 3000 , that’s fine. Create React
App will detect the next available port and run the server with that. In other words, if you
already have one project running on port 3000 , this new project will start on port 3001 .

If you are running this from a remote server you can still see your site without any
additional configuration. The address will be http://your_server_ip:3000 . If you have a
firewall configured, you’ll need to open up the port on your remote server.
In the browser, you will see the following React template project:

React template project

As long as the script is running, you will have an active local server. To stop the script,
either close the terminal window or tab or type CTRL+C or ⌘-+c in the terminal window or
tab that is running your script.

At this point, you have started the server and are running your first React code. But before
you make any changes to the React JavaScript code, you will see how React renders to the
page in the first place.

Step 4 — Modifying the Homepage

In this step, you will modify code in the public/ directory. The public directory contains
your base HTML page. This is the page that will serve as the root to your project. You will
rarely edit this directory in the future, but it is the base from which the project starts and a
crucial part of a React project.

If you cancelled your server, go ahead and restart it with npm start , then open public/ in
your favorite text editor in a new terminal window:
nano public/

Alternatively, you can list the files with the ls command:

ls public/

You will see a list of files such as this:

Output
favicon.ico

logo192.png

manifest.json

index.html

logo512.png

robots.txt

favicon.ico , logo192.png , and logo512.png are icons that a user would see either in the
tab of their browser or on their phone. The browser will select the proper-sized icons.
Eventually, you’ll want to replace these with icons that are more suited to your project.
For now, you can leave them alone.

The manifest.json is a structured set of metadata that describes your project. Among
other things, it lists which icon will be used for different size options.

The robots.txt file is information for web crawlers. It tells crawlers which pages they
are or are not allowed to index. You will not need to change either file unless there is a
compelling reason to do so. For instance, if you wanted to give some users a URL to
special content that you do not want easily accessible, you can add it to robots.txt and it
will still be publicly available, but not indexed by search engines.

The index.html file is the root of your application. This is the file the server reads, and it
is the file that your browser will display. Open it up in your text editor and take a look.
If you are working from the command line, you can open it with the following command:

nano public/index.html

Here’s what you will see:


digital-ocean-tutorial/public/index.html
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />

<meta name="viewport" content="width=device-width, initial-scale=1" />

<meta name="theme-color" content="#000000" />

<meta

name="description"

content="Web site created using create-react-app"

/>

<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />

<!--

manifest.json provides metadata used when your web app is installed on a


user's mobile device or desktop.

See https://developers.google.com/web/fundamentals/web-app-manifest/

-->

<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

<!--

Notice the use of %PUBLIC_URL% in the tags above.

It will be replaced with the URL of the `public` folder during the build.

Only files inside the `public` folder can be referenced from the HTML.

Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will

work correctly both with client-side routing and a non-root public URL.

Learn how to configure a non-root public URL by running `npm run build`.

-->

<title>React App</title>

</head>

<body>
<noscript>You need to enable JavaScript to run this app.</noscript>

<div id="root"></div>

<!--

This HTML file is a template.

If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.

The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.

To create a production bundle, use `npm run build` or `yarn build`.

-->

</body>

</html>

The file is pretty short. There are no images or words in the <body> . That’s because React
builds the entire HTML structure itself and injects it with JavaScript. But React needs to
know where to inject the code, and that’s the role of index.html .

In your text editor, change the <title> tag from React App to Sandbox :
digital-ocean-tutorial/public/index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />

<meta name="viewport" content="width=device-width, initial-scale=1" />

<meta name="theme-color" content="#000000" />

...

<title>Sandbox</title>

</head>

<body>

<noscript>You need to enable JavaScript to run this app.</noscript>

<div id="root"></div>

<!--

This HTML file is a template.

If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.

The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.

To create a production bundle, use `npm run build` or `yarn build`.

-->

</body>

</html>

Save and exit your text editor. Check your browser. The title is the name located on the
browser tab. It will update automatically. If not, refresh the page and notice the change.
Now go back to your text editor. Every React project starts from a root element. There can
be multiple root elements on a page, but there needs to be at least one. This is how React
knows where to put the generated HTML code. Find the element <div id="root"> . This is
the div that React will use for all future updates. Change the id from root to base :

digital-ocean-tutorial/public/index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

...

<body>

<noscript>You need to enable JavaScript to run this app.</noscript>

<div id="base"></div>

<!--

This HTML file is a template.

If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.

The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.

To create a production bundle, use `npm run build` or `yarn build`.

-->

</body>

</html>

Save the changes.

You will see an error in your browser:


Error message saying “Target container is not a DOM elem
ent”

React was looking for an element with an id of root . Now that it is gone, React can’t
start the project.

Change the name back from base to root :


digital-ocean-tutorial/public/index.html

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8" />

...

<body>

<noscript>You need to enable JavaScript to run this app.</noscript>

<div id="root"></div>

<!--

This HTML file is a template.

If you open it directly in the browser, you will see an empty page.

You can add webfonts, meta tags, or analytics to this file.

The build step will place the bundled scripts into the <body> tag.

To begin the development, run `npm start` or `yarn start`.

To create a production bundle, use `npm run build` or `yarn build`.

-->

</body>

</html>

Save and exit index.html .

At this point, you’ve started the server and made a small change to the root HTML page.
You haven’t yet changed any JavaScript code. In the next section, you will update the
React JavaScript code.

Step 5 — Modifying the Heading Tag and Styling


In this step, you will make your first change to a React component in the src/ directory.
You’ll make a small change to the CSS and the JavaScript code that will automatically
update in your browser using the built-in hot reloading.

If you stopped the server, be sure to restart it with npm start . Now, take some time to see
the parts of the src/ directory. You can either open the full directory in your favorite text
editor, or you can list out the project in a terminal with the following command:

ls src/

You will see the following files in your terminal or text editor.

Output
App.css

App.js

App.test.js

index.css

index.js

logo.svg

serviceWorker.js

setupTests.js

Let’s go through these files one at a time.

You will not spend much time with the serviceWorker.js file at first, but it can be
important as you start to make progressive web applications. The service worker can do
many things including push notifications and offline caching, but for now it’s best to leave
it alone.

The next files to look at are setupTests.js and App.test.js . These are used for test files.
In fact, when you ran npm test in Step 2, the script ran these files. The setupTests.js
file is short; all it includes is a few custom expect methods. You’ll learn more about these
in future tutorials in this series.

Open App.test.js :

nano src/App.test.js

When you open it, you’ll see a basic test:

digital-ocean-tutorial/src/App.test.js

import React from 'react';

import { render } from '@testing-library/react';

import App from './App';

test('renders learn react link', () => {

const { getByText } = render(<App />);

const linkElement = getByText(/learn react/i);

expect(linkElement).toBeInTheDocument();

});

The test is looking for the phrase learn react to be in the document. If you go back to
the browser running your project, you’ll see the phrase on the page. React testing is
different from most unit tests. Since components can include visual information, such as
markup, along with logic for manipulating data, traditional unit tests do not work as easily.
React testing is closer to a form of functional or integration testing.

Next, you’ll see some styling files: App.css , index.css , and logo.svg . There are
multiple ways of working with styling in React, but the easiest is to write plain CSS since
that requires no additional configuration.
There are multiple CSS files because you can import the styles into a component just like
they were another JavaScript file. Since you have the power to import CSS directly into a
component, you might as well split the CSS to only apply to an individual component.
What you are doing is separating concerns. You are not keeping all the CSS separate from
the JavaScript. Instead you are keeping all the related CSS, JavaScript, markup, and
images grouped together.

Open App.css in your text editor. If you are working from the command line, you can
open it with the following command:

nano src/App.css

This is the code you’ll see:


digital-ocean-tutorial/src/App.css

.App {

text-align: center;

.App-logo {

height: 40vmin;

pointer-events: none;

@media (prefers-reduced-motion: no-preference) {

.App-logo {

animation: App-logo-spin infinite 20s linear;

.App-header {

background-color: #282c34;

min-height: 100vh;

display: flex;

flex-direction: column;

align-items: center;

justify-content: center;

font-size: calc(10px + 2vmin);

color: white;

.App-link {

color: #61dafb;

}
@keyframes App-logo-spin {

from {

transform: rotate(0deg);

to {

transform: rotate(360deg);

This is a standard CSS file with no special CSS preprocessors. You can add them later if
you want, but at first, you only have plain CSS. Create React App tries to be
unopinionated while still giving an out-of-the-box environment.

Back to App.css , one of the benefits of using Create React App is that it watches all files,
so if you make a change, you’ll see it in your browser without reloading.

To see this in action make a small change to the background-color in App.css . Change it
from #282c34 to blue then save the file. The final style will look like this:
digital-ocean-tutorial/src/App.css

.App {

text-align: center;

...

.App-header {

background-color: blue

min-height: 100vh;

display: flex;

flex-direction: column;

align-items: center;

justify-content: center;

font-size: calc(10px + 2vmin);

color: white;

...

@keyframes App-logo-spin {

from {

transform: rotate(0deg);

to {

transform: rotate(360deg);

Check out your browser. Here’s how it looked before:


React app with dark background

Here’s how it will look after the change:

React app with blue background

Go ahead and change background-color back to #282c34 .


digital-ocean-tutorial/src/App.css

.App {

text-align: center;

...

.App-header {

background-color: #282c34

min-height: 100vh;

display: flex;

flex-direction: column;

align-items: center;

justify-content: center;

font-size: calc(10px + 2vmin);

color: white;

...

@keyframes App-logo-spin {

from {

transform: rotate(0deg);

to {

transform: rotate(360deg);

Save and exit the file.


You’ve made a small CSS change. Now it’s time to make changes to the React JavaScript
code. Start by opening index.js .

nano src/index.js

Here’s what you’ll see:

digital-ocean-tutorial/src/index.js

import React from 'react';

import ReactDOM from 'react-dom';

import './index.css';

import App from './App';

import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change

// unregister() to register() below. Note this comes with some pitfalls.

// Learn more about service workers: https://bit.ly/CRA-PWA

serviceWorker.unregister();

At the top, you are importing React , ReactDOM , index.css , App , and serviceWorker . By
importing React , you are actually pulling in code to convert JSX to JavaScript. JSX are
the HTML-like elements. For example, notice how when you use App , you treat it like an
HTML element <App /> . You’ll explore this more in future tutorials in this series.

ReactDOM is the code that connects your React code to the base elements, like the index.h

tml page you saw in public/ . Look at the following highlighted line:
digital-ocean-tutorial/src/index.js

...

import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />,document.getElementById('root'));

...

serviceWorker.unregister();

This code instructs React to find an element with an id of root and inject the React code
there. <App/> is your root element, and everything will branch from there. This is the
beginning point for all future React code.

At the top of the file, you’ll see a few imports. You import index.css , but don’t actually
do anything with it. By importing it, you are telling Webpack via the React scripts to
include that CSS code in the final compiled bundle. If you don’t import it, it won’t show
up.

Exit from src/index.js .

At this point, you still haven’t seen anything that you are viewing in your browser. To see
this, open up App.js :

nano src/App.js

The code in this file will look like a series of regular HTML elements. Here’s what you’ll
see:

You might also like