Introduction to React
By: David Wei

Introduction to React

Overview

Are you a software developer, one in training, or just interested in front-end software development? I suggest learning React! This blog is the perfect introduction to coding with React so you can determine if it's the right coding style for you. In this post, I will be exploring how to code React elements and components. I will also be touching on installations and environment setup. I have included installation links and code demos so you can try out React for yourself. 

What is React?

Heard of Facebook? React is a Javascript library first created by Facebook. It was made open-source in 2013 and since then has steadily grown in usage. It is now one of the most used libraries for front-end software development. React really shines when used for single-page applications. The server only needs to send a single HTML (index.js) page and React will manage the rest through the browser, including page rerouting, which makes for an incredibly efficient and speedy user experience. 

Installations

To follow along with my demos within this blog I would recommend the following installations of Node.js (version 8.1 or higher) and Npm (version 5.6 or higher) and Visual studio code (any 1.6 version will do). If you do not want to do the installations but still want to follow along please jump to the end of this blog section to the alternative method I provide.

You can double-check if you have the installations already with the following command line prompts.

// This is to check Node.js version
node -v

// This is to check Npm version
npm -v        

If both these prompts return with an appropriate version, you can skip this installation section.

  • First Install the latest version of Node.js, please visit: https://nodejs.org/en/ and get the LTS version.
  • During the Node.js installation setup please select the npm package manager to get the latest version of npm.

No alt text provided for this image

  • Lastly, install the latest version of visual studio code from: https://code.visualstudio.com/download.

Installation Alternative

I prefer to have my local environment set up with these installations but if you want to do the demos in the blog without going through installs, please visit https://codesandbox.io. Click "</> start coding for free" and make a react template!

Creating a local React project

If you are just following along with codesandbox.io, please skip to the next section.

Now that we have all the installations we require, let's create our first local React project! We will be using create-react-app. This environment I feel is the best for an introduction to creating single-page applications with React, it creates the file structures for us and optimizes production by allowing the usage of the latest Javascript libraries.

Make a folder on the drive of your choice through the file explorer GUI and navigate to it through the command line. I used the absolute path here to get to the folder I created but feel free do your own way as long as you end up in the folder :)

cd c:\INTP362        
No alt text provided for this image

Now we will run the following command and create-react-app / npm will do the rest and set up everything we need. (Right after create-react-app will be the name of the file I named it "blog-one" but feel free to change that. We set up the flag of --user-npm to make use we use Npm on our machine to handle all installations.)

npx create-react-app blog-one --user-npm        

It will take a couple of minutes to complete and once it does you should see something similar to the screenshot below.

No alt text provided for this image

Like the command prompt says it's time to hack! Just kidding, unfortunately, there will be no hacking tutorials in this blog but we have successfully set up a local React project.

Running the local project

To run the project and see your coding changes live, we need to navigate into the newly created folder and enter npm start on the command prompt:

No alt text provided for this image

This will start up the React project on the localhost in your default browser, and we can edit the code through Visual Studio Code. Open up VS code click "file" in the top left and then click "open folder" and find and select the folder you created with the npx create-react-app command prompt line. Now we are ready to code and you will see updates right away in the localhost browser!

React project file Structure

After opening up the file structure in VS code for the first time it might be intimidating, but you'll quickly notice the files under the "src" folder are files you've worked with before ranging from .html, .css to .js type files. This is the folder we will be mainly concentrating on for the demos in this blog and I will explain how to link the files as I do my code demos within the blog. The public folder is mainly for production and holding already built files.

As for the package JSON file, it holds the project's dependencies. If you take a look inside the package file, it includes the testing libraries, and React libraries which will provide us with everything we need to code in React. React-dom is what gives the project the ability to render the React code to the browser, and React-scripts helps the project bundle and serve the code.

React elements

To start let's create some simple React elements. We will be using the index.js file under the src folder. Let's clean up the code in the file a bit so it looks like the following snippet.

import React from 'react'
import ReactDOM from 'react-dom';
import './index.css';



ReactDOM.render(
  document.getElementById('root')
);        

The localhost browser will not have anything on it now but let's create an element with the .createElement() method from the React library. The method takes in three parameters, the first one is a Type argument, this will be the tag name that you want to create ('h1' or 'div') or a React component (class or function). The tag name will be exactly the same as HTML tags but it has to be wrapped by quotations. The second will be any properties you want the element to have (indicating style for the tag or type depending on the tag). The third is any children, this can be text or another tag.

createElement() method

Let's start off with something simple, creating a header 1 with "INTP362 rocks!" text in it. To call the method you have to start with "React." then the method name createElement(), and fill in the method parameters. This has to be within the ReactDOM.render method so the React code can be rendered to the browser and displayed. Try it on your own and then compare it to the snippet below.

ReactDOM.render(
  React.createElement("h1", null, "INTP362 rocks"),
  document.getElementById('root')
);        

Once you save the file, you'll notice your browser update and you should see h1 text with the text "INTP362 rocks".

How is the text showing up?

If you notice the line document.getElementById('root') in the code, this is actually grabbing a div in the index.html file within the public folder with the id of "root". ReactDOM renders the element we created in index.js into the div with id="root" of the HTML page so the browser can display the element.

Changing properties of the element you created

Let's try changing the color of the header now to blue to replace the null in the second parameter in the code above.

 ReactDOM.render(
    React.createElement("h1", {style: {color: "blue"}}, "INTP362 rocks"),
    document.getElementById("root")
  );        

Note that when adding properties they need to be contained within braces: { }. If the property is part of the tag, for example, input tag of type text then it is contained in quotations shown below.

React.createElement("input", "type='text'", null)        

The code block may be pretty simple right now creating one element but what if we had to create an input field with a label for part of a form?

ReactDOM.render(
  React.createElement(
    "div",
    null,
    React.createElement("label", null, "Name:"),
    React.createElement("input", "type='text'", null)
  ),
  document.getElementById("root")
);        

React requires a container for elements if there is more than one element being created, I am going to have the parent container be a div. We will make the label and input to be the children of the div. Now imagine creating three more labels and inputs within this div, the code would start looking pretty hectic. I know I would have a hard time reading the code.

How do we elevate this code like a cook elevating their dish in Masterchef? We can use React components to clean up the code and increase the readability and have reusable code. Let's jump into components next!

React components

When designing React applications for real, the user interfaces are created with a collection of React elements which is called a React component. Components are functions that return UI, and the code is independent and reusable! Components will also make the code a lot cleaner, easy to read, and increase functionality. Let's take the code from the last example in the React elements section and turn it into a component.

Making a component with several labels and inputs would look like this:

// React component called SampleForm
function SampleForm() {
  return (
    <div>
      <label>First Name:</label>
      <input type="text" />


      <label>Last Name:</label>
      <input type="text" />
      
      <label>Phone number:</label>
      <input type="text" />
    </div>
  );
}


  ReactDOM.render(
    <SampleForm />,
    document.getElementById("root")
  );        

The code has now been elevated! A few things to note:

  1. When creating a React component, the first letter of the name of the function needs to be capitalized.
  2. Rendering the piece of UI will be easier, it's just a self-closing tag of the function's name.
  3. The function needs to return the UI, and if there's a block of UI, it is contained within parentheses after the return statement.

Understanding properties and how components can use them

Properties (props) in React is an object that contains data about the component, components can dynamically display this data. Let's take a look at how we can use properties.

// The property is being passed into the component
function SampleForm(props) {
  return (
    <div>
      // the component calls the propert and display Name in its place
      <label>First {props.name}:</label>
      <input type="text" />
      
      <label>Last {props.name}:</label>
      <input type="text" />


      <label>Phone number:</label>
      <input type="text" />
    </div>
  );
}


  ReactDOM.render(
    // name is the property
    <SampleForm name ="Name" />,
    document.getElementById("root")
  );        

The prop calling can be shortened by just passing the property name instead of props into the function. So here instead of passing in props, we pass name.

function SampleForm({name}) {
  return (
    <div>
      <label>First {name}:</label>
      <input type="text" />
      
      <label>Last {name}:</label>
      <input type="text" />


      <label>Phone number:</label>
      <input type="text" />
    </div>
  );
}        

I know the example may be redundant here since we are typing names either way but this will help you understand the next section of how components can pass properties from one another to make efficient code.

Passing Properties between components

Let's make a new component that creates dynamic labels and inputs based on the properties passed into it. Our SampleForm component will be passing the different properties to create the same form label pairings as the example above.

// label property is passed in from SampleForm component
function SampleLabel(props) {
  return (
    <div>
      // label is dynamically used here
      <label>{props.label}:</label>
      <input type="text" />
    </div>
  );
}


function SampleForm() {
  return (
    <div>
      // setting the property of the labels
      <SampleLabel label="First Name"/>
      <SampleLabel label="Last Name"/>
      <SampleLabel label="Phone number"/>
    </div>
  );
}


ReactDOM.render(
  <SampleForm />, 
  document.getElementById("root")
);{        

Pretty cool right? This is a more efficient way to code in my opinion. Try making more components and create some UI of your choice.

Creating variables and using the map function

One last React library function I want to go over is the Map() function but before we can use it let's look at how to create a variable.

Creating variables

Creating variables within React coding consists mainly of 2 types of variables; "const" creates a variable that does not get reassigned after creation and "let" creates a variable that may be reassigned after creation. Create variables appropriately based on whether or not they need to be reassigned.

The snippet below creates a list of objects that cannot be reassigned. If the data is not a list, we do not need the square braces to contain it.

// Imitating user data 
const users = [
  {id: "1", name:"user1", email:"testing01@live.ca"},
  {id: "2", name:"user2", email:"testing02@live.ca"},
  {id: "3", name:"user3", email:"testing03@live.ca"}
];        

using .map

If we had to iterate through a list of user data objects like in the code snipper, map() is a really useful function within the React library for this. It will iterate over an array to manipulate or change data items.

As an example, the following code uses the map() function to iterate through the user's variable we created above and displays the username, and then email per user.

function ReadData({users})
  return (
    <div>
      {users.map (users => (
        <div>
          <h3>Username: {users.name}</h3>
          <p>User email: {users.email}</p>
        </div>
      ))}
    </div>
  )
}


ReactDOM.render(
  <ReadData users={users}/>, 
  document.getElementById("root")
);{        

A few coding syntaxes to note:

  1. when using .map() the whole code block needs to be contained within brace: { }.
  2. In order to send the data from the list into elements or calculations, the syntax is the variable name.map (). Inside the parentheses, is the variable name followed by "=>". all element creation after "=>" is contained in parentheses.

You can also use the map() function to iterate over an array and insert the data into calculations as well. It is a very useful function!

Unique key warning fix!

The user data is dynamically displayed now but if you inspect the browser page, you should see an error like the following screenshot.

No alt text provided for this image

Keys are a unique identifier for dynamically created elements like what we just created with the .map() function. It helps our React app keep track of what elements have changed, added, or removed.

Nobody likes warnings so let's fix that! we need to add a key to each div pairing dynamically created per user data by adding "key=" to the div tag. Since the users already have a unique id let's use that as the key.

function ReadData({users}){
  return (
    <div>
      {users.map (users => (
        // where we added our key
        <div key={users.id}>
          <h3>Username: {users.name}</h3>
          <p>User email: {users.email}</p>
        </div>
      ))}
    </div>
  )
}        

If you check the developer tools again through the browser inspect function, the error is gone!

Conclusion

I really enjoyed learning to make components and understanding how one component can call on another to create user interfaces. There is definitely a lot more to learn in React but I hope this blog has piqued your interest and you want to learn more React coding! Try coding a small application of your own. You can check out my references for further knowledge and I would definitely recommend going to the React docs to read up on function usage as you learn new React library functions. Lastly, I have a short tutorial demo for making a small form with all the knowledge we have learned and touch on the useState function. Look forward to more fun information in Blog #2!!

Code Demo Video Link: https://mysait-my.sharepoint.com/:v:/g/personal/yunze_wei_edu_sait_ca/EWdJRBi2zHRGkeHT-HfVrGMBoaJ3m28w8qegBqjHyVFDeA?e=AMzkbf&isSPOFile=1

Citations:

Porcello, E. (2020, May 20). Getting started with react - react.js video tutorial: Linkedin learning, formerly Lynda.com. LinkedIn. Retrieved February 16, 2022, from https://www.garudax.id/learning/learning-react-js-5/getting-started-with-react?autoAdvance=true&autoSkip=false&autoplay=true&resume=true&u=2245281

Getting started. React. (n.d.). Retrieved February 16, 2022, from https://reactjs.org/docs/getting-started.html 

To view or add a comment, sign in

More articles by David Wei

  • React Hooks and State Management

    Overview In the last blog, I introduced simple React elements and component creation (check it out here! -…

Others also viewed

Explore content categories