Categories
JavaScript React

Course Review: ‘React for Beginners’ by Wes Bos (June 2020)

Having gone through a video course of his some years ago, Wes Bos made a lasting impression on me as someone that could make learning to code really enjoyable and explain relatively complex concepts in an easy-to-understand way. So, when I embarked on this journey to learn React and wanted to go beyond freeCodeCamp’s intro course, I knew where to go next: his React for Beginners course.

Note: after purchasing the course and joining Wes’ Slack channel dedicated to it, I saw a couple of mentions of this course needing to be updated. I started to worry that what I was learning was out-of-date already, so I asked for some clarification. A couple of helpful fellow members of the group summarised it for me:

  1. In Video 12, value.value becomes current.value
  2. The FireBase UI has been updated
  3. Hooks have since been introduced to React

Altogether, these are minimal issues and the entire course remains relevant and valuable. Still, having purchased the course you get access to the updated version when Wes re-records it which is great.

Table of Contents

  1. Video 1: Introduction, Tooling and Editor Setup
  2. Video 2: Thinking and Understanding React Components
  3. Video 3: Creating our First Components
  4. Video 4: Writing HTML with JSX
  5. Video 5: Loading CSS into our React Application
  6. Video 6: Creating our application layout with components
  7. Video 7: Passing Dynamic data with props
  8. Video 8: Stateless Functional Components
  9. Video 9: Routing with React Router
  10. Video 10: Helper and Utility Functions
  11. Video 11: Events, Refs and this Binding
  12. Video 12: Handling Events
  13. Video 13: Understanding State

Video 1: Introduction, Tooling and Editor Setup

To kick things off, Wes introduces us to the project files, the terminal, code editor and more.

The project, ‘Catch of the Day’, is an online store selling seafood which allows you to add multiple items to a basket, as well as live updating of inventory. The files can be downloaded from GitHub (https://github.com/wesbos/React-For-Beginners-Starter-Files).

Wes then takes us through the package.json file, explaining the different parts of the file;

  • devDependencies – packages that are needed for development of the project, such as preprocessors
  • dependencies – packages needed to run the actual live project
  • scripts – ‘shortcuts’ to run series of commands, speeding things up

Running the following command in the terminal will install each of the dependencies above:

npm install

Running the following command launches one of the scripts listed in the package.json file:

npm start

This compiles all of the code and launches a new tab in your browser with hot reloading enabled. Hot reloading makes the development process so much easier as you can see the impact of your changes almost immediately. Whenever a change is made to a file in the project – files that are ‘watched’ – the browser will automatically reload the project to show the changes.

Video 2: Thinking and Understanding React Components

In this video, we get our first proper look at React.

React is made of components. They look a lot like custom HTML elements, but are much more powerful.

Wes shows us how we can view the React code used by websites – such as Facebook and Instagram – as React components, instead of just pure HTML.

To do this, you download the React Developer Tools extension for Chrome.

Launch the Developer Tools window in Chrome and click on the Components tab that should appear. Click on a component to see its ‘Props’ and ‘State’ (essentially just information stored by that component, but can be tied it how it looks).

You can see React in action by editing a prop or a state’s value and watch how it changes what’s displayed on the front-end (make sure you pick one that’s tied to something visual!).

Remember, the key thing about React here is that you aren’t running any JavaScript to make those changes and you’re not directly editing the HTML either. Instead, you are changing the underlying ‘record’ of information and React is reacting to it automatically.

Video 3: Creating our First Components

We’ve mostly been getting prepared and looking at examples of React at work, but now we’re getting into coding our own!

We get started by working within the index.js file and Wes explains how this project’s workflow will bundle all of the JavaScript together – React, our dependencies, and our custom code – into a single bundle.js file which is injected at the end of the page.

Importing the React Module

To get started using React, we need to first import the React package or module. To do this, we just need to include the following line:

import React from "react";

This will look for the React package in the node_modules folder and make it available to us in our project.

Creating a Component

We use classes to create components so that we can re-use them. We can do it like this:

class StorePicker extends React.Component {
  // component code goes here
}

Every single class in React needs at least one method inside it called render. Unsurprisingly, this tells React what to output or display. This render method should return only one element, like below:

class StorePicker extends React.Component {
  render() {
    return <p>Hello!</p>
  }
}

Rendering React Components to the DOM

Now, in order to actually render our React component to the DOM, we need to import the render method from the react-dom package, so we need to write the following:

import { render } from 'react-dom';

So, we’ve imported React and the ability to render React components to the DOM. We’ve also got a component ready to render. Here’s how we render it to the DOM:

render(<StorePicker>, document.querySelector("#main"));

Keeping Components Organised

So that we don’t end up with either one huge file with lots of components in it, or alternatively a messy project folder where components mix with the main HTML, CSS and JS files, we should create a dedicated components folder. So, for the StorePicker component we’ll create a StorePicker.js file in the new components folder and cut and paste the component into there.

Tip: we’ll always need to import React to every single component, so remember to add it to the top of the file.

Separating components into different files means we need to make sure any component we use in a file is made available. To do this, we’ll need to do two things:

  1. Export the component itself
  2. Import the component where we want to use it

In order to ‘surface’ a component (or function) for other files to use, we first need to export the component:

export default StorePicker;

We can then import the component elsewhere using:

import StorePicker from './StorePicker';

Notice that the location is a relative path as it will originally look into the node_modules folder.

Video 4: Writing HTML with JSX

Typically, writing HTML inside of JavaScript is a real pain. With ES6 it’s a little bit easier with template literals. However, with React we have JSX which allows us to quite easily mix HTML and JS.

Even though JSX isn’t compulsory, Wes shows us the React.createElement method and highlights the drawbacks (such as difficulties when nesting elements). JSX is the recommended way to render the contents of a component.

One of the differences with JSX comes when you want to add a CSS class to an element. In JSX, you need to use className.

If you want to return multiple lines in your component’s render method, you just need to return your JSX inside of brackets like this:

class StorePicker extends React.Component {
  render() {
    return (
      <div>
        <h1>This is a title!</h1>
      </div>
    )
  }
}

Always Return One Element

We mentioned this earlier, but we can’t return adjacent, sibling elements. We have to return just one element.

Many developers use <div> elements, but this can mean a complex app ends up with a nested nightmare of <div>‘s. React 16.2 introduced fragments, which React interprets as a sort of ‘non-element’ we can wrap around our elements. This looks like:

<React.Fragment>
  <p>Sibling 1</p>
  <p>Sibling 2</p>
</React.Fragment>

However, if we import React.Fragment explicitly we can just use <Fragment> like so:

import React, { Fragment } from 'react';

...

<Fragment>
  <p>Sibling 1</p>
  <p>Sibling 2</p>
</Fragment>

Commenting

Writing code comments in JSX is also slightly different. What we need to do is use curly braces which tell React to interpret the contents as regular JS, then use JS block commenting syntax like the below:

{ /* This is a JS comment in JSX */ }

It’s also worth noting that comments must go inside the returned JSX element and not be the very first line in the return statement, otherwise it will throw an error.

Video 5: Loading CSS into our React Application

In terms of getting our CSS into the project, it’s pretty straightforward.

On the one hand, we could write CSS on a per-component basis and couple it closely with the components themselves or, alternatively, we can just import a CSS file directly into our index.js file like you might do normally from within the <head> of your HTML page.

For simplicity, we start with the second option; importing the project-wide CSS file. To do this, we add another import statement to the index.js file (the root or parent file in this project):

import './css/style.css';

Once we’ve done this and saved the file, the pre-defined workflow (Webpack, etc) that came with the create-react-app foundation that the project is based on will handle the CSS build, injection and hot-reloading so we’re good to go!

Video 6: Creating our application layout with components

With the initial ‘setup’ complete and armed with a basic understanding of React components, we get started with laying out the main components of the project.

We start by creating an <App> component to house all of the other components. This means that within the index.js file we only need to render the one component in our React DOM render method.

We then create a <Header> component – being sure to import react at the start and export the component at the end – and use this as the basis for additional <Order> and <Inventory> components. These represent the three main sections of the app.

Video 7: Passing Dynamic data with props

Props and State are fundamental to React.

Wes explains that props (which stands for properties) are similar to HTML attributes in the sense that they tell a component (or element in the case of HTML) what to display. They give components the information they need.

State, on the other hand, is where the data lives. It is where the current state of the components in your app are stored.

Props are essentially what makes a React app dynamic.

There are two key parts to using props:

  • Defining a prop and passing the data when instantiating a component from the parent component
  • Displaying the prop within the child compontent itself

When it comes to defining a prop, there are no pre-existing props – you can name them pretty much any way you like.

When passing through data, if it’s a string you can just put it in quotation marks. If it’s anything other than a string, put it into curly braces.

In our Catch of the Day project, Wes asks us to add a prop called “tagline” to the <Header> component like this:

<Header tagline="Fresh Seafood Market" />

In terms of displaying props, we simply refer to the property that we defined like this:

<p>{this.props.tagline}</p>

In the code above, “this” refers to this specific instance of the component. Considering we can instantiate as many <Header> components as we like, we could pass through a different tagline prop value for each one and by using this we would always be referring to that specific instance of the component.

Finally, Wes shows us a useful little tip within your browser’s dev tools.

In the regular ‘Elements’ tab that shows the HTML, you can select an element and then type $0 in the console to show that element which you can then explore as a node or object.

With React, you can do the same – except in this case it’s with $r. It will output the component along with all of the ‘internal’ information for that component, such as it’s props.

Video 8: Stateless Functional Components

The components that we’ve created so far have been React ES6 Class components that have simply included a render method to output something. A simplified example of the Header component would be:

class Header extends React.Component {
  render() {
    return (
      <span>{this.props.tagline}</span>
    );
  }
}

Wes takes us through some of the code in the finished app and it becomes clear that components can get a lot more complex. The components we’ve created are relatively simple things – and this is the point…

Introducing Stateless Functional Components

Components that don’t do anything – that mainly just display information that is passed to them – represent a perfect opportunity to simplify further. We would convert these into stateless functional components.

A stateless functional component looks like this in ‘regular’ JS:

function Header(props) {
  return (
    <span>{props.tagline}</span>
  )
}

Compared to the React Class style of component, it is quite a bit simpler from the outset.

Notice how when moving to a stateless functional component and writing regular JS within curly braces, we no longer have to use this when displaying a prop. This is because the props have been passed in as the argument.

We can actually go even further by using ES6 syntax and converting the regular JS function into an arrow function with an implicit return (no need to use return as it’s implied by the opening brackets after the arrow). The result looks like this:

const Header = props => (
  <span>{props.tagline}</span>
)

It’s worth bearing in mind that you’ll need brackets around props if you have more than one argument in the function.

A further option we have to tweak this function is to destructure props into their own variables. This means we no longer have to use props when referring to a prop we want to display.

const Header = ({tagline}) => (
  <span>{tagline}</span>
)

So, what we’re doing here it taking the value of a property of an object and placing it in a variable, making it a more simple reference.

So, not only have we brought 7 lines down to just 3, but arguably we’ve made the JSX that we want to render shorter (and thus quicker to write, potentially less prone to syntax errors, etc) as there’s no need to use this.props.tagline when we can just use tagline.

So, the lesson here is; if you have a component that just gets passed some props and returns some JSX then a stateless functional component should be considered. It makes code a bit more legible/easier to understand and your app will potentially benefit from improved performance, too.

Video 9: Routing with React Router

Wes seemed to run through this one at the speed of light compared to the previous videos, so let’s break it down…

We’ve been building an app which we know has two different ‘screens’ or pages that feature a single main component; the Store Picker and the App. We need each of them to be available on different URL paths so that we can navigate between them. It’s worth bearing in mind we also need to cater for 404 Not Found errors when a user arrives at a non-existent page.

To do this, we need a router. There are several available, but the main ones are React Router and Next.js. These packages provide us with several components that allow us to do all of the above.

Wes’ recommendation is to create a new Router component of its own (in its own .js file) and then render this instead of either <StorePicker> or <App> from the index.js render method.

This is where it becomes clear; the Router component is like arriving at a junction and your satnav telling you which way to turn. We get to the junction (the Router component) and decide where we go from there (<StorePicker>, <App> or elsewhere).

To get started, we’ll want to import the bits that we need like so:

import { BrowserRouter, Route, Switch } from 'react-router-dom';

We’ll then create a stateless functional component called Router and start using the imported components:

const Router = () => (
  <BrowserRouter>
    <Switch>
        <Route exact path="/" component={StorePicker} />
        <Route path="/store/:storeId" component={App} />
        <Route component={NotFound} />
    </Switch>
  </BrowserRouter>
);

According to the creators of React Router, “A <Switch> looks through its children <Route>s and renders the first one that matches the current URL.” It’s a bit like a regular JavaScript switch statement.

Simple enough. Each <Route> is a possible path to take depending on the conditions. The conditions in this instance are the path attributes/arguments we’ve supplied and the qualifier in the first case (exact).

The final part to mention is the inclusion of :storeId in the second <Route>. This part acts as a sort of wildcard that will run on any matching path, e.g. /store/123 or /store/abc.

The clever bit here is that :storeId gets stored as a param prop in the component that the <Route> renders (in this case <App>). If we go to a matching URL that’ll render the <App> component (e.g. /store/123) and open up React Dev Tools, we can see that our <App> component now includes storeId as a prop under match and params.

Although Wes doesn’t show us in this video (I’m sure it’ll come later), it’s clear that we can now use storeID in our app as it’s a prop. For instance, we could display it by using:

<span>Store ID: {match.params.storeID}</span>

Video 10: Helper and Utility Functions

In this video, Wes explains how he uses some functions throughout the app that don’t necessary need to be React components. For example, a function to convert currency or get a random string. These are ‘helper’ functions and they sit outside of the components folder in a helpers.js file, alongside index.js.

export vs. export default

Wes uses this opportunity to point out the difference between export and export default.

When importing from another JS file, we can either name the specific function or we can get the default. If we want to get the default, we just name the exported function:

import React from "react"

The capitalised React is the important part here – it represents the default function.

To import specific functions from a file (that isn’t the default), you’ll use curly braces for the name. Here’s the example from the React Router lesson:

import { BrowserRouter, Route, Switch } from "react-router-dom";

As you can see BrowserRouter and the other functions are specifically imported here, rather than the whole package.

<input> value in React

This lesson also teaches us an important ‘quirk’ with React/JSX and <input> elements.

When it comes to setting a value of an <input>, we can’t just do what we’d assume:

<input type="text" value="hello" />

This throws an error. Much in the same way we must use className instead of class on elements to add CSS classes, we need to use defaultValue instead of value on input elements. So, a correct example would be:

<input type="text" defaultValue="hello" />

Now, connecting this to the whole point of this lesson – the introduction of the helper functions – we could use one of our imported functions like so:

import { getFunName } from "../helpers";

// setup of the component, etc...

<input type="text" defaultValue={getFunName()} />

Video 11: Events, Refs and this Binding

Events in React are written similarly to regular JavaScript or jQuery, except that they’re done inline.

Whereas in JS you might created a button, add a class to it, then use that class as a selector in a function and create event listeners, etc. In React it’s more tightly coupled with the component.

In the background, they’re wrapped in something called a SyntheticEvent which ensures events work across browsers and are consistent.

Example React Event

Here’s an example of a very simple event which calls a function in a component:

// setup of the component, etc...

handleClick() {
  alert("Hey!");
}

// render method, etc...

<button onClick={this.handleClick}>Click me!</button>

First, we’ve added a camelCase event (“onClick”) to the element and then given it a function to run (“this.handleClick”).

As you can see, it’s slightly different from how you might do an inline JavaScript event in regular HTML. We’ve put it in curly braces so that React interprets it as a regular JS function, and we’ve also not included any brackets after the function name to hold any arguments. If we do this, it’ll be run automatically on loading rather than when the event is triggered.

Submitting the Store Picker Form

If we try submitting the form we have at the moment in our Catch of the Day app, it’ll just refresh the page. This is because if we don’t declare where the form should submit to, by default it will submit to the page itself. As we haven’t got any server-side code to handle the submission or return some instructions, it just refreshes the page.

So, what we need to do is attach an onSubmit event to the form and tell it to run a custom function (a method of our component) that’ll define what to do on submission. The element with the event looks like this:

<form className="store-selector" onSubmit={this.goToStore}>

In terms of the method, we need it to do three things:

  1. Stop the form from submitting
  2. Get the value of the <input> element that holds our store name
  3. Load the next page

Preventing the Form From Submitting

As we’re dealing with regular JS in the component (as opposed to JSX in the component’s render() method), we deal with preventing events in the same way we normally would. Here’s our custom goToStore method:

goToStore(event) {
  event.preventDefault();
}

Accessing Input Values

A quick tip from Wes; we generally don’t want to touch the DOM directly. This means we shouldn’t get the value of the input by doing something like document.querySelector(‘input’) or $(‘input’) in the case of jQuery. Instead, there’s a couple of other React ways to do it:

  1. Refs (which does touch the DOM, but let’s go with it)
  2. Syncing the input with State
Refs

Let’s start with refs. Refs are just references and they involve creating a new property to store the reference, like so:

myInput = React.createRef();

We then make the ‘connection’ to the reference above by adding a ref attribute to the input element like this:

<input ref={this.myInput} ... />

Great! We now have a reference to the input element and would expect to be able to access its value directly from within our new function. Something like:

goToStore(event) {
  event.preventDefault();
  console.log(this.myInput);
}

Well, not so fast!

this Binding

All of the methods that are part of React – such as render() and lifecycle methods like componentDidMount() – know what “this” is as they come directly from the React.Component class.

All custom methods – like goToStore() we created above – are not bound by default, so we need to bind “this” to the component explicitly.

One way to do this is to add an ES6 constructor and do the binding in there:

constructor() {
  super();
  this.goToStore = this.goToStore.bind(this);
}

Alternatively, we can turn our custom method into a property of the component by using an ES6 arrow function:

goToStore = event => {
  event.preventDefault();
  console.log(this.myInput);
}

The second option is clearly shorter and cleaner as we’re making very few changes to convert our existing method, though it’s perhaps a little more nuanced and needs a reasonable understanding of ES6 arrow functions to avoid the pitfalls of syntax errors if you’re not used to them.

Note that console.log(this.myInput) does not give us the input value, just a reference to the element. Accessing the value is coming in the next video.

Video 12: Handling Events

This video is pretty much a continuation of the last, so we’ll get back into accessing the value of an input element.

Getting the Input Value

We started with this.myInput as a reference to the input element. To access the value property, we need to use current.value (as opposed to value.value that Wes writes in the videos). So, the code will look like this:

goToStore = (event) => {
  event.preventDefault();
  console.log(this.myInput.current.value);
}

With the second of the three things we wanted to accomplish in the last video now complete (get the value of the element that holds our store name), we now need to load the store page URL using that store name.

pushState

To load a new URL without refreshing the page and losing the data we have (the store name, for example), we are going to use pushState and React Router.

If we use React Dev Tools to view our StorePicker component, we’ll see what we saw in Video 9 when we were looking at the :storeId param in the match method. The other props include history and location which are available because the StorePicker component is a child of the Router component.

Inside the history prop is a push method – this is the one we want!

So, first, let’s store the store name in a variable like this:

const storeName = this.myInput.current.value;

Then we’ll use that variable to push the new URL path within an ES6 template literal:

this.props.history.push(`/store/${storeName}`);

The final goToStore method looks like this:

goToStore = (event) => {
  event.preventDefault();
  const storeName = this.myInput.current.value;
  this.props.history.push(`/store/${storeName}`);
}

Now, clicking the ‘Visit Store’ button will take us to a URL like /store/repulsive-quaint-elves and because that matches the Route condition in our Router component (<Route path="/store/:storeId" component={App} />) then the store page loads. Hooray!

Video 13: Understanding State

TBC

Categories
Amazon Web Services (AWS) WordPress

How to Setup a WordPress Website on AWS EC2 with Bitnami

Moving from a popular hosting provider – whether generic (i.e. GoDaddy) or WordPress-specific (i.e. SiteGround) – over to AWS can be a bit daunting at first (I know it was for me!). With this handy guide, however, you can get a new WordPress site up and running on an EC2 server in less than 10 minutes, getting familiar with AWS along the way.

Categories
Amazon Web Services (AWS) WordPress

How to Find Your Password for WordPress on AWS EC2 (Bitnami)

You can get a new server setup on AWS EC2 with WordPress installed via Bitnami quite quickly and relatively easily, but actually logging into WordPress itself can sometimes stop people in their tracks.

In this quick guide I’ll show you two ways to get your password for WordPress from your AWS EC2 server.

Categories
Amazon Web Services (AWS) WordPress

How to Connect via SSH to an AWS EC2 Instance Running Bitnami WordPress

An SSH connection gives you control over the configuration of your server. From handling folder permissions to simply removing the Bitnami banner that comes enabled as standard, you’ll need SSH access to do a lot of things.

If you’ve installed WordPress on an AWS EC2 instance using a Bitnami AMI but you don’t know how to connect via SSH, let me help you with this quick guide.

Categories
Google Tag Manager (GTM)

How to Check if Google Tag Manager is Working

There’s no doubt that Google Tag Manager is a great tool. One of the benefits it brings is that, once implemented, it removes the need for (and burden on) developers to implement various technical requirements. In order to get to that point where everyone’s happy, you need to make sure that Tag Manager is even working in the first place.

Categories
Facebook Ads Google Tag Manager (GTM)

How to Add Your Facebook Pixel Using Google Tag Manager

Facebook Ads is an incredibly popular platform for running advertising campaigns, but in order to get the most out of it you’ll need to make sure that the Facebook ‘pixel’ is implemented on your website. This is where Google Tag Manager comes in as it’s easier to implement the pixel through this as opposed to via the website’s code itself (which can be challenging and may require a developer).

Categories
Google Analytics Google Tag Manager (GTM)

How to Track Button Clicks Using Google Tag Manager

Google Tag Manager can be used to easily track clicks on any button on your website and send usage data to analytics platforms such as Google Analytics. You can then use that data to measure performance and make informed decisions. If you’re not yet measuring feature usage on your site then this is definitely a good place to start.

Categories
WordPress

How to Enable Shortcodes in Text Widgets in WordPress

If you make use of shortcodes and widgets on your WordPress site (which is probably most of us), you might find that they don’t particularly work well together straight out of the box. For example, including a shortcode in a Text widget does not execute the shortcode itself and just displays the shortcode as text (instead of the actual output of said shortcode).

Categories
Google Tag Manager (GTM)

How to Give Access to Google Tag Manager

If you need to let someone else have access to Google Tag Manager – whether that be a freelance developer or a colleague – then you can accomplish this in less than 30 seconds. Just follow the simple steps below.

Categories
Google Analytics Google Tag Manager (GTM)

How to Add Google Analytics to Google Tag Manager

Looking to add Google Analytics to your website through Google Tag Manager? Maybe you have GTM installed but don’t have direct access to the code to place GA directly. Maybe you want to keep all of your tracking scripts in one place, within a GTM container. Either way, here’s how you add the GA tracking code to via GTM.

It’s a given, but first you need to make sure you have a Google account with both Analytics and Tag Manager setup. Assuming you’ve done that, let’s get started.