digital-ocean-tutorial/src/App.
js
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
export default App;
Change the contents of the <p> tag from Edit <code>src/App.js</code> and save to re
load. to Hello, world and save your changes.
digital-ocean-tutorial/src/App.js
...
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Hello, world
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
...
Head over to your browser and you’ll see the change:
React app with “Hello, world” in paragraph tag
You’ve now made your first update to a React component.
Before you go, notice a few more things. In this component, you import the logo.svg file
and assign it to a variable. Then in the <img> element, you add that code as the src .
There are a few things going on here. Look at the img element:
digital-ocean-tutorial/src/App.js
...
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Hello, world
</p>
...
Notice how you pass the logo into curly braces. Anytime you are passing attributes that
are not strings or numbers, you need to use the curly braces. React will treat those as
JavaScript instead of strings. In this case, you are not actually importing the image; instead
you are referencing the image. When Webpack builds the project it will handle the image
and set the source to the appropriate place.
Exit the text editor.
If you look at the DOM elements in your browser, you’ll see it adds a path. If you are
using Chrome, you can inspect the element by right-clicking the element and selecting
Inspect.
Here’s how it would look in the browser:
Inspecting element with chrome dev tools
The DOM has this line:
<img src="/static/media/logo.5d5d9eef.svg" class="App-logo" alt="logo">
Your code will be slightly different since the logo will have a different name. Webpack
wants to make sure the image path is unique. So even if you import images with the same
name, they will be saved with different paths.
At this point, you’ve made a small change to the React JavaScript code. In the next step,
you’ll use the build command to minify the code into a small file that can be deployed to
a server.
Step 6 — Building the Project
In this step, you will build the code into a bundle that can be deployed to external servers.
Head back to your terminal and build the project. You ran this command before, but as a
reminder, this command will execute the build script. It will create a new directory with
the combined and minified files. To execute the build, run the following command from
the root of your project:
npm run build
There will be a delay as the code compiles and when it’s finished, you’ll have a new
directory called build/ .
Open up build/index.html in a text editor.
nano build/index.html
You will see something like this:
digital-ocean-tutorial/build/index.html
<!doctype html><html lang="en"><head><meta charset="utf-8"/><link rel="ico
n" href="/favicon.ico"/><meta name="viewport" content="width=device-width,i
nitial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="de
scription" content="Web site created using create-react-app"/><link rel="ap
ple-touch-icon" href="/logo192.png"/><link rel="manifest" href="/manifest.j
son"/><title>React App</title><link href="/static/css/main.d1b05096.chunk.c
ss" rel="stylesheet"></head><body><noscript>You need to enable JavaScript t
o run this app.</noscript><div id="root"></div><script>!function(e){functio
n r(r){for(var n,a,p=r[0],l=r[1],c=r[2],i=0,s=[];i<p.length;i++)a=p[i],Obje
ct.prototype.hasOwnProperty.call(o,a)&&o[a]&&s.push(o[a][0]),o[a]=0;for(n i
n l)Object.prototype.hasOwnProperty.call(l,n)&&(e[n]=l[n]);for(f&&f(r);s.le
ngth;)s.shift()();return u.push.apply(u,c||[]),t()}function t(){for(var e,r
=0;r<u.length;r++){for(var t=u[r],n=!0,p=1;p<t.length;p++){var l=t[p];0!==o
[l]&&(n=!1)}n&&(u.splice(r--,1),e=a(a.s=t[0]))}return e}var n={},o={1:0},u=
[];function a(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:
{}};return e[r].call(t.exports,t,t.exports,a),t.l=!0,t.exports}a.m=e,a.c=n,
a.d=function(e,r,t){a.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:
t})},a.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Objec
t.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProper
ty(e,"__esModule",{value:!0})},a.t=function(e,r){if(1&r&&(e=a(e)),8&r)retur
n e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.creat
e(null);if(a.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:
e}),2&r&&"string"!=typeof e)for(var n in e)a.d(t,n,function(r){return e
[r]}.bind(null,n));return t},a.n=function(e){var r=e&&e.__esModule?function
(){return e.default}:function(){return e};return a.d(r,"a",r),r},a.o=functi
on(e,r){return Object.prototype.hasOwnProperty.call(e,r)},a.p="/";var p=thi
s["webpackJsonpdo-create-react-app"]=this["webpackJsonpdo-create-react-ap
p"]||[],l=p.push.bind(p);p.push=r,p=p.slice();for(var c=0;c<p.length;c++)r
(p[c]);var f=l;t()}([])</script><script src="/static/js/2.c0be6967.chunk.j
s"></script><script src="/static/js/main.bac2dbd2.chunk.js"></script></body
></html>
The build directory takes all of your code and compiles and minifies it into the smallest
usable state. It doesn’t matter if a human can read it, since this is not a public-facing piece
of code. Minifying like this will make the code take up less space while still allowing it to
work. Unlike some languages like Python, the whitespace doesn’t change how the
computer interprets the code.
Conclusion
In this tutorial, you have created your first React application, configuring your project
using JavaScript build tools without needing to go into the technical details. That’s the
value in Create React App: you don’t need to know everything to get started. It allows you
to ignore the complicated build steps so you can focus exclusively on the React code.
You’ve learned the commands to start, test, and build a project. You’ll use these
commands regularly, so take note for future tutorials. Most importantly, you updated your
first React component.
If you would like to see React in action, try our How To Display Data from the
DigitalOcean API with React tutorial.
How To Create React Elements with JSX
Written by Joe Morgan
The author selected Creative Commons to receive a donation as part of the
Write for DOnations program.
In this tutorial, you’ll learn how to describe elements with JSX. JSX is an
abstraction that allows you to write HTML-like syntax in your JavaScript
code and will enable you to build React components that look like standard
HTML markup. JSX is the templating language of React elements, and is
therefore the foundation for any markup that React will render into your
application.
Since JSX enables you to also write JavaScript in your markup, you’ll be
able to take advantage of JavaScript functions and methods, including array
mapping and short-circuit evaluation for conditionals.
As part of the tutorial, you’ll capture click events on buttons directly in the
markup and catch instances when the syntax does not match exactly to
standard HTML, such as with CSS classes. At the end of this tutorial, you’ll
have a working application that uses a variety of JSX features to display a
list of elements that have a built-in click listener. This is a common pattern
in React applications that you will use often in the course of learning the
framework. You’ll also be able to mix standard HTML elements along with
JavaScript to see how React gives you the ability to create small, reusable
pieces of code.
Prerequisites
You will need a development environment running Node.js; this
tutorial was tested on Node.js version 10.19.0 and npm version 6.13.4.
To install this on macOS or Ubuntu 18.04, follow the steps in How to
Install Node.js and Create a Local Development Environment on
macOS or the Installing Using a PPA section of How To Install
Node.js on Ubuntu 18.04.
You will need to be able to create apps with Create React App. You can
find instructions for installing an application with Create React App at
How To Set Up a React Project with Create React App.
You will also need a basic knowledge of JavaScript, which you can
find in How To Code in JavaScript, along with a basic knowledge of
HTML and CSS. A good resource for HTML and CSS is the Mozilla
Developer Network.
Step 1 — Adding Markup to a React Element
As mentioned earlier, React has a special markup language called JSX. It is
a mix of HTML and JavaScript syntax that looks something like this:
<div>
{inventory.filter(item => item.available).map(item => (
<Card>
<div className="title"}>{item.name}</div>
<div className="price">{item.price}</div>
</Card>
))
</div>
You will recognize some JavaScript functionality such as .filter and .map,
as well as some standard HTML like <div> . But there are other parts that
look like both HTML and JavaScript, such as <Card> and className .
This is JSX, the special markup language that gives React components the
feel of HTML with the power of JavaScript.
In this step, you’ll learn to add basic HTML-like syntax to an existing React
element. To start, you’ll add standard HTML elements into a JavaScript
function, then see the compiled code in a browser. You’ll also group
elements so that React can compile them with minimal markup leaving
clean HTML output.
To start, make a new project. On your command line run the following
script to install a fresh project using create-react-app :
npx create-react-app jsx-tutorial
After the project is finished, change into the directory:
cd jsx-tutorial
In a new terminal tab or window, start the project using the Create React
App start script. The browser will autorefresh on changes, so leave this
script running the whole time that you work:
npm start
You will get a running local server. If the project did not open in a browser
window, you can find it at http://localhost:3000/. If you are running this
from a remote server, the address will be http://your_IP_address:3000 .
Your browser will load with a React application included as part of Create
React App.
React template project
You will be building a completely new set of custom components, so you’ll
need to start by clearing out some boilerplate code so that you can have an
empty project. To start open App.js in a text editor. This is the root
component that is injected into the page. All components will start from
here.
In a new terminal, move into the project folder and open src/App.js with
the following command:
nano src/App.js
You will see a file like this:
jsx-tutorial/src/App.js
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Now, delete the line import logo from './logo.svg and everything after
the return statement in the function. Change it to return null . The final
code will look like this:
jsx-tutorial/src/App.js
import React from 'react';
import './App.css';
function App() {
return null;
export default App;
Save and exit the text editor.
Finally, delete the logo. In the terminal window type the following
command:
rm src/logo.svg
You won’t be using this SVG file in your application, and you should
remove unused files as you work. It will better organize your code in the
long run.
Now that these parts of your project are removed, you can move on to
exploring the facets of JSX. This markup language is compiled by React
and eventually becomes the HTML you see on a web page. Without going
too deeply into the internals, React takes the JSX and creates a model of
what your page will look like, then creates the necessary elements and adds
them to the page.
What that means is that you can write what looks like HTML and expect
that the rendered HTML will be similar. However, there are a few catches.
First, if you look at the tab or window running your server, you’ll see this:
Output
...
./src/App.js
Line 1:8: 'React' is defined but never used no-unused-vars
...
That’s the linter telling you that you aren’t using the imported React code.
When you add the line import React from 'react' to your code, you are
importing JavaScript code that converts the JSX to React code. If there’s no
JSX, there’s no need for the import.
Let’s change that by adding a small amount of JSX. Start by replacing null
with a Hello, World example:
jsx-tutorial/src/App.js
import React from 'react';
import './App.css';
function App() {
return <h1>Hello, World</h1>;
export default App;
Save the file. If you look at the terminal with the server running, the
warning message will be gone. If you visit your browser, you will see the
message as an h1 element.
browser screen showing “Hello, World”
Next, below the <h1> tag, add a paragraph tag that contains the string I am
writing JSX . The code will look like this:
jsx-tutorial/src/App.js
import React from 'react';
import './App.css';
function App() {
return(
<h1>Hello, World</h1>
<p>I am writing JSX</p>
export default App;
Since the JSX spans multiple lines, you’ll need to wrap the expression in
parentheses.
Save the file. When you do you’ll see an error in the terminal running your
server:
Output
./src/App.js
Line 7:5: Parsing error: Adjacent JSX elements must be wrap
ped in an enclosing tag. Did you want a JSX fragment <>...</>?
5 | return(
6 | <h1>Hello, World</h1>
> 7 | <p>I am writing JSX</p>
| ^
8 | )
9 | }
10 |
When you return JSX from a function or statement, you must return a single
element. That element may have nested children, but there must be a single
top-level element. In this case, you are returning two elements.
The fix is a small code change. Surround the code with an empty tag. An
empty tag is an HTML element without any words. It looks like this: <>
</> .
Go back to ./src/App.js in your editor and add the empty tag: