How to Get Started With React in 2022
JavaScript is not exactly the easiest when it comes to creating dynamic websites, and that’s exactly why there are tools such as React that facilitate this process. React is a UI library that allows developers to easily create interfaces that users can interact with.
In this guide you will learn the basics of React. I assume that you have some experience with JavaScript and a decent knowledge of HTML and CSS. You don’t need to be an expert, but you at least need to know the basics of these.
Buckle up, because this is not exactly a short guide.
Before we go on any further, let’s talk about JSX.
What Is JSX?
JSX is a syntax extension that introduces XML-like syntax to JavaScript. It basically allows developers to write HTML inside JavaScript.
This is what it looks like:
function App() {
return (
<div>
<p>Hello world! I'm using <b>HTML-like syntax</b> within JavaScript.</p>
<p>Isn't that cool?</p>
</div>
)
}
Within the return statement, everything looks just like regular HTML. In the example, the function is returning JSX.
With JSX you can use most HTML tags and their respective attributes (e.g. id, type, etc.), but one attribute that is named differently in JSX is class. Since JavaScript uses class as a reserved word to create, obviously, a class, it doesn’t work in JSX. If you want to add a class to an element, you can do so by using ‘className.’
<div className="example">Like this.</div>
So, hopefully we understand what JSX is. In React, you can use JSX in many different ways; you can assign it to a variable:
const example = <span>Oh, another example.</span>
But one thing to ALWAYS keep in mind is that the JSX statements have to have an opening and closing tag. What do I mean by that? Well, it means that JSX statements such as the following would not work.
const example = Oh, <b>another</b> example.// This is going to cause a syntax error.
Why would that not work? Because JSX only reads statements that have an opening and closing tag. Sometimes we might find ourselves in situations in which we don’t want it to be enclosed in any specific tags. In that situation you can use empty tags:
const example = <>And <b>another</b> one.</>
Now, this statement WILL BE recognized as JSX. It’s part of the syntax.
These are things to keep in mind not only because they will make your life much easier in the long run but also because they will make the code work.
JavaScript Within JSX
That might sound redundant, but one of the cool things about JSX is that you can run JavaScript statements within JSX.
Let’s look at a very basic example of what I mean.
function App() {
return (
<div>
<p>What is the result of 2 + 2? It's {2 + 2}!</p>
</div>
)
}
It’s going to render on the browser as:
What is the result of 2 + 2? It's 4!
To use JavaScript statements within JSX you need to enclose the statements within curly brackets (“{” and “}”).
Let’s Create an App!
Finally, let’s get to it. We’ll need the following programs for this part:
Once you’ve installed Node.js and have also made sure that you’ve set up your editor of choice, we can get started with this part of the guide.
For this part, we’ll create a CRUD web app that handles information regarding the employees of a company.
First, we’ll open Terminal on macOS or Command Prompt on Windows. I’ll use the word terminal to refer to these interchangeably throughout the guide.
In the terminal we’ll go to the directory in which we plan to store this project. To do this you can type the following in the terminal:
cd [name of folder where we'll store this project]
Now, we’ll use Create React App to create the boilerplate for our app. In the terminal we’ll enter the following command:
npx create-react-app crud-application
Now, a folder named “crud-application” should’ve been created with the boilerplate code and folders that we need for this part of the guide. Proceed to open the folder with VSCode.
In the root folder, we’ll delete a few files:
- App.css
- App.test.js
- logo.svg
In the App.js file, let’s get rid of a few things. The file should only have the following code:
function App() {
return (
<div></div>
);
}export default App;
We didn’t need any of the extra stuff.
Then let’s add some text. Just to test that our web app works. Within the div tags, we’ll add “Oh, this is a test.”
...
<div>
Oh, this is a test.
</div>
...
It’s time to run the app. To do this we’ll need to run a command from the terminal. Open the terminal from the editor by clicking on the “Terminal” option from the top bar and then “New Terminal.”
Now, type the following command and hit enter:
npm run start
If everything goes well, a new tab on your browser should open our shiny brand new app.
It’s not the prettiest or most useful app just yet.
Enough Examples
Now that we’ve covered some important concepts, we can start coding our app.
Let’s go to src/index.css and add some CSS. I won’t go over the CSS because this is not that kind of guide. The file should only contain the following code:
That should give the app some character.
Now, go to src/App.js and add the following import to the top of the file:
import { useState } from 'react';
useState is a React function that allow us to manage the state of our website. State is the current value of elements within a website.
In the same file, right below this line:
function App() {
Add the following code:
const [employees, setEmployees] = useState([]);
const [displayBox, setDisplayBox] = useState(false);
const [name, setName] = useState('');
const [address, setAddress] = useState('');
const [salary, setSalary] = useState('');
const [position, setPosition] = useState('');
const [update, setUpdate] = useState(null);
We are being introduced to a new function. useState is a function that’s being assigned to pairs of variables (employees, setEmployees; displayBox, setDisplayBox; etc.). This allows React to be aware that these variables have to be watched. In the case that one of these variables has a new and/or different value, React will remember to render it.
What is supposed to go inside of ‘useState()’? useState() initializes the values of the pairs. For the variable employees, we initialized it with an empty array, and for the variable name, we initialized it with an empty string, and so on.
For example:
const [value, setValue] = useState(null);
The value of the variable ‘value’ is null. And with the function ‘setValue()’ we should be able to update its value depending on what we need to do on our app.
So far we have used the useState() function for the following values that we want for React to watch:
- employees: Array of objects that stores the employees’ information.
- displayBox: Boolean that allows us to show or hide the ‘Add Employee’ container.
- name: Holds the current value of the Name text input.
- address: Holds the current value of the Address text input.
- salary: Holds the current value of the Salary text input.
- position: Holds the current value of the Position text input.
- update: Holds the index value of the employee to be updated. If the value is null, it means that there is no employee object being updated.
The reason why we need to watch for these values is because they will constantly be changing depending on what the users’ needs are.
Now, add the following after the last line of code:
There are a few functions here that will be handling the user interaction. Let’s cover each:
- addEmployee(): This function reads the current values for name, address, salary, and position. If any of these is empty, then the problem will output to the console ‘Not enough information has been provided,’ otherwise it will add the employee object to the employees array. It also calls the resetValues() function at the end.
- deleteEmployee(): This function gets the index that has to be deleted from the employees array and sets a new employees array without the deleted value.
- updateEmployee(): This function gets the index from the employees array that has to be updated, and it also checks whether any of the values are left blank. If any of the values is left blank the program will output to the console ‘Not enough information has been provided,’ otherwise it will update the employees array with the newly provided information. It also calls the resetValues() function at the end and it sets the value of update to null. This is so the entries go back to being displayed without the “editing” box.
- resetValues(): This function resets the values for name, salary, position, and address.
Now, within the return statement, let’s get rid of everything inside it. (Yes, even the div tags.)
Add the following inside the return statement:
It’s about to get reactive. Get it? I’m funny.
On this part of the code you will notice a few new concepts. Line 3 of this code snippet shows a JavaScript statement inside the JSX that also has some more JSX inside of it. How does this work? We have a ternary operator that is telling us that if the employees array is longer than zero then it should display null (so, nothing) on this part of the app… OTHERWISE (meaning that the array is empty) it should display “No employees in the system yet. Do you want to add the first one?”
Ternary operators are going to help you a lot in React. You can use these to display different information depending on what the values from certain variables are.
The way it works is the following:
The next thing we notice is the button element with the attribute ‘onClick.’ This is somewhat similar to what we have in vanilla JavaScript. In React if you want to add an event to an element you can do so by adding the name of the event as an attribute to an element in camel case. What’s inside the attribute onClick is an arrow function that lets the app know that once the user clicks the button our app should perform the following tasks:
- Set the displayBox value to true. The displayBox value is the value we’re using to check whether the ‘Add Employee’ container is displayed.
- Set the update value to null. In case an employee is being updated, once the user clicks the Add Employee button, it will stop the process of updating the employee.
In lines 8 through 19 we have the ternary operator that checks whether to display the ‘Add Employee’ box which holds the text boxes that will get input from the user. If the variable displayBox is true it’ll show the container, otherwise it will display an empty string. (I could’ve also chosen to render null instead of an empty string, but I wanted to showcase different scenarios.)
Then, after this block, starting from line 20 onward we have the ternary operator that shows the list of employees. It will only show employees if, obviously, there are any, otherwise it will not show anything within this block.
Within this last ternary block we have a good number of conditions that if met will show different information.
In line 22 we’re using the map() method from arrays to display every single employee object within the employees array.
In line 24 we get the first if statement. This one checks whether the value of the variable update holds the value of null. If update does have a value (not null) it will render the employees objects with the one employee that’s being edited rendering with a highlighted blue container.
Every element from the map() method in React needs a key. A key is a unique identifier for that item. As you can see, in line 26 within the section element there are a few attributes attached to it: className, key, onKeyDown, and onKeyUp. These 2 last ones are events that will run once the user holds a key (the keyboard one) and releases it.
In line 59, we’re rendering the value of the variable employee.name. In case the value of employee.name ever changes, React will only re-render that one part. That’s what’s awesome about react.
That should be it for this guide. This was a very extensive guide so I expect a lot of questions to come my way, so feel free to ask away.
You can check out the entire source code here.
A few things to brush up on: