0% found this document useful (0 votes)
140 views

A Complete Quickstart To React For Dummies - by Explore Hacks - JavaScript in Plain English

A Complete Quickstart to React for Dummies _ by Explore Hacks _ JavaScript in Plain English

Uploaded by

M052221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views

A Complete Quickstart To React For Dummies - by Explore Hacks - JavaScript in Plain English

A Complete Quickstart to React for Dummies _ by Explore Hacks _ JavaScript in Plain English

Uploaded by

M052221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Get unlimited access to the best of Medium for less than $1/week.

Become a member

A Complete Quickstart to React for


Dummies
Explore Hacks · Follow
Published in JavaScript in Plain English · 17 min read · Jun 8, 2021

108

Prerequisites With Links To External Resources:


HTML, CSS, & JavaScript
Intro to HTML & CSS - Tutorial

Learn JavaScript - Full Course for Beginners

Bash Shell Commands:


Beginner's Guide to the Bash Terminal

What Exactly Is React JS and Why Is It Powerful?


React JS is a JavaScript front-end framework that allows web developers to
reuse traditional HTML code using components, to keep the code clean,
dynamic, and fast. This framework is declarative, allowing you to
automatically update your components according to changes in data. React
JS can also help you make a faster website given that it leverages the concept
of having a Single Paged Application (SPA). To learn more about SPA, you can
refer to the article here:

A Comparison of Single-Page and Multi-Page Applications -


DZone Web Dev
There are millions of web applications that help companies deliver
their goods and services, connect with customers…
dzone.com
Who Uses ReactJS?

An agglomeration of very prominent businesses leverage the versatility and


power of React; large-scale firms including Netflix, Tesla, and Khan
Academy, make use of this framework. In this article, we’ll be going over
some important concepts in React as we apply what we learn to create a to-
do list website.

Download All Dependencies


The first dependency that we’re going to need to install is Node.js which
allows your computer to run JavaScript code locally. When you download
Node.js, it includes a convenient package manager called npm which allows
us to utilize bits of code that other developers have already written instead of
writing everything from scratch ourselves.

To download Node.js, go to https://nodejs.org/en/ and download the latest


version of Node.js.

After Node.js is installed, open up your terminal and make sure that both
Node.js and npm were installed. To check this, simply type:
node -v
npm -v

If these two lines run and show you the correct version of both npm and
Node.js, you’re all set!

Setting Up The Project


Now that you have npm installed, open up your terminal again and type:

npx create-react-app <application name>

This command initializes and creates a React Application with boilerplate


code.

npx create-react-app demo

Run the command above in your terminal. Following the command, open up
your new React Project in the IDE of your choice.
When you open the folder, you’ll see three main folders:

node_modules

public

src

The node_modules folder contains all the dependencies your project relies
on; the public folder simply holds items that you will sometimes need in
your websites such as images or favicons.
The src folder is where we will keep all our JSX Components, which I’ll cover
more extensively later.
The most important item in the public folder is the index.html file, this is
where we will render our JSX Components. As a final note, you will see a
package.json file towards the bottom of your page, which basically holds
important information for your application, such as dependencies and
scripts.
Before we actually begin coding, feel free to delete all of the files in the
public folder other than the index.html and manifest.json; you can also
delete all the files in the src folder other than App.css, App.js, and index.js.

Open in app

Search Write
Understanding the Structure of a ReactJS Project
If you open up index.html, you’ll see that there’s not much other than a div at
the bottom of the page with an id = “root”. This seemingly insignificant fact
is absolutely integral for ReactJS to work properly. Awe will insert the JSX
Components that we need into the div to render in our other JavaScript files.
JSX is a statically-typed language that allows us to write HTML code in react
JSX Components are functions that return HTML code. They can be used to
represent an object on your website that gets frequently rendered, allowing
us to avoid the repetition of code.
Root div from index.html

In index.js, you’ll see that React is being imported in the index.js along with
the ReactDOM. The ReactDOM (React Document Object Model) is necessary
to render the respective JSX Components of your choice; this is done in the
ReactDOM.render function. The second parameter to this function simply
dictates where the Component(s) should be inserted, which is the “root” div.
In this case, the rendered React Component is App. You’ll need to delete the
line where you import reportWebVitals since we deleted that file earlier. The
<React.StrictMode> in the render function, surrounding the App component,
tells React to add extra developer warnings for your application.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

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

Furthermore, in index.js you can see that “App” is being imported from a
local App file and being rendered in the ReactDOM.render() function; if we
go to that App.js file and look at its contents, we can see that a function, App,
returns a div containing some HTML. App.js is essentially creating a
component that can be imported and used in other files. Each JSX
component must have a function in it that returns some HTML to describe
that component and is later exported as seen on the bottom of the App.js
file. By convention, the name of this function is the name of the file. When I
go to use this component, all I have to do is import the App file as seen in
index.js, and type <App /> where I want my App component’s HTML to show
up. While you’re on App.js, remove the img tag in the return statement of
App.js and the logo.svg import, since we deleted that file.

An important thing to note here is that every component’s function can only
return one “block” of HTML.

If you don’t want to add an extra div to the DOM by wrapping everything in a
div, you can use React Fragments.
React Fragments

To run our app on a local server and see all of our changes, open up your
terminal and run the following command:

npm start

Building a Simple To-Do List Application (Setup):


Now that we have a quick introduction to React, I can walk you through an
example with ReactJS while introducing some more complex features of
ReactJS.

First off, I will not be going over the CSS of the project to focus on the React
side of the website. Feel free to read/download the CSS and refer to my React
code from my CodeSandbox here:
https://codesandbox.io/s/to-do-list-frq2q?file=/src/components/Input.js

Second of all, create folders inside your project’s src folder named
“Components” and “Css”. Drag all of the files in src, except index.js, into
their respective folders; this will keep your code organized. Following this
change, you may need to tweak your import statements from each of your
JavaScript files.

Finally, before we begin, remove all of the HTML code inside App.js’s return
method, except for the div. Then, change the className of the div to just
“app” for the CSS in the Code Sandbox to properly show.

Building a Simple To-Do List Application (The Note


Component):
The first step in creating any ReactJS application is to thoroughly think about
what components, or items in your website, that you need. I find it helpful to
draw out what I want my application to look like and then draw boxes around
each specific item I want on my website. In the case of a messaging
application, a typical component you might have is a message.

Drawing of a website

For a To-Do List application, I thought that a note component would be


necessary so that I didn’t write repetitive code; this would be the HTML
which had both a checkbox and a corresponding text. Thus, create a new
JavaScript file called “Note.js” inside the Components folder and import
React and its respective CSS file from the CSS folder. As a side note, by
convention, the name of your component should be capitalized.
Since each note should act like a div with both a check mark and some text,
I’ve made my Note function return exactly that, but instead of needing to
code an entire checkbox on my own, I decided to use npm, the package
manager we’ve installed, to simply download and import a checkbox.

To download this checkbox, we’ll need to open up our terminal again and
type (“i” is short for install):

npm i @material-ui/core

to install a module with premade UI components. To use the checkbox, we


simply have to add this import into our Note.js file:

import { Checkbox } from '@material-ui/core';

After we installed @material-ui/core into our application, npm added the


dependency into our package.json.
package.json

Now, we can just type <Checkbox /> in our div inside the Note function.
However, since we also need to have some text next to it, I’ll add an <h3> in
the div.

Finally, I’ll add this line of code to the bottom of my Note.js file so that I can
export my Note component to anyone who wants to import and use it.

export default Note;


This will be the base of our Note component. If you want to see what the
Note component looks like, simply go to the App.js file and import the Note
component we just made so that you can put it into App.js’s return
statement.

So now if you take a look at your React application, you’ll see that our
application looks something like this.
So now that we have a base structure for our Note, we should create another
component for the place where we can type a new note. I’ll be calling this
component, Input.

Building a Simple To-Do List Application (The Input


Component):
As we did earlier, I’ll create a new JavaScript file called Input.js which will
hold all the code I need for that component. We’ll also import React and our
Input.css

Hopefully, this is starting to become routine, but now I’ll create a function
named Input, which will return the HTML code that I want as a component.
Finally, I’ll type

export default Input;

at the bottom of the file to allow other files that import Input to have access
to its returned HTML.

Since I essentially want to have an HTML form to handle the input I get from
the user, I’ll add that into the return statement of my Input function,
surrounded by a div with a class name of “input”, for my CSS to target.

After adding in a couple more ids for my CSS, my resulting Input file looks
like the following:
Input.js
To add a “title” to this App, I can just add an <h1> in my App.js file on top of
both my Note and Input components. This will leave me with an App.js file
like this:
and an overall application looking very close to our final result:
Event Listeners
we need to store the value that is typed into the input tag. To do this, we can
add an “onChange” event listener to our input so that we can always keep
track of the value inside of the input tag. Moreover, we’ll need to handle what
happens when we press the submit button so I’ll add an “onSubmit” event
listener for the HTML form. I’ll need to pass in a function as the value for
these event listeners so that I’ll be able to execute whatever code I want
when those particular events occur. Here’s what adding those two changes
will look like:

Input.js

Every time I type something new inside my input tag, thehandleChange


function will be called, and anytime a user presses the submit button, the
handleSubmisson function will be called.

The curly braces around the event handlers allows JSX to interpret the code
within it as JavaScript.

React Props
To answer the question of what to put into these two functions, we must first
talk about React Props, React Hooks, and the event parameter.
Understanding these three topics are integral to developing any React
Application.
To introduce React Props, I’ll utilize a hopefully familiar bit of code.

Here, I’m simply creating an image in HTML with some properties such as:
src, alt, width, and height. This is essentially what React Props are built off
of; let us say that I wanted to pass in my own property called msg to my Note
component. How would I do that, and how would I get hold of the property
that was passed to my component?

To do the first part of the question, you would need to type the name of your
property and set that equal to the value of your choice while inside the
angular brackets of your custom ReactJS Component.
Addressing the latter question, I can pass a parameter into my Note function
called props, which will hold the key-value pairs of the passed-in properties
by default.

To show that React Props work, I’ve decided to set the text inside my Note
Component’s <h3> to the msg property that was passed into the Note
Component when it was used in App.
The final thing to remember about React Props is that you don’t need to
always pass in primitive data types into your React component; you can pass
in anything from an object to a function. We’ll leverage this fact later in our
Input.js after we cover React Hooks and the event parameter.
React Hooks
So what is a React Hook? From a top-level view, a React Hook is just a
function that allows you to “hook into” React’s current states and update
them. States in ReactJS are essentially just variables that keep track of
important pieces of information that need to be passed between
components.

By using React Hooks to manipulate states, you trigger a re-render of the


component it’s being used in automatically. In the case of our To-Do List
application, if you just had a variable where you held an array of notes, and
just pushed every time someone pressed on the submit button, no re-render
would be triggered, and the website would be left with no changes.

We can fix this by passing in this array as a property for our Input.js file to
use and by rendering Note components based on this array.

To render the Note components based on the contents of the array, you’ll
need to call the JavaScript map function to “map” each element inside the
notes array onto a Note component and then return it.
Turning each element inside my notes array into a Note Component.

Now, I’ll go into Input.js and change the handleSubmission handler to push
“hi” to the array that was passed each time I click the submit button. Ideally,
I would hope that simply doing this would show all my notes, but
unfortunately, this isn’t the case since there’s no re-render being triggered.
Furthermore, I’ve passed a parameter e into my submission handler to
prevent the application from automatically refreshing the page on
submission. I’ll talk more about this later.

I’ve also added a log to make sure that we’re entering the submission
handler.
Upon running the application and trying to press submit, you’ll see this:
To ascertain that this is a problem with re-rendering, even if I initialize my
array with a couple of Strings, to begin, I’ll still have the same problem of not
being able to see extra notes pop up.
App.js

Although this approach didn’t work, we at least know that we are properly
mapping each of our notes into their respective note components. To solve
the issue of not re-rendering when our array changed, we can use React
Hooks, which we talked about previously.

To use React Hooks, we have to import the useState module from React.
Following that import statement, we’re now able to change our old array into
a state array with hooks in place for us to use. This way, any changes to our
array will re-render the component. To create a React Hook type the
following in place of the array:

const [notes, changeNotes] = useState([])

This line of code is telling React that you are creating a state array called
notes, which is initially set to just an empty array. useState returns an array
containing a state and a hook. We use array destructuring to assign notes
and changeNotes to the state and the hook respectively. The changeNotes is
the “hook” that will allow us to alter our notes state. Thus, anytime you want
to make a change to the notes state and re-render the Component in which it
is being used, you must call this changeNotes function/hook. This is the
syntax for creating a react hook:

const [{name of state}, {name of function to change state}] =


useState({initial value of state})

So now that I’ve created this state, I’ll need to pass the changeNotes hook
into my Input Component from App.js so that I can call it and change “notes”
whenever I need to.

App.js

Instead of pushing to my notes state inside the Input component, I’ll need to
call the changeNotes property that I passed in from App.js.
Input.js

As you can see, now I’m setting my notes state equal to a new array with the
previous elements inside notes along with a new note appended to the end,
which in this case is “hi”. The “…props.notes” is telling my changeNotes
hook, that I should include the previous values of notes when I give the notes
state anew value.

Now when we run our code, we’ll see a dynamic list of notes showing up
when we press the submit button!
However, if you press the submit button enough times, you can see the
messages go behind my Input component. We’ll address this problem later.

The Event Parameter


I’ve already used the event parameter inside my handleSubmission event
handler, but now I’m going to explicitly talk about what it does and why I
needed it earlier.

The event parameter is just an object containing information about the event
that occurred. Since the parameter is an object, it has many useful
properties for us to use inside our event handlers. In the handleSubmission
case, I used it to prevent the default behavior of HTML forms; HTML forms
automatically refresh the entire page upon submission.

Printing The Event Parameter

Arguably, the most useful part of the event parameter is its “target” value.
When you try to get access to the event’s target value by typing “event.target”
you’ll have access to that HTML element and be able to read all of its
properties.
Building a Simple To-Do List Application (Tying it All Together):
Now that we know about props, hooks, and the event parameter, we can
finish off the handleChange listener inside our Input.js function. First, I’ll go
back to my App.js file and add a new hook for each note like so:

const [note, changeNote] = useState("");

and I’ll pass both the note state and the changeNote hook into my Input
component. I’ll need these two values to keep track of what the user is typing
inside my Input component.

My App.js looks like this now:

App.js

Inside my Input.js file, I need to set the value of my input tag to “props.note”
so that I can keep track and update my note’s state. Furthermore, by setting
the value of my input to “props.note”, I can easily clear all the text inside my
input tag from my handleSubmission function.

Next, I’ll call props.changeNote and pass in e.target.value so that my note is


now text inside of the input tag from Input.js.

The last change I need to make inside Input.js is to call props.changeNotes


with the values …props.notes like before, and also props.note, which holds
the text the user put into the input tag. After that, I’ll set my note to an empty
string so that I clear the input tag of any previously entered text.

Input.js

When we run our application again, we’ll see that adding notes works
perfectly.
On top of what we did here, you could make your handleSubmission
function in Input.js check whether or not the user entered an empty note by
changing the function to the following:
handleSubmission()

This version of the handleSubmission function prevents users from trying to


create empty notes.

As you can see above, clicking the check mark doesn’t delete a note at all. To
add this functionality, we simply have to pass an id property to each of our
notes, so that we know which one to delete; we’ll make the id of each note its
index in the notes state array. To access this index, we can just add a second
parameter to our arrow function inside the map function in App.js.

Furthermore, since my note state array is inside App.js, I’ll need to pass in a
function that dictates how to remove a particular note according to its id. I
used the JavaScript filter function to grab hold of the notes array without the
note I’m aiming to delete. I can now set the notes state equal to the array I
obtained with the filter function by using the notes hook.
App.js

Inside Note.js, I can simply set an onClick listener on my Checkbox and then
have the event handler call the remove function I passed in previously with
the id.

Note.js
If you wanted to, you could’ve also set the onClick listener equal to an
anonymous function that called “props.remove(props.id)”. However, to keep
it simple, I chose to just explicitly define a function above.

Since I’ve properly defined my onClick handler, notes are now able to be
deleted when their checkbox is clicked.
Building a Simple To-Do List Application (Finishing Touches):
Since we don’t want messages to appear under our Input component, I can
pass in another property to my Note component which adds padding to only
the last element inside my notes array; I’ll pass in a class name. To figure out
which element is last in my notes array, I can check if a note’s index is equal
to the one less than the length of my notes array. I’ve used the ternary
operator to add the correct class properties to each Note component.

Finished App.js

Inside Note.js, I can just set the className of the Note component’s div equal
to “note” as we had before, along with the class property that was passed in.
Note.js

With that done, our To-Do List Application is finished!


The Code
Congrats on making it this far! You can access the code I wrote in this article
here:
If you’re a high school student looking to improve your programming skills,
feel free to join our hackathon from July 23 to July 25, 2021, and exercise
your new ReactJS skills!

Explore Hacks
Explore Hacks is a hackathon providing high school students with
the chance to explore the process of ideation to product execution.
explorehacks.org

Next Steps:
If you’re interested in learning more about React, feel free to read about
some of the topics I’ve put below. Thanks for reading!

Getting Started with Redux | Redux


Redux is a predictable state container for JavaScript apps. It helps
you write applications that behave consistently…
redux.js.org

Using the Effect Hook - React


Hooks are a new addition in React 16.8. They let you use state and
other React features without writing a class. The…
reactjs.org

The ultimate guide to the React useReducer Hook - LogRocket


Blog
useReducer is one of the additional Hooks that shipped with React
16.8. An alternative to the useState Hook, it helps…
blog.logrocket.com

When to useMemo and useCallback


Performance optimizations ALWAYS come with a cost but do NOT
always come with a benefit. Let's talk about the costs and…
kentcdodds.com

Deployment | Create React App


npm run build creates a build directory with a production build of
your app. Set up your favorite HTTP server so that a…
create-react-app.dev
Author:
Leo Xu

More content at plainenglish.io

JavaScript Programming React Front End Development Web Development

Written by Explore Hacks Follow

23 Followers · Writer for JavaScript in Plain English

Explore Hacks is a three-day high-school hackathon where hackers can tackle real-world
issues. https://explorehacks.org https://instagram.com/explore_hacks

More from Explore Hacks and JavaScript in Plain English


Explore Hacks in Python in Plain English Luna Rojas in JavaScript in Plain English

Create Your First CNN In PyTorch NodeJS 21 is HERE! Features that


for Beginners will blow your mind 🤯
Part 1. To create a Neural Network in PyTorch, The launch of Node.js 21 has brought a wave
all you need to do is create a class for the… of excitement and anticipation to the…

11 min read · Jun 8, 2021 · 8 min read · Feb 14, 2024

177 1 1.4K 19

fatfish in JavaScript in Plain English Explore Hacks in Python in Plain English

Interview: Can You Stop “forEach” Part 2: Transfer Learning with


in JavaScript? PyTorch CNNs For Beginners
There are 3 ways to stop forEach in JavaScript When creating a CNN for a difficult task,
Transfer Learning is often used to save time…

· 5 min read · Feb 15, 2024 8 min read · Jun 9, 2021

1K 24 160
See all from Explore Hacks See all from JavaScript in Plain English

Recommended from Medium

Akshay George Leshchyshyn in Stackademic

A Guide to Organizing Your React Mastering OOP Patterns in React:


Project: The Optimal Folder… Unlock the Secrets to Cleaner, Mo…
In the vast world of web development, In today’s fast-paced development
organizing the project structure can be as… environment, writing efficient and…

2 min read · Sep 29, 2023 9 min read · Oct 19, 2023

256 28 1

Lists

General Coding Knowledge Stories to Help You Grow as a


20 stories · 1009 saves Software Developer
19 stories · 896 saves
Coding & Development ChatGPT
11 stories · 501 saves 21 stories · 513 saves

Issam Eddine Bouhoush Artturi Jalli

Micro-front-end with React JS I Built an App in 6 Hours that Makes


$1,500/Mo
Copy my strategy!

6 min read · Oct 1, 2023 · 3 min read · Jan 23, 2024

43 13.4K 159

Benoit Ruiz in Better Programming Evelyn Taylor

Advice From a Software Engineer Structuring React Projects with


With 8 Years of Experience Feature-Driven Development 🏗️
Practical tips for those who want to advance When it comes to building complex web
in their careers applications with React, project structure an…

22 min read · Mar 20, 2023 5 min read · Oct 14, 2023
14.4K 269 148 3

See more recommendations

You might also like