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
Become a member
108
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!
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
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.
Drawing of a website
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
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.
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.
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
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
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.
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:
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:
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 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.
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:
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.
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.
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()
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
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!
Explore Hacks is a three-day high-school hackathon where hackers can tackle real-world
issues. https://explorehacks.org https://instagram.com/explore_hacks
177 1 1.4K 19
1K 24 160
See all from Explore Hacks See all from JavaScript in Plain English
2 min read · Sep 29, 2023 9 min read · Oct 19, 2023
256 28 1
Lists
43 13.4K 159
22 min read · Mar 20, 2023 5 min read · Oct 14, 2023
14.4K 269 148 3