Explore Free Web Development Tutorials – GameDev Academy https://gamedevacademy.org Tutorials on Game Development, Unity, Phaser and HTML5 Wed, 22 Feb 2023 21:14:27 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 https://gamedevacademy.org/wp-content/uploads/2015/09/cropped-GDA_logofinal_2015-h70-32x32.png Explore Free Web Development Tutorials – GameDev Academy https://gamedevacademy.org 32 32 Create a Basic Quiz using JavaScript https://gamedevacademy.org/javascript-quiz-tutorial/ Mon, 19 Dec 2022 01:00:15 +0000 https://coding.degree/?p=809 Read more]]>

You can access the full course here: JavaScript Mini-Projects – Language Learning Game 

Also available for school usage via the Zenva Schools platform which offers online courses, classroom management tools, reporting, pre-made course plans, and more for teachers.

Showing a Question

In this lesson we will start by simply showing a single question on the web page. To do this we will represent the question in a JavaScript variable, then display the question in HTML.

JavaScript Spanish quiz with basic UI

Project Setup

Like any web development project we need two key tools: code editor and browser. You can use your favorite code editor or an online development environment together with Google Chrome, Firefox or any modern web browser. In this course we use the free and popular Visual Studio Code ( https://code.visualstudio.com/ ). In your code editor, create two files.

Code File Description
index.html Our website HTML code for structuring and displaying our app in a web page
script.js Our JavaScript code for app logic and functionality

Question – HTML Web Page

Let’s starting by setting up the structure of our web page to display our question and alternatives. Inside index.html add the following HTML DOM (Document Object Model) elements as well as a reference to our JavaScript code file, script.js

<div id="title"></div>
<ul>
    <li class="alternative"></li>
    <li class="alternative"></li>
    <li class="alternative"></li>
    <li class="alternative"></li>
</ul>

<script src="script.js"></script>
HTML Code Description
<div id=”title”></div> The <div> tag is a generic HTML element. We provide an id so we can uniquely reference this HTML element from within our JavaScript code and CSS styling
<ul></ul> An Unordered List ( <ul> tag ) is a HTML element used to wrap HTML List Item elements ( <li> tags )
<li class=”alternative”></li> Add four List Items ( <li> tags ) to hold the four alternatives we show the user to select from. We provide each List Item with a CSS class of alternative so we can reference them from within our JavaScript code and CSS styling
<script src=”script.js”></script> At the bottom of our index.html file we add a reference to our JavaScript code file, named script.js, which will be loaded by the browser when this HTML web page loads

Question – JavaScript Object

Let’s start coding inside script.js, setting up our question as a JavaScript Object.

// define the object for the question entity
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};
JavaScript Code Description
let question = { properties: values }; Using the JavaScript let keyword and the curly braces ( {…} ), we set the variable question to be equal to a JavaScript Object which can contain any number of property:value combinations. To complete the syntax, follow the curly braces with a colon
title: ‘gato’,
alternatives: [‘dog’, ‘cat’, ‘bird’, ‘fish’],
correctAnswer: 1
Using the JavaScript Object Property:Value syntax (property and value separated by a colon and each combination separated by a comma). Here we assign our question variable three properties: title (String), alternatives (Array) and the array index of the correctAnswer (Number)

Question – showQuestion() Function

To keep our code organized and flexible we will create a JavaScript Function to show the question ( showQuestion ). This will enable us to execute the function by calling it, passing in the question object.

// define the object for the question entity
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// function for showing the question
function showQuestion(q) {
  // code
}

// call the function
showQuestion(question);
JavaScript Code Description
function showQuestion(q) { // function code } Function Definition. We define a function named showQuestion and set it up to receive a parameter named q, which will represent the question inside the function block
showQuestion(question); Execute Function. We call the function named showQuestion passing it the question object previously defined as an argument

Working with the DOM

The DOM connects the web page to our JavaScript code. Inside script.js, we use DOM Methods on the Document (Object representing the currently loaded web page) to select DOM Elements. Working with the DOM from JavaScript is a two step process. First, we select the DOM Element then we modify the DOM element.

Question – Show on Web Page

In our case, the question word (Spanish word) is stored in the question Object under a String property called title. In the HTML we represented the question word as a <div> with an id of title. Inside the showQuestion function, add logic to select and modify this DOM element.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// modified code
function showQuestion(q) {
  // new code
  let titleDiv = document.getElementById('title');
  titleDiv.textContent = q.title;
}

// existing code
showQuestion(question);
JavaScript Code Description
let titleDiv = document.getElementById(‘title’); Using the DOM method getElementById(),  passing it the id as a String (in our index.html file we set this id to be title), we select the element storing a reference to it in a variable ( titleDiv )
titleDiv.textContent = q.title; With a reference to the DOM element stored in a variable (previous step), we can now modify it. To do this, we set the textContent property of the DOM element ( <div> with an id of title ) to be the title property stored in our question variable (received as parameter q inside our function)

The web page now shows our question followed by an empty Unordered List ( represented by default with bullet points ) which will hold our alternatives.

JavaScript quiz with unordered list for answers

Alternatives – Show on Web Page

In our case, the alternatives (English words) are stored in a question Object under an Array property called alternatives. In the HTML we represented the alternatives as an Unordered List ( <ul> ) containing List Items ( <li> with a class of alternative ). Inside the showQuestion function, add logic to select and modify these DOM elements.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// modified code
function showQuestion(q) {
  // existing code
  let titleDiv = document.getElementById('title');
  titleDiv.textContent = q.title;

  // new code
  let alts = document.querySelectorAll('.alternative');
  console.log(alts);
  alts.forEach(function(element, index){
    element.textContent = q.alternatives[index];
  });
}

// existing code
showQuestion(question);
JavaScript Code Description
 let alts = document.querySelectorAll(‘.alternative’); Since we are selecting DOM elements by class (multiple DOM elements returned) rather than by id (one unique element returned) as we did above, we use the DOM method querySelectorAll(),  passing it a CSS Selector (in this case, class name preceded by a period – ‘.alternative’). A list of matching elements is returned and we store a reference to these elements in a variable ( alts )
console.log(alts); Log the variable alts to the console (see image below). Notice that alts contains each List Item element ( <li> with class of alternative ) in an array-like ordered list called a NodeList
 alts.forEach(function(element, index) {
element.textContent = q.alternatives[index];
});
We can now modify each element to contain one element from our question variable alternatives array property. To do this, we set the textContent property using the JavaScript forEach method which loops over each element in the alts variable

Console shows a list of DOM elements which will contain our question alternatives (<li> with class of alternative ).

Console showing list of alternative quiz answers

The web page now shows our question followed by our list of alternatives.

Quiz questions with unordered list showing various answer options

Handling User Input

In this lesson we introduce the concept of handling user input. We will do this by adding an event listener to the alternatives List Items so we can check if the user picks the correct answer.

Event Listeners – Simple Button Click

Before we add the functionality for our user to choose the answer they believe is correct, let’s start with a simple example of using an event listener to know when a user has clicked a button. When the user clicks the button, we log the message Clicked! to the console. Starting with the code from the last lesson, add the following code below the showQuestion(question) function call.

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// existing code
function showQuestion(q) {
}

// existing code
showQuestion(question);

// new code
let btn = document.getElementById('btn');
btn.addEventListener('click', function() {
  console.log('Clicked!');
});
JavaScript Code Description
let btn = document.getElementById(‘btn’); Select Button Element. Using the DOM method getElementById(),  passing it the id as a String (in our index.html file we set this id to be btn), we select the Button element storing a reference to it in a variable ( btn )
btn.addEventListener(‘click’, function() { console.log(‘Clicked!’); }); Add Click Event Handler. With a reference to the Button element ( btn ) which is known as the Event Target, we can now attach an event handler by calling the method addEventListener(), passing it a function with two arguments: a case-sensitive String representing the event type we are listening for ( ‘click’ ) and a function to call when the event occurs. When the event occurs, we run the code inside the function which in this case logs the word Clicked! to the console

Quiz with Click Me button under it

Note: you can optionally remove the code we just wrote as an example before continuing with the next section.

Event Listeners – Alternatives List

Next, let’s add event listeners to each List Item element ( <li> with a class of alternative ). As we did in the above Button example, we could assign each element an id, then select and add the event listeners one by one. However, since we already have a reference to this list from our last lesson (stored in the variable alts ), we can add the event listeners to each List Item element ( <li> with a class of alternative ) inside the existing alts.forEach() method. Recall that the function passed to the alts.forEach() method has two parameters, element and index. We can use the element parameter ( each alternative ) as our Event Target to attach the event handler to on each iteration of forEach. We can then use the second parameter, index, to check against our question’s correctAnswer property. If this comparison is true then we log Correct Answer! to the console else we log Wrong Answer!

// existing code
let question = {
  title: 'gato',
  alternatives: ['dog', 'cat', 'bird', 'fish'],
  correctAnswer: 1
};

// existing code
function showQuestion(q) {
  // existing code
  let titleDiv = document.getElementById("title");
  titleDiv.textContent = q.title;
  
  // existing code
  let alts = document.querySelectorAll('.alternative');
  
  // modified code
  alts.forEach(function(element, index){
    // existing code
    element.textContent = q.alternatives[index];
    // new code
    element.addEventListener('click', function(){
      if (q.correctAnswer == index) {
        console.log('Correct Answer!');
      } else {
        console.log('Wrong Answer!');
      }
    });
  });
}

showQuestion(question);

Click each alternative one at a time and notice the result in the console. The only one that returns true is in fact the correct answer! ( gato is Spanish for cat ).

JavaScript quiz showing clickability of answers in the Console

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

Transcript

Showing a Question

In this lesson, we are gonna get started with creating our project. And we’ll concentrate on something simple, just showing one question on the screen. In particular, we’re gonna be looking at how to represent a question as a variable in JavaScript. And we’ll be showing a question which is composed of a question title, as well as the possible alternatives, possible answers on the HTML document.

Let’s head over to our code editor and get started. I’ve created a new project, which includes index of HTML as well as an empty script file. To represent the question in JavaScript, we’ll be using an object, as that allows us to store an entity with different properties in a variable.

Let’s create our variable, it’s going to be called question. We know that questions have a title, which is the word in Spanish. Let’s create a sample question here. The title will be Gato, which means cat. Then we’re gonna be showing to the user a list of possible solutions. And those we’re gonna call alternatives. The alternatives the user will see, let’s say that they will be dog, cat, bird, and fish.

We know that the correct solution here is cat, which is in position. If we start here, this is position zero, this is position one. And so we want to store the correct answer here, just so that we can check later on. And that’s going to be in position one. Optionally, you can store the actual word as the correct answer. And I do have to say that for everything that I do here, there are many other alternative solutions. So feel free to explore other architectures, if you want to get a bit deeper into the language.

Next, in order to show my question to the user, I’m gonna have to create some containers where the different information will be displayed. So let’s go to HTML, and add our code above the script inclusion. Normally, you always add your script inclusion at the bottom of your document right before the closing of the body tag. I’m gonna add a div for the question title, I’m gonna give it the ID of title. Let’s type in some sample code for now.

So I should be seeing in the browser, that word up here. Next, for the alternatives, we’re gonna be using a list, an unordered list, and each one of the list items will show a different possible response. We wanna duplicate this line many times. And to do so in Visual Studio, you can press Ctrl C, Ctrl V, or Command C, Command V on the Mac, like so. And that will show what this is looking like.

What we want to do now is of course, replace this data by our own data. So I’m actually going to delete this because I just want to show you what that was going to look like. We’re going to give our list items a class, which is going to be called alternatives, alternative like so. Great, so let’s now go to JavaScript and start by adding the title here of the word that we want to show, at the moment it’s all empty.

The first step here will be to select the DOM element that we want to modify. And we’re gonna store that in a variable. I’m going to call my variable title div. And we’re gonna select this by doing document dot get element by ID, and then enter the ID, which is title. Going to zoom out a little bit, there we go. So now that we’ve selected it, now we can modify it. Title div dot text content, will be equal to question dot title. And that should be enough to show that title there, great.

To keep my code organized, I’m gonna place all of these in a function so that then we can call that function multiple times. Start by typing function. The name here will be show question. And the parameter will be that question that we need to pass in. So let’s call this question Q. And let’s move all of this code inside of our function. And make sure to add some indentation just for readability. And instead of question the title, we’re going to do q dot title, as that will be gathered from here.

And then we if we want to call this function, we can just do show function, and we can pass in our question. So if I run this code, it should be the exact same result.

Great, well, now let’s address the last part, which is the alternatives part. If you’re wanting to select every one of these, one at a time, you could go and add a certain ID to each one of them. But since they all behave in the same way there is a different way of doing this, which is to select it all by the class, in this case alternative, and then work on an iteration and change all of them.

Let’s go and select them all. In this case, we’re gonna be selecting them by class. In CSS, when you select by class, you type dot alternative, or name of the class, and then you add certain CSS rules. That’s how CSS works. Well, the good thing about the DOM API is that there’s a way to select everything by using the same type of queries that you’ll use in CSS. So in this case, we’re going to be selecting by a query.

And for that, we are going to be using document dot query selector all. This will go and select all of the elements that satisfy a certain CSS query. In this case, it will be dot alternative. That is the same query that you would use in CSS. We definitely want to put this in a variable. So let’s call this alternatives like that, just an average of an average deviation.

So after we’ve selected this, it’s always a good idea to check in the console, to be sure that it’s working as expected. And you can see here that we have four Li nodes selected. So four list items. To go over each one of them, we’re gonna be using the for each method, which is part of the result that you get from when doing these queries. For each takes a function as a parameter. And we can pass in different parameters here, one of them is the element itself and the other one is the index the position of the element.

Let’s open the function body. And in the function body, if we call this element variable here, this will give us access to each one of these as the iteration progresses. So we can go and change their values. Let’s type element dot text content. And we could change the value to let’s say, a. You can see that they’re all being modified to a. But we don’t wanna modify them to a, we wanna modify them to the corresponding alternative. For that we can access our q variable, which contains the question we’re passing in and typing q dot alternatives.

And now what position is this going to be? Well, the good thing here is that we have that index parameter. So that will start from zero and increase in each iteration. So if we do that, we can actually get all of these one at a time. Let’s save and check to see if it works.

And there we go. Well, that is all for this lesson. As you can see, we’ve created the basic HTML template that we’re gonna be using in our app. And we created a method that receives a question as a parameter. And inside of that method, you can modify the title that you’re gonna show as well as showing each one of the alternatives. For the alternatives, we selected them all using query selector all and then we iterate through each one of them and change their corresponding values. Thank you for watching, I will see you in the next lesson.

Handling User Input

In this lesson, I’m going to start with the code of the previous lesson. We are going to be taking that approach going forward, so that we can build up our app. The way user interaction will work here, is that the user will be able to click on any of the alternatives, and will check whether that’s the correct answer. But to keep things simple, at first, let’s go and try a simple example of using click events.

I’m going to add a new element here in my index.html file. It will be a button. It’s going to have a certain ID. And it will just say Click Me. We want to be able to listen to these clicks and show something in the console. For that, we’re going to start by selecting our button, document.getElementById, and the ID here it needs to be entered, and this will grab our button, and let’s refresh here so that we can see the button.

To listen to click events, type the name of your variable, and then .addEventListener. This is a method that allows us to pass what’s called an event listener. That basically means we are going to specify what event we want to listen for in this case, we want to be listening to a click event. And whenever there is a click event, something needs to happen, and that will be represented as a function here. This function will be executed every time that there is a click on the button. I can go and I can type console.log, and this will say, clicked, save, reload your index.HTML file, and if you click now, you’re going to see that every time you click, you are running these functions. So that’s really how they work.

Next, we want to be listening to events for all of these list items. You could go and give them all a separate ID, and you could select them individually and check that, but since we’re already selecting them all using query selector all, and we are iterating through them, for now, we are going to be adding our event listening here, and check that the answer is correct.

I say for now because there will be some changes made to this architecture later in the course. So for now, we’re going to type in our element, which is this list item. And we’re going to add that same event listener, add event listener. We are listening to click events, and let’s create our function here. In the body of the function, I’m going to access my element again and change the text content, just so that we can be sure that this is working.

If I refresh and I click on this list items, you can see that their content is being changed. And that means that our click listening is working.

And now we can get rid of these, and instead check for the correct answer. Now we need to get the answer that the user entered, which would be the position index. So let’s check the correct answer. And for now we’re going to list inside of here, later on we’re going to move it to a separate place.

How do we know if the answer that was submitted is the correct one? Well, we need to use an if statement to check, first of all, what’s the correct answer? The correct answer would be q.correctAnswer. So q.correctAnswer needs to be equal to whatever the user clicked on. And that would be in our case, the position of the current alternative, starting from zero, so that is index that we have already used to show the text. We’re also going to use that to check for correctness. So if this is equal, then we’re going to show in the console, correct answer.

Let’s go and save and refresh, and let’s check that, see if it’s working. I’m going to click on dog and nothing is happening. If I click in cat, then I see correct answer. If I click on bird and fish, nothing happens. We can add an else statement here to also show when something is not the correct answer, in the console. So let’s go and save, and you can see that’s the wrong answer, that is the correct answer. That’s the wrong answer. And that is the wrong answer.

Great, so we have a basic click functionality. This button that we added, we can definitely get rid off. So I’m going to leave that up to you. I’m going to keep that in this file, but in the next lesson, that is not going to be around. Well, that is all for this lesson. You have learned something really useful which is how to detect for clicks, basics of user interaction. Now your applications on projects can have a whole new layer of interactivity to them. Thank you for watching this lesson. I look forward to seeing you in the next one.

Interested in continuing? Check out the full JavaScript Mini-Projects – Language Learning Game course, which is part of our Full-Stack Web Development Mini-Degree.

For teachers, you can also try Zenva Schools which offers online learning suitable for K12 school environments and offers a wide array of topics including JavaScript, Python, Unity, and more.

]]>
How to Submit Forms and Save Data with React and Node https://gamedevacademy.org/how-to-submit-forms-and-save-data-with-react-js-and-node-js/ Sun, 18 Dec 2022 14:24:31 +0000 https://html5hive.org/?p=1228 Read more]]> While there are multiple ways to deal with forms on the web, the popular React library offers a unique and easy way to do it.

In this tutorial, we’re going to explore how to combine React, Node.js, and various techniques to allow users to submit forms – and then save that data so we can use it for whatever backend purposes we might need.

If you’re ready to explore some core web fundamentals, let’s jump into it.

Intro

In my last two tutorials, I covered the basics of React.js and form error handling in React.js. In each case, I used hard-coded data. React is a front-end library, providing no easy way to save to, or read information from, a database or file. That is the part we will cover in this tutorial – but if you need some refreshing on React, especially on Props & States, feel free to read the linked resources.

React is a user interface library, so it is common to use a different library or framework to do all the back-end work. One of the most common pairings is React.js with Node.js. Lucky for us, we already have a tutorial on the basics of Node right here!

The main React Facebook tutorial does something similar to what we will be doing with this tutorial, and they also provide a Node server, as well as many other server examples within their download files. Although our Node server will be similar, our front-end React interface will have a few extra complications. In fact, I’ll be using the same files from my form error handling React tutorial, with a few updates that will allow the saving and reading of information from a file or database.

Download the tutorial files & prerequisites

You can download all the files used in this tutorial from here.

As hinted above, we do assume that you know the fundamentals of web development (especially JavaScript which heavily plays into both Node and React). For those a bit new to these topics – or even just in need of a review – you might want to try some online courses first to make sure you’re ready.

We also don’t recommend React or Node for classroom teaching. Instead, you can check out K12-friendly web development courses on Zenva Schools that will be perfect for the classroom.

BUILD YOUR OWN GAMES

Get 250+ coding courses for

$1

AVAILABLE FOR A LIMITED TIME ONLY

Learn React online

If you are keen to learn React from the ground-up feel free to check Learn and Understand React JS on Zenva Academy which covers all the basics + lots of bonus topics like React Router and Flux.

Tutorial requirements

  • You must have basic knowledge of React.js and JavaScript. For a beginner’s guide to React, please see my past tutorial. In addition, I will be using many of the same functions from my other React tutorial, so you may want to read that one as well.
  • You will need to use the React library, although we will be using CDN links to get around that during testing.
  • You will need to download a text editor of some sort. You can use just a plain text editor, although Notepad++ is popular on Windows, and TextMate is popular on Mac machines. An editor with code highlighting capability is preferable.
  • You will need to read and follow the directions in most of the beginner’s Node.js tutorial in order to create the server that will be used later in this tutorial.

Making revisions to a React user interface

I will be using the same files I created for the error handling tutorial, with some simple revisions that will make it possible to read and save data. The files with all the revisions are provided above. The index file from the previous tutorial remains the same, but now we are going to be pulling data from a file, then posting new form entries to the file.

The original file was set up with some of the code needed to post and read data, but some parts were commented out, since we had no server to do the work. All we have to do is uncomment those lines, and we have this:

var DonationBox = React.createClass({
  getInitialState: function() {
    //this will hold all the data being read and posted to the file
    return {data: []};
  },
  loadDonationsFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentDidMount: function() {
    this.loadDonationsFromServer();
    setInterval(this.loadDonationsFromServer, this.props.pollInterval);
  },
  handleDonationSubmit: function(donation) {
    //this is just an example of how you would submit a form
    //you would have to implement something separately on the server
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: donation,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  render: function() {
    return (
      <div className="donationBox">
        <h1>Donations</h1>
        <DonationList data={this.state.data} />
        <DonationForm onDonationSubmit={this.handleDonationSubmit} />
      </div>
    );
  }
});

ReactDOM.render(
  <DonationBox url="/api/donations" pollInterval={2000} />,
  document.getElementById('content')
);

So far, everything we have here is similar to Facebook’s Commenting tutorial. We save all the data from the file in a DonationBox component state, then set an interval to pull new donations from the server so the user can see new donations as they come in, in close to real time. On each form submission, the data is pushed to the database (or in this case, the file). We include JQuery in the index file in order to make the loading and submitting of data easier.

Let’s continue with the changes I’ve made to the form before discussing the server side.

Displaying new data from everyone

We now have a new listing that will display all new donations coming from all users.

var DonationList = React.createClass({
  render: function() {
    var donationNodes = this.props.data.map(function(donation) {
      return (
        <Donation
          contributor={donation.contributor}
          key={donation.id}
          amount={donation.amount}
        >
          {donation.comment}
        </Donation>
      );
    });
    return (
      <div className="donationList">
        {donationNodes}
      </div>
    );
  }
});

Similar to the Facebook tutorial, we are mapping out all the data from the JSON file into a new Donation component for each entry. We then display the entire donationNodes list. Let’s take a look at the new Donation component:

var Donation = React.createClass({
  render: function() {
    return (
      <div className="donation">
        <h2 className="donationContributor">
          {this.props.contributor}: ${this.props.amount}
        </h2>
          {this.props.children.toString()}
      </div>
    );
  }
});

This is actually simpler than what we see in the Facebook tutorial, because we are expecting comments by contributors to be in plain text. We are simply displaying the main donation information, leaving out anything private. In fact, we are only saving the public information for the purposes of this tutorial, but it’s easy enough to store all of the data in a database, then only display the information that is public.

So far, our additions are very similar to what you can find in the Facebook tutorial, but our original Donation app is nothing like that tutorial. This is where the changes become a little more complicated.

Submitting form data

In the original donation app, we had some fairly complicated calls to other components that allowed us to serve up multiple fields from a single component. Now that we have to think about actually saving and displaying that data, we have to add a value attribute to the components that will allow us to empty all the fields after submission, and we also have to save all the data in a state.

var DonationForm = React.createClass({
  getInitialState: function() {
    return {
      contributor: "",
      amount: undefined,
      comment: "",
      email: "",
      department: undefined
    };
  },
  handleSubmit: function(e) {
    //we don't want the form to submit, so we prevent the default behavior
    e.preventDefault();
    
    var contributor = this.state.contributor.trim();
    var amount = this.state.amount;
    var comment = this.state.comment.trim();
    if (!contributor || !amount) {
      return;
    }
    
    //Here we do the final submit to the parent component
    this.props.onDonationSubmit({contributor: contributor, amount: amount, comment: comment});
    this.setState({
      contributor: '',
      amount: undefined,
      comment: '',
      email: '',
      department: undefined
    });
  },
  validateEmail: function (value) {
    // regex from http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(value);
  },
  validateDollars: function (value) {
    //will accept dollar amounts with two digits after the decimal or no decimal
    //will also accept a number with or without a dollar sign
    var regex  = /^\$?[0-9]+(\.[0-9][0-9])?$/;
    return regex.test(value);
  },
  commonValidate: function () {
    //you could do something here that does general validation for any form field
    return true;
  },
  setValue: function (field, event) {
    //If the input fields were directly within this
    //this component, we could use this.refs.[FIELD].value
    //Instead, we want to save the data for when the form is submitted
    var object = {};
    object[field] = event.target.value;
    this.setState(object);
  },
  render: function() {
    //Each form field is actually another component.
    //Two of the form fields use the same component, but with different variables
    return (
      <form className="donationForm" onSubmit={this.handleSubmit}>
        <h2>University Donation</h2>
      
        <TextInput
          value={this.state.email}
          uniqueName="email"
          text="Email Address"
          textArea={false}
          required={true}
          minCharacters={6}
          validate={this.validateEmail}
          onChange={this.setValue.bind(this, 'email')} 
          errorMessage="Email is invalid"
          emptyMessage="Email is required" />
        <br /><br />

        <TextInput
          value={this.state.contributor}
          uniqueName="contributor"
          text="Your Name"
          textArea={false}
          required={true}
          minCharacters={3}
          validate={this.commonValidate}
          onChange={this.setValue.bind(this, 'contributor')} 
          errorMessage="Name is invalid"
          emptyMessage="Name is required" />
        <br /><br />
          
        <TextInput
          value={this.state.comment}
          uniqueName="comment"
          text="Is there anything you'd like to say?"
          textArea={true}
          required={false}
          validate={this.commonValidate}
          onChange={this.setValue.bind(this, 'comment')} 
          errorMessage=""
          emptyMessage="" />
        <br /><br />
      
        {/* This Department component is specialized to include two fields in one */}
        <h4>Where would you like your donation to go?</h4>
        <Department
          value={this.state.department} 
          onChange={this.setValue.bind(this, 'department')} />
        <br /><br />
      
        {/* This Radios component is specialized to include two fields in one */}
        <h4>How much would you like to give?</h4>
        <Radios
          value={this.state.amount}
          values={[10, 25, 50]}
          name="amount"
          addAny={true}
          anyLabel=" Donate a custom amount"
          anyPlaceholder="Amount (0.00)"
          anyValidation={this.validateDollars}
          onChange={this.setValue.bind(this, 'amount')} 
          anyErrorMessage="Amount is not a valid dollar amount"
          itemLabel={' Donate $[VALUE]'} />
        <br /><br />
      
        <h4>Payment Information</h4>
        <Payment />
        <br />
      
        <input type="submit" value="Submit" />
      </form>
    );
  }
});

As you can see, we’ve added new states for each piece of data we plan on saving. The other bits of data can always be added later, but we are just going to focus on the data that we want to display. On submit, we send all the data to the parent component to do the actual saving to the server. We then reset all the fields so they will appear empty after submission.

We also have a new method called setValue. Because we do not have form fields directly within this component, we have to have a way to set the state as we go (using the onChange attribute in each component call). Rather than create a new function for every form field, we use this single function by taking the field as a variable, and using it to create a new object that can be used to set the state for that field. The field name is included in the call to the component.

Each component call also has a new value attribute. This is what allows us to empty all the fields when the form is submitted. I’ve have also added a new text field, with an option for producing a textarea rather than a single line text field. This allows us to add a new comment field for contributors who want to say something about why they’re donating. Now let’s take a look at the few changes made to the form element components.

Emptying fields on form submission

There are no changes to the InputError component, but we do have a few small changes to the other components which will allow us to empty all the fields after submission.

var TextInput = React.createClass({
  getInitialState: function(){
    //most of these variables have to do with handling errors
    return {
      isEmpty: true,
      value: null,
      valid: false,
      errorMessage: "Input is invalid",
      errorVisible: false
    };
  },

  handleChange: function(event){
    //validate the field locally
    this.validation(event.target.value);

    //Call onChange method on the parent component for updating it's state
    //If saving this field for final form submission, it gets passed
    // up to the top component for sending to the server
    if(this.props.onChange) {
      this.props.onChange(event);
    }
  },

  validation: function (value, valid) {
    //The valid variable is optional, and true if not passed in:
    if (typeof valid === 'undefined') {
      valid = true;
    }
    
    var message = "";
    var errorVisible = false;
    
    //we know how to validate text fields based on information passed through props
    if (!valid) {
      //This happens when the user leaves the field, but it is not valid
      //(we do final validation in the parent component, then pass the result
      //here for display)
      message = this.props.errorMessage;
      valid = false;
      errorVisible = true;
    }
    else if (this.props.required && jQuery.isEmptyObject(value)) {
      //this happens when we have a required field with no text entered
      //in this case, we want the "emptyMessage" error message
      message = this.props.emptyMessage;
      valid = false;
      errorVisible = true;
    }
    else if (value.length < this.props.minCharacters) {
      //This happens when the text entered is not the required length,
      //in which case we show the regular error message
      message = this.props.errorMessage;
      valid = false;
      errorVisible = true;
    }
    
    //setting the state will update the display,
    //causing the error message to display if there is one.
    this.setState({
      value: value,
      isEmpty: jQuery.isEmptyObject(value),
      valid: valid,
      errorMessage: message,
      errorVisible: errorVisible
    });

  },

  handleBlur: function (event) {
    //Complete final validation from parent element when complete
    var valid = this.props.validate(event.target.value);
    //pass the result to the local validation element for displaying the error
    this.validation(event.target.value, valid);
  },
  render: function() {
    if (this.props.textArea) {
      return (
        <div className={this.props.uniqueName}>
          <textarea
            placeholder={this.props.text}
            className={'input input-' + this.props.uniqueName}
            onChange={this.handleChange}
            onBlur={this.handleBlur}
            value={this.props.value} />
      
          <InputError 
            visible={this.state.errorVisible} 
            errorMessage={this.state.errorMessage} />
        </div>
      );
    } else {
      return (
        <div className={this.props.uniqueName}>
          <input
            placeholder={this.props.text}
            className={'input input-' + this.props.uniqueName}
            onChange={this.handleChange}
            onBlur={this.handleBlur}
            value={this.props.value} />
      
          <InputError 
            visible={this.state.errorVisible} 
            errorMessage={this.state.errorMessage} />
        </div>
      );
    }
  }
});

The TextInput component has the simplest change because all we have to do is set the value to the props value sent to the component. We were already calling this.props.onChange from the handleChange function for real-time error processing, and simply rearranged the error processing a bit in the parent component so we can save the data. We still call the parent validation method when the user leaves the field.

We do add one additional input field to handle the textarea option. When the text field is a textarea, we have to use the textarea field. Otherwise, it’s a normal text field. There are no other changes.

var Radios = React.createClass({
  getInitialState: function() {
    //displayClass is the class we use for displaying or hiding
    //the optional "any value" text field
    return {
      displayClass: 'invisible',
      valid: false,
      errorMessage: "Input is invalid",
      errorVisible: false
    };
  },
  handleClick: function(displayClass, e) {
    //if we click any option other than the "any value" option,
    //we hide the "any value" text field. Otherwise, show it
    if (displayClass == 'invisible') {
      this.setState(
        {
          displayClass: displayClass,
          errorVisible: false
        }
      );
      this.props.onChange(e);
    }
    else {
      this.setState({displayClass: displayClass});
    }
  },
  handleAnyChange: function(e) {
    //this validation is specifically for the optional "any value" text field
    //Since we have no idea what the requirements are locally, we call the parent
    //validation function, then set the error states accordingly
    if (this.props.anyValidation(e.target.value)) {
      this.setState(
        {
          valid: true,
          errorMessage: "Input is invalid",
          errorVisible: false
        }
      );
      this.props.onChange(e);
    }
    else {
      this.setState(
        {
          valid: false,
          errorMessage: this.props.anyErrorMessage,
          errorVisible: true
        }
      );
    }
  },
  render: function() {
    var rows = [];
    var label = "";
    
    //we have passed in all the options for the radios, so we traverse the array
    for (var i = 0; i < this.props.values.length; i++) {
      //We do this little replace for when we want to display the value as part of
      //additional text. Otherwise, we would just put '[VALUE]' when passing
      //the itemLabel prop from the parent component, or leave out '[VALUE]' entirely
      label = this.props.itemLabel.replace('[VALUE]', this.props.values[i]);
      
      //You'll see that even the <br /> field has a key. React will give you errors
      //if you don't do this. This is just an axample of what's possible, but
      //you would normally add extra spacing with css
      rows.push(<input
        key={this.props.name + '-' + i}
        type="radio"
        ref={this.props.name + '-' + this.props.values[i]}
        name={this.props.name}
        value={this.props.values[i]}
        selected={this.props.value==this.props.values[i]?true:false}
        onClick={this.handleClick.bind(this, 'invisible')} />,
        
        <label key={this.props.name + '-label-' + i} htmlFor={this.props.values[i]}>{label}</label>,
      
        <br key={this.props.name + '-br-' + i} />);
    }
    
    //The "any value" field complicates things a bit
    if (this.props.addAny) {
      //we passed in a separate label just for the option that
      //activates the "any value" text field
      var selected = false;
      label = this.props.anyLabel;
      if (this.props.value != undefined && this.props.values.indexOf(this.props.value) == -1) {
        selected = true;
      }
      rows.push(<input
        key={this.props.name + '-' + i}
        type="radio"
        ref={this.props.name + '-any'}
        name={this.props.name} value="any"
        selected={selected}
        onClick={this.handleClick.bind(this, 'visible')} />,
          
        <label key={this.props.name + '-label-' + i} htmlFor={this.props.values[i]}>{label}</label>);
      
      //and now we add the "any value text field, with all its special variables"
      var value = "";
      if (selected) {
        value = this.props.value;
      }
      
      rows.push(<div key={this.props.name + '-div-' + (i+2)} className={this.state.displayClass}>
        <input
          className="anyValue"
          key={this.props.name + '-' + (i+1)}
          type="text"
          value={value}
          placeholder={this.props.anyPlaceholder}
          onChange={this.handleAnyChange}
          ref={this.props.name} />
      </div>);
    }
    
    //Now we just return all those rows, along with the error component
    return (
      <div className="radios">
        {rows}
        
        <InputError 
          visible={this.state.errorVisible} 
          errorMessage={this.state.errorMessage} />
      </div>
    );
  }
});

The only changes made to the Radios component have to do with the addition of the value attribute. You may have noticed that the default and reset values sent to the Radios and Department components are “undefined.” That’s because there’s always a possibility that one of the radio or select options could be 0 or an empty string, but both components also contain an “any value” text field. The only way to truly unset these radio and select fields, therefore, is to set the value to undefined.

Properly setting the regular radio buttons is easy. We just select the radio button using the selected attribute if it matches the value, as we iterate through each radio button:

selected={this.props.value==this.props.values[i]?true:false}

Just because we are using the value property to empty the fields doesn’t mean that we don’t have to set the current value. Remember that we are saving the state as the user makes changes, but that state change causes the display to update, which means that we have to set the value correctly even when the field is not empty. Otherwise, the fields would be set to empty as soon as a user makes a change!

We then put the “undefined” setting to use when deciding whether to select the “other” option:

var selected = false;
if (this.props.value != undefined && this.props.values.indexOf(this.props.value) == -1) {
  selected = true;
}

If the value is undefined, then we know not to select anything, because we are emptying all the fields. If it’s not undefined, however, and the value does not match any of the other radio buttons, then we know we have a custom value.

For the optional text field, we just need to set the value if it exists:

var value = "";
if (selected) {
  value = this.props.value;
}

There are no changes to the Payment component, but we do have a small change to the Department component (even though we aren’t actually saving the value):

var Department = React.createClass({
  getInitialState: function() {
    return {
      displayClass: 'invisible'
    };
  },
  handleClick: function(e) {
    //We're doing another one of these "any value" fields, only shown when
    //a specific "other" option is chosen
    this.props.onChange(e);
    var displayClass = 'invisible';
    if (e.target.value == 'other') {
      displayClass = 'visible';
    }
    this.setState({displayClass: displayClass});
  },
  render: function() {
    //This is a select field with options and sub-options, plus an "any value" field
    var value = this.props.value;
    if (this.props.value != undefined && ['none', 'muir', 'revelle', 'sixth', 'jacobs', 'global', 'medicine', 'scholarships'].indexOf(this.props.value) == -1) {
      value = 'other';
    }
    else if (this.props.value == undefined) {
      value = 'none';
    }
    
    return (
      <div className="department">
        <select value={value} onChange={this.handleClick} multiple={false} ref="department">
          <option value="none"></option>
          <optgroup label="College">
            <option value="muir">Muir</option>
            <option value="revelle">Revelle</option>
            <option value="sixth">Sixth</option>
          </optgroup>
          <optgroup label="School">
            <option value="jacobs">Jacobs School of Engineering</option>
            <option value="global">School of Global Policy and Strategy</option>
            <option value="medicine">School of Medicine</option>
          </optgroup>
          <option value="scholarships">Scholarships</option>
          <option value="other">Other</option>
        </select>
        <div className={this.state.displayClass}>
          <input className="anyValue" value={this.props.value=='other'?this.props.value:''} type="text" onChange={this.props.onChange} placeholder="Department" ref="any-department" />
        </div>
      
        <InputError 
          visible={this.state.errorVisible} 
          errorMessage={this.state.errorMessage} />
      </div>
    );
  }
});

Since this is a select field with an “any value” text field, we have to check for “undefined” again:

    var value = this.props.value;
    if (this.props.value != undefined && ['none', 'muir', 'revelle', 'sixth', 'jacobs', 'global', 'medicine', 'scholarships'].indexOf(this.props.value) == -1) {
      value = 'other';
    }
    else if (this.props.value == undefined) {
      value = 'none';
    }

The Department component is a little bit different from the others, in that the options are simply hard-coded. The only reason it’s a separate component is to simplify the code in the DonationForm component. As such, the easiest way to set the correct value is to simply check against the hard-coded values. This is similar to what we did in the Radios component, but with hard-coded values. We then set the text field based on whether they’ve selected “other.”

Saving data to the server

Now we get to save the data and watch the changes happen! Our example hinges on the installation of Node.js. Most of what needs to be done is covered in the beginner’s Node.js tutorial. If you follow all the directions in that tutorial, within the folder for your project, you’ll wind up with a package.json file. The only addition to that tutorial is to install body-parser along with express. After installing express, you will need to run the same command, but with body-parser:

npm install body-parser --save

This will give you a package.json file similar to the one included with the files for this tutorial:

{
  "name": "donation-tutorial",
  "version": "0.0.1",
  "description": "Donation tutorial",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "keywords": [
    "react",
    "tutorial",
    "donation",
    "example"
  ],
  "author": "zenva",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.14.1",
    "express": "^4.13.3"
  }
}

We use server.js for our example, since we are creating a server, although the file in the Node.js tutorial is called script.js. You can use either name as long as the name in your package file matches the name of your Node file.

From there, you would create your Node server in whatever way you see fit. The server can do additional processing and error checking, and should include security measures as well. It can also save information to a database, and read from a database. In our example file, we simply save to, and read from, a file called donations.json. In fact, our server is so simple that it’s very similar to Facebook’s server.js file, included within their tutorial files. You can’t really make it more simple than that!

If using the files with this tutorial, all you have to do is install Node.js (which includes npm), then go to the same folder as the package.json file and run the following command on the command line:

npm install

Once it’s installed, just run the following command:

node server.js

But look at the following line in package.json:

"start": "node server.js"

This means that you can also start the server by running the following command:

npm start

The server will then start, and tell you right where you need to go in your browser: http://localhost:3000/

Once you open that URL, you should see a list of donations, with the ability to add new donations. In addition, if you add a field directly to the donations.json file, it will display on the screen almost immediately!

Screen Shot 2015-11-17 at 8.03.00 PM

Ending Tips

There is a lot more to explore in regard to web development – and trust us, React isn’t the only way to deal with forms. So be sure to check out all your options for web development with full-stack courses. You can also just return to basics and explore web fundamentals – especially educators who have options like Zenva Schools.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Understanding How the INTERNET Work https://gamedevacademy.org/internet-protocols-tutorial/ Fri, 05 Aug 2022 01:00:58 +0000 https://gamedevacademy.org/?p=18447 Read more]]>

You can access the full course here: JR CODERS – INTRO TO NETWORKS

How Does the Internet Work

When using the Internet, we’re both sending and receiving packets over the network.

Internet Protocols

It’s important to know that there are different types of packets, they are not all the same. These are known as  Internet Protocols. A common one on the Internet is the HTTP (Hypertext Transfer Protocol). This protocol is used to transfer web pages across the Internet, while the FTP (File Transfer Protocol) is used for transferring files across a network (e.g., to upload files to a server).

The TCP (Transmission Control Protocol) and IP (Internet Protocol) are the ones we use to define how the data will be sent. IP is responsible for establishing a connection between two devices, then TCP is in charge of sending the data across the connection:

TCP and IP

Say you want to open up a website on your computer, here’s what is going to happen:

  1. A connection between you and the server is defined by the IP
  2. TCP breaks the web page into several small chunks (i.e., packets)
  3. TCP sends these packets over to your requesting device
  4. Your computer reads the packets and can reconstruct the final page

And that’s how communications are established and held over the Internet.

Transcript

When using the internet, we are both sending and receiving packets over the network. It’s important to know that these packets are not all the same, there are different types. These are known as internet protocols and determine how data is sent across the network.

When using the internet, a common one is the Hypertext Transfer Protocol, also known as HTTP. This protocol is used to transfer webpages across the internet.

FTP, which stands for File Transfer Protocol, is used for transferring files across a network, okay, so if you wanted to upload some files to a server, you would most likely be using FTP.

Now, this is how we define the data. TCP/IP, which stands for Transmission Control Protocol and Internet Protocol, is what we use as the means of transmitting that data.

IP is responsible for establishing a connection between the two devices, then TCP is in charge of transmitting that data across the connection. It works like this. Let’s say you want to open up a webpage on your computer.

A connection between you and the server is defined by the IP, then the TCP chops up that webpage into a number of different small chunks and sends them over via packets. Your computer can then read these packets and form the final webpage.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
How to use Inline CSS: Beginner’s Web Development Tutorial https://gamedevacademy.org/inline-css-tutorial/ Fri, 03 Jun 2022 19:37:07 +0000 https://html5hive.org/?p=2700 Read more]]> When it comes to changing how your website looks, inline CSS can be a real lifesaver when used properly.

In this tutorial, we’re going to quickly show you how you can use inline CSS to quickly apply your styles from your main webpage. We’ll also help you understand when to use inline CSS – since it isn’t the best choice in many situations.

If you’re ready to add a new tool to your web development kit, let’s jump in!

A Quick Overview of HTML & CSS

While HTML provides the essential structure and content of your website, CSS (Cascading Style Sheets) provides the look and feel. Without CSS, modern websites would not function as they do. When developing a website, there are three ways to apply CSS styling: inline, internal, and external. The focus of this tutorial is to show you, by example, how to apply Inline CSS directly to individual HTML elements. Not only that, but we’ll help you understand appropriate use cases between the three – so you can use inline CSS with newfound confidence, skills, and in ways that work for your personal responsive website!

Applying CSS Styles: An Overview

Inline CSS styles are applied by assigning a string directly to an HTML element’s style attribute. It allows you to style an individual HTML element directly within your HTML document without any impact to other elements on your web page.

Since Inline CSS is applied directly to an HTML element, there is no requirement to first define CSS selectors like Internal and External style sheets (by which we mean there’s no separate CSS file).

Let’s illustrate the differences by applying a single style to a header <h1> HTML tag on a super simple website. Here is our website with no CSS.

<!DOCTYPE html>
<html lang="en">
  <head> </head>
  <body>
    <h1>My Super Simple Website</h1>
  </body>
</html>

Screenshot of a rendered headline on a webpage

Inline CSS: HTML Style Attribute

Notice the style attribute on the <h1> header element. We define the style by assigning the attribute a string containing normal CSS properties. Multiple CSS rules can be applied but it’s important that each rule end with a semi-colon.

<head>
</head>
<body>
  <h1 style="text-align:center;">My Super Simple Website</h1>
</body>

Our header is now centered on the page.

Webpage headline centered via inline CSS

Internal CSS: HTML <Style> Element

Internal CSS is applied inside HTML <Style> Elements placed in the <head> section of the HTML website file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      h1 {
        text-align: center;
      }
    </style>
  </head>
  <body>
    <h1>My Super Simple Website</h1>
  </body>
</html>

Notice that our web page looks the same. The key difference, other than the <style> element in the <head> section is that we are required to first select the HTML element (h1) and enclose the CSS rule to center the text inside curly braces.

Headline appearance after being moved to style tags

External CSS: Link to Stylesheet

External CSS is coded inside a separate file with a specific file extension (.css). The CSS stylesheet is referenced from the <head> section of the HTML website file using HTML <link> element with a href attribute set to a string containing a relative path/filename of the stylesheet. Two other attributes are used: rel set to the string “stylesheet” and type set to the string “text/css”.

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css" type="text/css" />
  </head>
  <body>
    <h1>My Super Simple Website</h1>
  </body>
</html>
h1 {
  text-align: center;
}

Headline appearance using external CSS sheet

Notice that our web page looks the same. The other important thing to notice is that the CSS rules inside the external stylesheet are coded in the exact same syntax as the internal stylesheet.

Inline CSS: Beginners Guide

When to Use Inline CSS

Use Inline CSS primarily for testing new styling of specific HTML elements that would otherwise be difficult to isolate by modifying existing CSS stylesheets which could have unwanted or unpredictable consequences to other HTML elements across your website.

While too much Inline CSS may impact performance, there may be certain use-cases where initial page load of “critical CSS” can be cautiously considered as a candidate for limited use of Inline CSS.

When to Avoid Inline CSS

Avoid using Inline CSS when you have more than a few CSS rules to apply to a specific HTML element because it can get very messy, very quickly and become difficult to read and maintain.

Importantly, avoid using Inline CSS as your main source of styling. Using Inline CSS on too many HTML elements will not only become very messy, difficult to read, and impossible to maintain but will lead to significant repetition of styling, huge refactoring headaches as well as negate the many benefits of applying consistent styling across your website enabled by CSS stylesheets.

It’s also worth noting that CSS has advanced significantly in recent years with the addition of CSS Grid and CSS Flexbox which provide significant power but also involve setting more properties than would be feasible to put within a simple string assigned to an HTML element’s style property. So in other words, you can’t avoid a separate CSS file forever to add CSS to your page.

Order of Precedence

CSS is an acronym for Cascading Style Sheets and the order of precedence is very important in CSS regardless of which technique you use. Generally, order matters – the last style rule applied for any given element wins. Since Internal CSS can apply to an entire web page while External CSS can apply to an entire website across many pages it is not always obvious what CSS rule will apply to a specific HTML element. The very nature of cascading styles is simultaneously the power and curse of CSS. Over time various techniques have been developed to help better predict and control the application of styles but it remains a topic that requires thoughtful consideration and a consistent approach.

While Inline CSS is generally not considered a good practice for an entire website or even a web page, the one thing you can count on is whatever Inline CSS style you set on an HTML element will override style properties set in both Internal and External Stylesheets.

How to Use Inline CSS

Let’s consider once again the simple example of styling a header HTML tag. Let’s assume we are trying out new styles for the main header of our website and want absolute control over three styles for this header: its font-style must be italic, its color must be blue and the header text must be centered on the page. We are aware that CSS rules affecting the style of this header are already set within the web page’s Internal Stylesheet and the linked External Stylesheet and within the website HTML file the reference to Internal styles comes after the link to External styles. Furthermore, we don’t want to touch either the Internal or External CSS as our focus is simply testing new styles for this one HTML element and we don’t want to affect anything else on our website.

This scenario satisfies the advice provided above of when to use Inline Styles and when to avoid Inline Styles so let’s get started.

The External Stylesheet contains the following rules regarding <h1>  header tags.

h1 {
  font-style: none;
  color: red;
  text-align: left;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css" type="text/css" />
  </head>
  <body>
    <h1>My Super Simple Website</h1>
  </body>
</html>

At this point our web page header looks like this:

H1 headline with red text

Since we want our new design to have font-style of italic, a color of blue and text aligned to the center on the page none of our criteria is met by our External Stylesheet.

Next, let’s consider the <h1>  header styles in our Internal Stylesheet. Notice that the External styles remain so we can better understand the Order of Precedence described previously.

h1 {
  font-style: none;
  color: red;
  text-align: left;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css" type="text/css" />
    <style>
      h1 {
        font-style: none;
        color: green;
        text-align: right;
      }
    </style>
  </head>
  <body>
    <h1>My Super Simple Website</h1>
  </body>
</html>

Internal CSS styled headline so the text is green and aligned right

Notice that with the inclusion of our Internal Stylesheet after the reference to the External Stylesheet has altered our design completely but still does not resemble the style we want.

Keeping both the Internal and External Stylesheets as is, let’s now add Inline CSS to the <h1>  header tag providing the exact design styles we want to this HTML element. Again, those styles are: font-style of italic, a color of blue and text aligned to the center on the page.

h1 {
  font-style: none;
  color: red;
  text-align: left;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="style.css" type="text/css" />
    <style>
      h1 {
        font-style: none;
        color: green;
        text-align: right;
      }
    </style>
  </head>
  <body>
    <h1 style="font-style: italic; color: blue; text-align: center">
	My Super Simple Website
    </h1>
  </body>
</html>

Notice that we have applied our Inline CSS to the <h1>  header by setting its style attribute to a string containing three CSS rules separated by semi-colons.

Headline text centered, italicized, and moved to the center with CSS

Learning Resources

Learn more about including CSS in a web page (Inline, Internal and External) from CSS expert Kevin Powell in these two video lessons Introduction to CSS and External CSS.

Continue your CSS learning with this free HTML & CSS 101 – Web Development Fundamentals course or take your skills to the next level in just over an hour with this free COMPLETE COURSE – Learn HTML and CSS in 80 MINUTES. You might also consider trying this HTML Tutorial for Beginners from Programming with Mosh or decide to master the foundations of all web development with this premium Full-Stack Web Development Mini-Degree.

Conclusion

By applying proper syntax for Inline CSS to our website’s <h1>  header HTML tag (including applying multiple styles), we were able to test a new design for our website’s <h1>  header tag. We also considered the proper use of Inline CSS and the Order of Precedence in relation to Internal and External CSS Stylesheets, so we were able to target a single HTML element without impacting the CSS styling of any other HTML elements on our website.

While there are plenty of cases to not use Inline CSS, it is still a useful tool that can help you out of tough situations as you build your websites. Nevertheless, we do encourage you to learn other CSS skills including how to make an external CSS file, what each CSS property does, how to create a unique style, and so forth. After all, it’s better to use a separate CSS file if the alternative is a messy block of code.

We hope you take these newfound skills to the next level, and master the art of CSS so you can get your sites to look exactly how you’d like them too!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
How to Fetch API Data from a URL – JavaScript Tutorial https://gamedevacademy.org/fetch-api-data-tutorial/ Sun, 08 May 2022 01:00:52 +0000 https://html5hive.org/?p=2597 Read more]]>

You can access the full course here: Bite-Sized Modern JavaScript

 

Fetching Data from URL

To fetch data from a URL, we will use the Javascript fetch API. We won’t cover every aspect of the fetch API, just the basic retrieval functionality. To get this functionality, you need to install node-fetch. Set up node in your project if you haven’t already and navigate to the folder in terminal. Once there, run:

npm i node-fetch --save

To install node-fetch and add the line:

const fetch = require(‘node-fetch’);

At the top of your program. Next add the code:

fetch('http://api.steampowered.com/ISteamUserStats/GetGlobalAchievementPercentagesForApp/v0002/?gameid=221380')
    .then(function(response) {
        return response.json();
    })
    .then(function(myJson) {
        console.log(JSON.stringify(myJson));
    });

This will fetch the data, convert it to JSON, and print it to the console. The json response data is stored in the “myJson” variable. This is also taking advantage of Javascript’s new Promise feature along with asynchronous functionality. Let’s take a few minutes to talk about Promises and async functions in Javascript.

 

Transcript

What’s up everyone. Welcome to fetching data from a URL. Here we’re going to write the actual code that will fetch the data we want, and we’re going to use our asynchronous functions that promises to do so. Actually, before we get started we should probably install that fetch API.

So assuming that you are in your project directory, if not then navigate there now. We’re just going to use a simple npm command to install what’s called node fetch. So we’re going to do npm i node-fetch –save like so. Okay, so we’ll not worry about the warning or anything as long as we see added 1 package then we are good to go. If you open up your packages.json – so let’s go back here if we open up packages.json we should see node-fetch there.

So now we’ll need to add the fetch API here. And we’re gonna do so by creating a constant called fetch this is going to be equal to require node-fetch. Okay, so now we have the fetch function and can use this to retrieve the data in our URL. So lets actually go back to chrome. This is the data that we want. This is exactly what the format of the data we want comes back in.

So what we’re going to do for now is gonna copy this URL. We’re gonna create a variable and let’s make this URL equal to this string here, and we’re gonna feed that into a fetch function. So we’ll create an async function and we’re going to call this: fetchData. It’s going to take in a URL as a parameter. Now we want to call upon fetch with that URL. So fetch is the actual JavaScript function built into the node fetch library that will be used to actually retrieve data from a URL.

So we actually want to store the results of this in a variable. We’re going to call this a response. Response equal to fetch(URL). This is where things get interesting, because this is an asynchronous function, we’re going to actually do await fetch(URL). So the fetching of the data is going to take some time. We don’t want this blocking up the main thread while it’s fetching the data. And that’s why we’re doing await fetch, because fetching the URL or fetching dates from this URL may take some time. So we’re basically just going to say response only takes on the value after fetch has retrieved the data.

Okay so from here, we have the response but we want to make sure that it’s JSON data. So this will just come back as an object that needs to be decoded. So what we’re gonna do is we’re gonna create a variable, jsonResponse, and we’re gonna set this equal to again await – because it may take some time – and we’re going to get our response and we’re going to call the JSON function. So this is gonna convert our response to JSON and then let’s say we just want to print out a simple console.log and we’re going to stringify this data.

So we’re gonna call upon a JSON method called stringify and we’re just gonna pass in our jsonResponse. So we’re gonna call upon fetchData and we’re going to pass in that URL. Now this will do the printing. We can actually give this a save and we can run it. This is really promising, you can see that we’re getting back this huge string of data and has essentially exactly the same data as we see here.

Interested in continuing? Check out the full Bite-Sized Modern JavaScript course, which is part of our Bite-Sized Coding Academy.

]]>
How to Set up a Localhost – Web Development Tutorial https://gamedevacademy.org/how-to-setup-a-localhost/ Fri, 18 Mar 2022 08:07:57 +0000 http://html5hive.org/?p=510 Read more]]> If you’re at all intent on becoming a web developer, knowing how to set up a localhost is a key skill to making sure your website is prepared for production.

In this tutorial, we’re briefly going to go over how to set up a localhost as quickly as possible so you can work with your site’s server-side functionalities.

If you’re ready to learn new web development skills, let’s get started!

Brief description

In Web Development, a localhost is a local server environment in which we can test and use server side scripts on our computer. We can set-up our localhost environment with an Apache server application, MySQL and PHP.

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

XAMPP

If you are a Windows or Linux user, you can download and install XAMPP from Apache Friends. You can also use XAMPP on Mac!

MAMP

If you are using a Mac, I recommend installing MAMP – Mac Apache MySQL and PHP (there is a free version available and is absolutely fine for our intents and purposes).

Once we have our installation set up we can start to set-up our localhost environment.

Overview

Today, I will be running through a default MAMP set-up.

Windows and Linux users; you should be able to follow along with the MAMP tutorial, your ‘htdocs’ directory should be located in the XAMPP Application directory. Depending on your System Configuration, your localhost URL should be http://localhost. You would also be using the XAMPP control panel.

Stepping into MAMP

We have our MAMP folder located in ‘/Applications/MAMP/’, this is where the good stuff is. Navigate to the MAMP folder and launch ‘MAMP.app’ (don’t worry about MAMP pro).

As you can see, its a fairly basic, easy to navigate application. On the left we have our server status- Apache and MySQL, these should currently be red, as we have not ‘started our servers’.

If you are using XAMPP, you should see the Apache web server and MySQL servers under the ‘Manage Servers’ Application tab.

Starting Our servers

So, let’s start up those local servers!

We can do this by clicking on ‘Start Servers’.

If you are using XAMPP, you can select ‘Apache Web Server’ and click the ‘Start’ button.

Once the servers have loaded (lights turn green), our MAMP home page should load.

Notice the URL; http://localhost:8888/MAMP/

Note: If you are using XAMPP, the localhost url should just be http://localhost.

Our MAMP local server, by default uses port 8888 for Apache and port 8889 for MySQL (for the purposes of this tutorial, we won’t be talking about MySQL server ports).

Root Web directory

So, basically http://localhost:8888 is saying, “http to localhost via port 8888”. http://localhost:8888 ‘points’ to our ‘root web directory’. So now that we have seen our MAMP homepage and we can see that our servers are running- let’s locate our root web directory!

Let’s go back and open up our MAMP folder ‘/applications/MAMP/’ and take a bit more of a look inside.

So, we have our MAMP applications and a little folder titled ‘htdocs’. This ‘htdocs’ folder is magic; this is the root web directory. Any files (.html, .PHP, .css, .txt, .xml) that are placed in our ‘htdocs’ or root web directory will then be accessible via the localhost URL i.e. http://localhost:8888/script.php.

Adding Content

Let’s create a new HTML file with the basic HTML5 structure, add some content and save the file as ‘home.html’.

Now, let’s place our ‘home.html’ file inside our root web directory of our localhost server ‘/Applications/MAMP/htdocs/’ and load up http://localhost:8888 in your browser.

If you are using XAMPP, your htdocs folder will be located in the XAMPP directory. You would then use the http://localhost URL.

You should now see ‘home.html’ listed in your directory contents. Click on “home.html” and your HTML page will load. You should now have an understanding of the root web directory and its relation to our localhost.

Info

Open up your text editor, create a new php file and add the following to its contents and save it as ‘info.php’. Place this file inside your ‘htdocs’ directory.

<!--?php phpinfo(); ?-->

Now, let’s load up http://localhost:8888/info.php (or http://localhost/info.php – depending on the application you are using) in our browser and you will see everything you need to know about your PHP configuration.

When using an application such as MAMP or XAMPP, once installed they will install an Apache Web Server, a MySQL Server and a PHP installation on your system.

Documentation

Check out the official pages for MAMP and XAMPP, for additional instructions and download links.

I hope you found this resource useful – especially as you might be diving into various other programming languages or even considering job prospects for your web developer career!

]]>
How to Add Google Fonts to Your Websites and Webapps https://gamedevacademy.org/google-fonts-html5hive-tutorial/ Sat, 12 Mar 2022 01:00:39 +0000 https://coding.degree/?p=1058 Read more]]>

You can access the full course here: Intro to Web Development with HTML and CSS

Tutorial

In this lesson, we look at a great resource for adding different fonts to your website.

Google Fonts

To use different style fonts on your website, Google Fontshttps://fonts.google.com/ ) is a great resource. This site offers a wide variety fonts beyond those installed by default in your browser or operating system. You can scroll through many different examples or even type something in the text box provided to see how your specific text would look with various font styles.

Screenshot of Google Fonts with Type something field highlighted

Selecting Google Font

For an example, scroll down and select Goldman.

Google Fonts with Goldman font circled

This takes you to a detail page for this font where you can make selections on exactly what style of this font you want. For this example, select the Regular 400.

Goldman font on Google Fonts with Regular 400 selected

Linking to Google Font

Next, click the button in the top right corner of the Google Fonts website that allows you to view your selected font families.

Google Fonts with cursor on Selected Families button

This opens a side panel where you can select how you want to access your selected font. From this panel copy the link tag information, then go back to index.html and paste the links in the Head (<head></head>) section of our web page.

Google Fonts with link area circled for Selected family

<!DOCTYPE html>
<html>
    <head>
        <title>Learn web development on ZENVA.com</title>
        <meta charset="UTF-8">
        <meta name="description" content="This is what Google will show!">
        <link rel="icon" href="favicon.ico">
        <link rel="stylesheet" href="style.css">
        <!-- Link to Google Fonts -->
        <link rel="preconnect" href="https://fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css2?family=Goldman&display=swap" rel="stylesheet">
    </head>
    <body>
        <p>This paragraph contains <span class="keypoint">everything</span> you've always wanted to know!</p>
    </body>
</html>

Using Google Font

Back in the Google Font side panel below where we just copied the link information is instructions on how to include the font in your CSS Stylesheet. Copy this information and paste it into style.css in place of the font-family we setup in the last lesson.

Google Fonts with Selected Family's CSS rule circled

body {
    font-size:20px
}

p {
    font-size:2rem;
    /* new Google Font */
    font-family: 'Goldman', cursive;
}

.keypoint {
    font-style:italic;
    font-weight:bold;
    text-decoration:underline;
}

Website example of Goldman font applied from Google Fonts

Our Paragraph text now appears with our newly included Google Font. Notice that the <span>everything</span> styling still applies.

 

Transcript

Hey everyone, and welcome back.

Google Fonts is a great resource if you want to use a large number of different fonts inside of your webpage. Because computers do have quite a large library of fonts pre-installed. But there is still a number of different fonts that are more specific to different styles, to handwritten styles that you might want to include on your website. And in that case, you can visit fonts.google.com, and this is a website where you can get a large number of different fonts, okay.

As you see, you can scroll down, see a preview of what they look like. You can even type something up here and it can basically preview what that text looks like. Okay, so let’s just say we wanna pick a text right here. Let’s just say we want this text right here, Goldman. We can select that, and it’ll bring us to this page here, okay. We want to go get the regular. So we’ll click Select this style right here.

This is then going to allow us to click on this button up here, at the top right, View your selected families. We’ll click on that. It’ll open up this side screen right here. And as you can see, we have this code right here, or this tag, this link tag that we can actually select. We can copy that with Control + C or Control + V.

We can go over to our HTML document, and add this just under where we specify the style sheet, okay. Paste that in with Control + V or Command + V. And there we go. So we are now able to use this Google font now that we have actually applied it to our webpage or to our HTML document, okay.

So how do we actually use it? Well, if we return to the Google Fonts site, you’ll see down here that it says CSS rules to specify families. And what we can do is copy that font-family CSS rule right there, go back to our CSS document. And I’m gonna replace this in the paragraph right here with that new one. So I’m gonna paste that in like so, click Run.

And there we go. We’ve got the new font, now applied to our text right here. And of course you can go through Google Fonts, choose all different ones. You can mix and match them with different spans, with different containers. Google Fonts is a great resource if you’re looking for a specific font, a specific style for your website. Thank you for watching.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
Learn Asynchronous Programming – JavaScript Tutorial https://gamedevacademy.org/javascript-asynchronus-programming-tutorial/ Fri, 11 Mar 2022 01:00:07 +0000 https://gamedevacademy.org/?p=15363 Read more]]>

You can access the full course here: Intermediate JavaScript – Build a Dynamic Data Table

Asynchronous Programming with Async Await

In this lesson, we’ll see how to do asynchronous programming with async/await.

An async function is a function declared using the ‘async‘ keyword, with ‘await‘ used within it to make the code stop and wait for the function being called to finish before proceeding to the next line:

async function myAsyncFunction(){
const response = await fetch(‘http://localhost/myfile.json’);
let json = await response.json();
}

Here in this example, we’re loading in a JSON file to our const ‘response‘. Once the fetching is done then we continue by parsing its contents to an object that we store in the ‘json‘ variable.

Note that the await keyword can only be used inside an async function.

Promises vs Async Await

In this lesson, we’ll compare the differences between promises and async/await.

The main differences we can notice between the two approaches are:

  • Async functions do not have states like promises, they simply return a success or failure;
  • Async has cleaner error handling (which we’ll see in the next lesson);
  • You can’t chain async functions as you could with promises;
  • Chaining multiple promises can become complex to deal with.

As such, we’re going to use async functions for the rest of the course.

Error Handling in Async

In this lesson, we’ll learn how to handle errors in JavaScript.

The easiest way to do error handling is by using try catch blocks as they are statements that specify how to handle exceptions when thrown.

Let’s take a look at how they work in practice:

async function myAsyncFunction(){
try {
const response = await fetch(‘http://localhost/myfile.json’);
let json = await response.json();
} catch (err){
console.log(err);
}
}

By wrapping up our code in a try catch block, we’re telling the browser to try to load in the specified JSON file for us, and if it can’t do it then it should simply log the error in the console. Additionally, we could also show a message to the user explaining that an error occurred without displaying the actual whole error stream to them unnecessarily.

Try catch blocks handle pretty much any exception that may occur and thus work pretty well with asynchronous functions as we never know when an error can happen.

Transcript

Asynchronous Programming with Async Await

Hello and welcome back to the next video in this course. And in this video, we’ll be taking a look at asynchronous programming with the async and await keywords.

So what is async and await? An async function is a function declared using the async keyword, and await is used within them. So what that means is that we have to have the two keywords together.

As we can see in this example, before the function key, we use the async keyword, and then somewhere throughout the function, we have to do an await, we have to have the two together.

And what we’re doing in this function is that to our variable response that we’ve made, we are loading in a JSON file, and then what we’re doing is we are adding this, create another variable later on using the let keyword again to load the response, the JSON of our response, into another variable.

Really, you can kinda see, we’re doing the same thing that we did with promises, but this is, in the way I look at it, this is a lot more cleaner.

Now, the next video, we’ll take a look at the differences between promises and async and await, and then we’ll decide which one we’re gonna use for this course. See you then.

Promises vs Async Await

Hello and welcome back. This video, we’re gonna be comparing the two asynchronous options that we’ve looked at so far in JavaScript in the Promises versus Async and Await.

So what is the differences between the two? Technically async and await function is the same thing as a Promise. It’s just done a lot cleaner and you can’t chain them like you can, in the same sense as you do the Promise chaining with next and such.

Async functions do not have states like Promises do either. They either return success or failure. There’s not different states, again, like Promises have.

Async has a much cleaner error handling that we will look at in the next video. And Promises, as you start chaining them, they can really become messy. Again, async and await, is just so much easier to use and easier to maintain.

So because of that, for the rest of the course, when we do asynchronous programming, it will be using the async and the await function. And in the next video, we will take a look at how we can do error handling for async and await.

Error Handling in Async

Hello, and welcome back. And I promise you, this will be our last theory video that we have. The next video, we’ll start getting into, into the code and start writing it. But before we get to that, we have to just look at one more topic.

And that is how we will do our error handling with Async. And the easiest way that we can do error handling is what’s called a try catch block. Try catch blocks are statements that they kind of tell the browser, the JavaScript partial or whatever you want to call it, how to handle exceptions when they occur.

And let’s take a look at what I mean by that. Here this is the rehash of our function that we looked at in the Async and await video. And all I’ve done is I’ve added this try and catch to it.

And what happens is that it will, we’re telling the browser to try to do what we’re doing right here. Try to load in this JSON file for us. However, if you can’t do it, you know, don’t display the massive error to the user.

Let’s put our, put the error into the console. And then what we could do here is we could put a nice little message to the user. Hey, you know, an error has occurred or whatever, instead of just bombarding them with a you know, just massive error stream.

So this try catch block really comes in handy with an asynchronous function. Cause you never know what could happen. You know, the user’s internet could go out.

There could be changes to your server that you’re not aware of, and you can lose a file or, you know, any number of things could happen. And try catch allows us to handle pretty much anything that we can think of gracefully.

So, as I said, this is our last theory video. In the next video, we will begin creating our json file for the project, with all the cards that we’re going to use. And the from here on out, we’ll be writing some code. See ya then.

Interested in continuing?  Check out our all-access plan which includes 250+ courses, guided curriculums, new courses monthly, access to expert course mentors, and more!

]]>
How to Do an HTML Redirect: Beginner’s Web Tutorial https://gamedevacademy.org/html-redirect-tutorial/ Tue, 22 Feb 2022 10:37:03 +0000 https://html5hive.org/?p=2682 Read more]]> The easiest way to have your users automatically redirected from an old URL to a new one is by using an HTML Redirect. Whether you’ve changed your domain name, restructured your website, or simply reorganized some of your web pages, avoiding the dreaded 404 Page-Not-Found error is paramount.

Regardless of your reason for website changes, in this HTML Redirect tutorial, we’ll show you through simple examples how to confidently enhance your website, while protecting your user’s experience and the SEO you have built over time.

Let’s dive in!

About HTML Redirects

HTML redirects are one of three techniques that provide instructions to your visitor’s web browser to automatically take your user from the URL they keyed into their browser to the URL where your content now resides. In this way, you can retire an old HTML page and send users to a brand new HTML page entirely.

How to Code HTML Redirects

Modern websites have a formally structured HTML file, often called index.html, that serves as the main entry point to your site. Your site then has zero to many less formal web pages, HTML fragments, or components that return HTML which varies depending on if you’re using no JavaScript (JS), vanilla JS or one of the many JS libraries or frameworks that are so popular today (React, Angular, and Vue, just to name a few). In its simplest form, the HTML structure consists of three HTML tags: html, head, and body.

<!DOCTYPE html>
<html lang="en">
  <head>
  </head>
  <body>
  </body>
</html>

HTML redirects are coded with a <meta> tag inside the <head> section which contains the metadata written for web browsers rather than the <body> section which contains the HTML elements visible on the displayed webpage.

HTML Redirect Syntax Explained

An HTML redirect,  sometimes referred to as meta redirect or meta refresh, has two attributes containing three pieces of information important to the web browser.

<meta http-equiv="refresh" content="time_delay; url=new_url">

The first property is http-equiv. For HTML redirects, its value is set to “refresh”. Since browsers work within an HTTP Request-Response cycle, this attribute provides information to the browser “equivalent” to what can be found in a similarly-named HTTP header.

The second attribute is content which has two values. Its syntax may seem a little odd so it’s important to note that you have two values inside a single set of double quotes separated by a colon (“time-delay; new_url”).

HTML Redirect Syntax Example

In the code below, the browser redirects to the URL provided (https://example.com) after a delay of 3 seconds.

<meta http-equiv="refresh" content="3; url=https://example.com">

If you changed the first value in content to 0, the page would immediately redirect. If you changed the value to 10, the browser would wait 10 seconds before going to the new URL (in this case the website example.com). Always set this value to zero for accessibility compliance unless you have a strong use-case not to. If you do need to introduce a delay, it is important to keep the user top of mind. Too short a delay may be frustrating while a longer delay should probably be accompanied by a “click here” link that allows the user to manually perform the redirect. This can easily be accomplished in the <body> section using an anchor <a> tag.

<h3>My Important Message...</h3>
<p>You will be automatically redirected in 5 seconds.</p>
<p>Please <a href="https://example.com">click here</a> to be taken immediately.</p>

Essential HTTP Status Codes

What is HTTP?

HTTP is an acronym for Hyper Text Transfer Protocol. In simple terms, web technologies communicate using an HTTP Request/Response cycle.

Why is this Important for Redirects?

When working with web technologies, it’s good to know the meaning of at least a few of the many HTTP Status Codes that are returned when a user enters a URL into the browser or in our case redirects one web page URL to another.

Essential HTTP Status Codes for Redirects

HTTP Status Codes contain three digits with the first number indicating response type (1xx – 5xx). Within this block, there are many codes that you can learn over time. If we ignore for the moment codes that start with 1 (informational) and codes that start with 5 (server-side) there is a small subset of the remaining codes that are essential to redirects:

  • 200 – success
  • 301 – permanent redirect
  • 302 – temporary redirect
  • 404 – page not found

Our goal in redirects is to receive 200 (our web page loaded successfully) and avoid 404 (our web page could not be found). If our content has been permanently moved, we want our redirect strategy to send the browser a 301 status code (known as a permanent redirect). If our content is only temporarily residing at a different location we want our redirect strategy to send the browser a 302 status code (known as a temporary redirect).

HTML Meta Redirect Website Example

An HTML redirect is actually quite simple and best illustrated with an example. In the first code snippet, we add the meta refresh tag redirecting visitors to our new URL after a delay of 3 seconds.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      http-equiv="refresh"
      content="3; url=http://127.0.0.1:5500/new_url"
    />
    <title>Old Website</title>
  </head>
  <body>
    <h1>Old Website URL</h1>
    <h3>http://127.0.0.1:5500/old_url</h3>
  </body>
</html>

Screenshot of a website showing the old website URL

Note the HTTP Status Code of 200 in the browser’s Network tab indicating our old website loaded successfully. After the 3 second delay we coded, the new website is loaded.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>New Website</title>
  </head>
  <body>
    <h1>New Website URL</h1>
    <h3>http://127.0.0.1:5500/new_url</h3>
  </body>
</html>

Screenshot of a website showing the new website URL and Status Codes

Note the two HTTP Status Codes for our new website. The code of 301 indicates a successful redirect while code of 200 indicates our new website was successfully loaded.

Alternative Methods to Perform Redirects

While HTML redirects may be the easiest way to perform redirects, it is not the only way or even the best. As we mentioned in the opening “About HTML Redirects” section, there are two other ways to define redirections. The two other methods are:

  1. HTTP Redirects
  2. JavaScript Redirects

HTTP Redirects

HTTP redirects (also known as 301 redirects, URL forwarding, or URL redirection) are done server-side and are the most powerful and reliable way to ensure that users and search engines are directed to your new content location with no loss of traffic or SEO page ranking.

For Google’s guidance on using 301 redirects where SEO is an important consideration, you can watch this video from Google Search Central YouTube channel.

Important note: In cases where your content is at a new location temporarily it is important to use a 302 (temporary redirect) instead of the 301 (permanent redirect).

While all the concepts we’ve discussed in this article apply, when it comes to HTTP redirects there are so many combinations of technology stacks, hosting services, and domain providers your best approach is to search “301 redirect” followed by “your-technology-stack” followed by “your-service-provider” and follow the guidance of official sources when possible.

JavaScript Redirects

JavaScript redirects provide another simple option to automatically take your user from the URL they keyed into their browser to the URL where your content now resides. At first glance, JavaScript offers a lot of cool benefits for triggering redirections. Let’s explore the JavaScript way by mirroring the results we accomplished above using the HTML redirect technique.

In the code below, the browser redirects to the URL provided (https://example.com) immediately.

window.location = 'https://example.com';

The following are other techniques you may use to achieve the same result.

window.location.href = 'https://example.com';
window.location.assign('https://example.com');

In the code below, the browser redirects to the URL provided (https://example.com) immediately as above. The difference from using the assign() method is that after using replace() the current page is not saved in history which simply means the user cannot navigate back to the original page using the browser’s back button.

window.location.replace('https://example.com');

Another interesting thing with using JavaScript is that you can make the URL dynamic, update the URL in response to events, and basically provide any programming logic to determine which URL to navigate to.

let urlBase = 'https://';
let domainExtention = '.com';
window.location.assign(urlBase+'example'+domainExtention);

In the HTML redirect section above we also showed how you could introduce a delay in redirecting to a new URL. This can be easily accomplished in JavaScript as well by using a setTimeout()  function. In the code below, the browser redirects to the URL provided (https://example.com) after a delay of 3 seconds.

let urlBase = 'https://';
let domainExtention = '.com';

setTimeout(() => {
   window.location.assign(urlBase + 'example' + domainExtention);
}, 3000);

Learning Resources

Learn more about HTML, JavaScript and HTTP Redirect details from the Mozilla Developer Network documentation and from this insightful article from CSS-Tricks.

Continue your HTML learning with this free HTML & CSS 101 – Web Development Fundamentals course or take your skills to the next level in just over an hour with this free COMPLETE COURSE – Learn HTML and CSS in 80 MINUTES. You might also consider trying this HTML Tutorial for Beginners from Programming with Mosh or decide to master the foundations of all web development with this premium Full-Stack Web Development Mini-Degree.

Conclusion

There are many reasons why you might want to provide URL redirection and send people to another page – including seamlessly transitioning to a new domain, restructuring your existing website, directing visitors to a secure version of your site (from http://example.com to https://example.com), allowing people to access your site from multiple domain names (there are now well over 1000 domain extensions and it’s still growing), and many other scenarios.

Regardless of your reason, ensuring that users and search engines are directed to your new content, maintaining other internet sites’ backlinks to your content, user’s bookmarks and of course, no loss of traffic or SEO page ranking make awareness of this topic essential in today’s world. Just think of how many times you’ve been frustrated trying to access an old HTML page that no longer exists.

In this article, we focused on the simplest of three techniques, HTML redirects, and briefly discussed the other two (HTTP and JavaScript). While HTML redirects are a simple solution and JavaScript provides a powerful developer experience, it’s important to keep your end goal in mind when deciding which approach to take. One site’s best way for sending someone to another page may not work for you.

With this foundational knowledge, you can confidently enhance your website by finding and implementing the steps that match your requirements and technology stack ensuring people continue to find you and your valuable content!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>
Create a React App: Beginner’s Tutorial https://gamedevacademy.org/create-react-app-tutorial/ Mon, 16 Aug 2021 04:19:18 +0000 https://coding.degree/?p=1346 Read more]]> In this post, we’re going to explore the popular JavaScript library of React and learn the fundamentals of creating our own web app by using Create-React-App.

Why React? Well, considering it is used by over 9 million websites and is ranked as the 2nd most popular framework, you can bet these skills will pay off greatly in your success as a web developer.

Let’s get started in exploring React!

About React

React is a powerful open-source JavaScript library created by Facebook for a very specific purpose – building user interfaces. React enables developers to create complex and interactive UIs by composing together React components built with JavaScript that encapsulate UI, state, and logic.

Banner with React Logo and Purpose Statement

There are several important points to note with React:

  • When you write code in React you can render it in different environments including the web (using React-DOM), server (using Node), and on mobile (using React Native)
  • React focuses on the UI and makes no assumptions about the rest of your website or app’s technology stack
  • React forms the basis for static, dynamic, and hybrid server-side frameworks for building web apps and websites such as Next.js and Gatsby

While React’s approach creates a lot of options for developers, it can be a little overwhelming to those new to React. Options mean choices. Choices with the development environment tooling, testing, and optimization for production as well as the other technology layers involved in any full-stack app.

This is where Create-React-App (CRA) shines! CRA (https://create-react-app.dev/) is a free, open-source, command-line interface (CLI) tool created and officially supported by the React team at Facebook. CRA has been used to create millions of React apps and there’s a very good reason for that.

If you’re an experienced developer and you know you want server-side rendering (SSR), static-site generation (SSG), or any Hybrid combination then you may want to consider starting with Next.js or Gatsby. Otherwise, go ahead and use Create-React-App. In the following sections, we’ll show you how!!!

Create-React-App: An Overview

Whether creating a demo or building a new website or app, Create-React-App (CRA) gets you set up with a new React app, preconfigured for development with build tools chosen, maintained and hidden from the developer. The other great thing is the demo app created by CRA is pre-wired to run in the browser in development mode using a pre-configured development server. You can easily modify this demo to start your project.

Banner for Create-React-App Website Home Page

CRA also comes with other built-in commands to test your app, build an optimized version for production deployment, as well as an “eject” option that exposes all the hidden configuration files for the developer to take full control at any time.

The CRA environment is perfect for beginners learning to create their first React Web App, experienced developers looking to quickly start work on an idea for a Web App that will be deployed to the world and all scenarios in between. That’s why millions of apps have been created with CRA including almost every demo, tutorial, or course you’re likely to watch!

Banner image for idea

How to use Create-React-App

Normally, this is where we would talk about installation instructions except with Create-React-App (CRA) there are none! Really… you don’t need to install, configure or maintain any of the build tools normally required to create a modern web app because CRA sets up your environment using a package runner (no installs required), preconfigures your development environment and hides all this complexity so you can focus on the code.

Let’s get started by creating a project with some initial project structure, complete with a properly-wired demo React App that you can easily modify to quickly start prototyping an idea, following a tutorial, or creating the next big thing!!!

Display Image of Collage of Social Apps

Before You Begin

The only two things you need on your local development machine are Node.js (version 10 or higher) and the Node Package Manager (NPM version 5.2 or higher). Chances are you have both tools already. To verify simply open your computer’s command prompt or terminal window and enter the commands:  node --version and  npm --version

node --version
v14.15.0
npm --version
7.17.0

If you get an error indicating command not found visit nodejs.org and follow the installation instructions for your operating system (Windows, Mac, or Linux). These easy-to-follow instructions (choose LTS version) will install both node and npm.

As a note, do make sure to enable JavaScript on your browser as well – as a JavaScript-based library, even new React projects need this to function correctly.

Now you’re ready to begin!

Create App

Open your computer’s command prompt or terminal window (from now on simply referred to as terminal) to the directory location where you want to create your new project. When you run the CRA command, it will create a new folder, based on the name you provide, inside the current directory and install your entire development environment as well as React demo project in it.

Terminal Command:

npx create-react-app my-app

This command has three parts:

npx

  • NPM Package Runner CLI Tool
  • Available since NPM version 5.2
  • Execute packages from the online NPM Registry without needing to install the code package first

create-react-app

  • NPM Package to execute
  • This is the Create-React-App Command Line Interface (CLI) tool used to create your local React development environment and demo app

my-app

  • Name of the folder that will be created to store the local React development environment and your project code
  • This could be any folder name as long as it meets npm naming restrictions including no capital letters and URL-friendly characters (example: no spaces)

Running the npx CLI command above temporarily installs the latest version of create-react-app, and then executes it to create the dev environment and demo app. The following output displays in the terminal after successful completion.

Terminal Output:

Screen Shot of Create React App Creation Output

This output lets you know that CRA has completed the environment setup. It also provides the list of CRA available commands with brief descriptions (more detail in an upcoming section) and suggests your next two actions:

  1. Change directory to your new project folder (cd my-app)
  2. Start the development server which launches the demo app and makes it available in the browser (at localhost:3000 by default)

Let’s start now by running these commands in the terminal and checking out our newly created project.

Launch App

Change to the new project folder (my-app):

cd my-app

Launch the app:

npm start

This command launches the app by starting the CRA development server. The following output displays in the terminal:

Screen Shot of Create React App Development Server Terminal Output

The demo React app will automatically open in your default browser window at localhost:3000

Screen Shot of Create React App Demo App in Computer Browser

You could also open up another browser to localhost:3000 and the app will appear there as well. It’s also interesting to note the “On Your Network:” address in the above terminal message. Not surprisingly you could enter this address into a web browser and it will also show the app. What’s more interesting is that if you have a phone or other device on the same wifi network as your computer, you could open your device’s browser and enter this address and the React app will open on your device.

Screen Shot of Create React App Demo App in Device's Web Browser

Essential Files and Folders

Open your newly created React app in your favorite code editor and let’s explore the files and folders that were created by default.

Create-React-App Defaults

Running  npx create-react-app my-app creates a project folder named my-app inside the current directory. Inside my-app, Create-React-App (CRA) generates a React web app development environment along with a demo project resulting in the following project (files and folders) structure:

Screen Shot of Create React App Default Files and Folders

The project structure generated by CRA is relatively simple by default and contains everything you need to develop, test, and optimize your app for production deployment.

If you’re new to React or simply creating a demo or following a course it’s worth understanding what the generated files are, how they’re connected and what files can be deleted, added, or renamed. Chances are if you’re watching a tutorial the first thing you’ll notice the instructor do after running CRA to generate the project is start deleting a bunch of files! The following sections contain the essentials you need to know.

Development Essentials

In the image above, showing the default project structure generated by CRA, you’ll notice three folders and three files have been highlighted. The key thing they all have in common is that they must exist and have these exact names.

  • node_modules (folder)
  • public (folder)
  • index.html (file)
  • src (folder)
  • index.js (file)
  • package.json (file)

The node_modules folder contains all packages (code) downloaded from the online NPM Registry. These are the development and production dependencies of your React app. This folder is automatically updated when npm install/uninstall commands are run so it’s best if you just ignore this folder and let it remain closed. If the folder or its contents are accidentally deleted it can be recreated by running the following command (as long as the package.json file exists):

npm install .

The public folder contains the web page (index.html) which is the “single-page” in the Single Page App (SPA) generated by CRA. The other files are image and config files that are only required when building an app for production. In that case, the image and icon files would be replaced with your own and the config files would be modified accordingly. If just learning React, it’s best to ignore this folder and let it remain closed.

The index.html file is the web page which is the “single-page” in the Single Page App (SPA) generated by CRA. For a SPA, this is the only file directly fetched from the server when a user visits your web page. When the browser parses (reads) this HTML file it fetches any files referenced inside. The key reference we’re interested in is our React app which is a JavaScript file. When this file is loaded and executed by the browser, the React app comes to life and you now have a dynamic web app. For those learning React, these are the only important lines of code in the index.html file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

The src folder contains ALL the JavaScript code and CSS styles processed by Create-React-App. If it’s not in this folder, it doesn’t exist!!! Inside the src folder, you can create as many subfolders as your want including subfolders of subfolders. You can also name these subfolders anything you like. Perhaps the most common folder name you’ll find is “components”. Many React developers will create a components folder inside the src folder to hold all React Components developed for use in the app.

As for CSS, you’ll often find two variations: separate .css files that are then imported into JavaScript components (the default option seen in the CRA demo – example below) and CSS styles embedded directly in JavaScript files (styled-components is a popular option for this approach). Note that all images, fonts, and files are added the same way as shown below with the import of both the CSS and the logo image into the App Component.

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

The index.js file is the JavaScript entry point CRA uses to start the build and render of your React app. In this file, React takes the code we’ve written as Components and renders them on the web page. There are several key things to note in the index.js code below:

  •  import React from 'react'; Including the main React library
  •  import ReactDOM from 'react-dom'; React can render on more than just the web so its render logic is in a separate code file. In this case, we are including the React code necessary to render on a web page (HTML) in what is known as the Document Object Model (DOM)
  • import App from './App';Including the App component which makes it available to use inside the index.js file. React builds User Interfaces (UI) by bringing together Components. In the code above, we show the App Component that contains the code to create what you see in the browser when we launched the app with the  npm start command in a previous section
  • The  ReactDOM.render() method places the App component UI inside the  <div id="root"></div> element inside the index.html file as shown above in the index.html file description
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')
);

The package.json file is the only configuration that CRA exposes to the developer. Normally this file would contain a large list of development and production code dependencies as well as build tools. There are only two key things of note for us in this file:

  • The required entries in “dependencies” section are “react”, “react-dom”, and “react-scripts”. The references to “react” and “react-dom” are the code dependencies we noted above as being imported into the index.js file so React can do its work and render that work to the web page. The reference to “react-scripts” is actually the CRA magic!!! In this single reference is the entire React web app development environment including commands to be run that we’ve been referencing throughout this article
  • The “scripts” section is the commands that CRA provides. We’ll discuss these in more detail in the next section. For now, note that each command runs the “react-scripts” and this is how CRA allows us to execute the commands to “start” the development server as well as create an optimized “build” to deploy to production

Banner for Create React App CLI Commands

Create-React-App Built-in Commands

There are two main JavaScript Package Managers (NPM and Yarn) that interact with the online NPM Registry and also run commands (“scripts”) locally in the terminal. As the following examples indicate, you can use npm or yarn (if installed).

Create-React-App (CRA) offers four built-in CLI commands, by default, when it sets up your local React development environment. These commands are exposed as a set of “scripts” defined in the package.json file and executed in the terminal. These four commands or “scripts” are:

Start

npm start or  yarn start

Starts the development server which launches your React app in development mode. You can view the app by opening localhost:3000 in the browser. The dev server will automatically reload the page any time you make changes to the React code. You’ll also be able to view build errors and warnings in the console.

Test

npm test or  yarn test

Starts the test runner in an interactive “watcher” mode. By default, runs tests against all files that have been changed since the project was last committed to a git repository.

Build

npm run build or  yarn build

When you are ready to deploy your app to production, running this build command will bundle React in production mode, minifying and optimizing all code and assets for best performance. The build produced is stored in a folder created named build. This folder contains everything needed to deploy your app to production.

Eject

npm run eject or  yarn eject

It’s important to note that this command is a one-way operation. Once you “eject” you are completely removed from the CRA environment and you can not go back! For experienced developers, this provides a great option because it enables a developer to get a quick start on creating their React app without being concerned about being locked into a controlled environment once their project had outgrown it or they wanted more configuration control.

Banner for Start React App Development

Start React App Development

The best way to learn to code… is to write code! Follow a tutorial, code along, change the code, break the code, fix the code and code something new! Focus on learning more from lessons not on completing more lessons. “I see how that works… now what if I tried this?”

To begin, let’s understand how the demo app works. Then let’s understand the basics of building and composing React components by separating the UI into several simple components which we’ll compose back together.

Installing React Developer Tools

Before we start developing it’s a great idea to install the free and officially created and supported browser extension called “React Developer Tools” which is available for most modern browsers (Chrome, Firefox, Brave, Edge).

For example, search the “chrome web store” for “React Developer Tools” and press the “Add” button. This adds two React-specific tabs (Components and Profiler) to the existing browser dev tools.

Screen Shot of React Developer Tools Install Page

The components tab is a great asset for both developing a React app as well as learning React as it helps you visualize and interact with React components and subcomponents including any information they’re holding in React State, Props, Hooks and more.

Open your browser dev tools with your menu (dev-tools), keyboard shortcut (Option + ⌘ + J on Mac | Shift + CTRL + J on Windows) or right-click your web page and select “inspect”. With dev tools open select the “Components” tab when on a page running React.

How Components are Composed and Rendered

Start by opening a terminal window in your project’s main folder then execute the “start” command to open the React development server:

npm start

The following output displays in the terminal:

Screen Shot of Web page with React Dev Tools open

Your React app will automatically open in your default browser window at localhost:3000

React app open with localhost:3000

Open the browser dev tools and select the Components tab. Notice that we have only one component (App).

This page is rendered by linking three key files:

  • public/index.html
  • src/index.js
  • src/App.js

public/index.html

The important line of code to notice is  <div id="root"></div> which is where our React app will be placed.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

src/index.js

The three important lines of code to notice are:

  • import App from './App'; which is how we include the file named App.js containing our App Component
  • <App /> which is how we place the App Component
  • document.getElementById('root') which is how we link to the HTML element where we want to place the React app
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')
);

src/App.js

This file contains the App Component with the JSX (HTML- looking syntax in the JavaScript code) to be displayed on the Web page where this component is placed.

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

Building an App with Components

Next, Let’s divide the App.js code into several Components. Normally each component would be placed in its own file within a components folder adhering to naming conventions. For example, the file’s name and component’s name should be the same and both should start with a capital letter. For simplicity of illustrating the point in this lesson, we’ll keep all components within the App.js file.

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Logo logo={logo}/>
        <Message/>
        <Message text="Bootstrapped with Create React App"/>
        <ReactLink linkText="Learn React"/>
      </header>
    </div>
  );
}

export default App;

/* Logo component 
- normally in separate file: src/components/Logo.js*/
function Logo(props) {
  return (
    <img src={props.logo} className="App-logo" alt="logo"  />
    );
  }

/* Message component 
- normally in separate file: src/components/Message.js*/
function Message({text}) {
  return (
    <p>
    { text || 'My React App'}
  </p>
  );
}

/* ReactLink component 
- normally in separate file: src/components/ReactLink.js*/
function ReactLink({linkText}) {
  return (
    <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
         {linkText}
        </a>
  );
}

When the React development server is running, any change you make to your code is automatically reflected on the web page. You can see in the Components tab that originally we had only one component (App) and now we still have App but nested inside App is four other components including the Message component that we used twice.

Screen Shot of App and Dev Tools - before and after

Important React notes about code above:

  • props are used to pass static data (text) or dynamic data (variables)
  • props are passed using a syntax similar to HTML attributes except that variables are enclosed in curly braces ( {…} ) whereas static data (text) is enclosed in quotes ( “…” )
  • props are received by a component within the function parameters as an object variable named “props”. The properties and values of this object are the names and values you used on the component in the parent. For example, “logo” for the Logo component and “text” for the Message component. The value can be referenced within the component by using  {props.[name]} such as {props.logo} or destructured as it is passed into  function Message({text}) {...} . When destructured, the property can be used directly  <p>{ text || 'My React App'}</p> and in fact, we can use any JavaScript expression inside the curly braces. In this case, we have default text which will appear if no text is passed in as a prop

This ability to compose small, self-contained, reusable components is one of the things that make working in React a great developer experience.

Banner for Software Testing

Test App

Testing is critical for any application intended for actual use!!!

With the importance of testing in mind, Create-React-App (CRA) includes running tests as one of its core features. The default React development environment generated by CRA has several important “test” elements:

  • Built-in test runner (Jest)
  • CLI command (“script”) to start the test runner
  • Working test file coded to test the demo app

To start the test runner inside CRA, execute the following command:

npm test

This command starts the test runner in an interactive “watcher” mode. By default, tests are run against all files that have been changed since the project was last committed to a git repository. The interactive test runner then asks you what files you want it to watch for changes the next time you run a test. The following is what appears in the terminal window after executing the “test” command above.

Screen Shot of the terminal output after starting CRA interactive test runner

Testing is a huge topic in itself and guidance on how to write tests is outside the scope of this tutorial. If you are new to programming or new to React and your focus is on following tutorials to learn the fundamentals of React then you’ll likely avoid writing formal tests. At this level, writing code along with a tutorial likely won’t focus too heavily (if at all) on working with a test runner and that’s okay.

The reason it’s okay is that coding along with a React fundamentals course likely won’t meet the standard of necessity stated at the beginning of this section “intended for actual use”. When you’re ready to learn more about testing in React you can start with the official React testing docs, Create-React-App testing docs, and the Jest test runner website.

As a final note, if you are new to programming, you may hear developers talk about unit testing and debugging. Each time you update your code and the browser refreshes the act of noticing if the page is working as expected and observing if there are errors in the console means you are “unit testing” your app. When you take action to determine the cause of the errors and fix them you’re entering the territory of “debugging”. This can involve logging information to the console, ensuring the information inside the React Developer tools, that we installed in a previous section, is as expected and taking action in your code to fix the issue, using the browser’s developer tools for debugging, using your code editor’s debugging tools or working with external developer tools.

As we noted above, both “testing” (identifying errors) and “debugging” (finding the root cause of the error and fixing it) are huge topics in themselves. As you work professionally, perhaps as part of a team, you’ll become aware of various levels of testing ranging from the “unit testing” we’ve discussed so far (which is generally performed by a developer) to “integration testing”, “system testing”, “end-to-end” testing and more (which are generally performed by business or functional roles). Generally, the higher you go, the more critical the application being tested, and the context of the application within a larger ecosystem of related apps the more higher-level testing will be required and the more likely test runners, code coverage, and continuous integration testing will become your reality.

For now, when you’re ready to learn more about debugging options you can start with the Create-React-App debugging docs and take it from there!

Banner for Build and Deploy of App

Build and Deploy React App

Software applications are never done!!! When you complete an iteration of your application that you’re ready to move to a production environment that makes it available to a wider group of users or to a public Internet address for the world to discover there is one important step to complete first – optimizing your app and its static assets.

Build – Optimize React App

npm run build

When you are ready to deploy your app to production, running this build command will bundle React in production mode, minifying and optimizing all code and assets for best performance. The build produced is stored in a folder created named “build“. This folder contains everything needed to deploy your app to production.

The best way to test your optimized app before actually deploying it to production is to install an HTTP server locally that will serve your main web page ( index.html file from the newly created build folder). This way, you ensure that your app and all its links and static assets work in production mode. To do this install an NPM package called “serve” as follows:

npm install serve

This “serve” package (which is an HTTP server) is installed locally on your computer and added to the node_modules folder with a config reference placed in the package.json file. If this is something you’ll be using often across multiple projects then it can be installed globally by adding the (-g) flag:  npm install -g serve

To serve our optimized app (from the build folder) run the following command:

serve -s build

This command serves our static site on localhost:5000. Open a browser to this address and you’ll see your production React app just as someone visiting your site from the Internet would see it.

Deploy – Hello World!!!

While you wrote all your code in the src folder and perhaps made adjustments to the index.html file, images, icons, or other static assets in the public folder; everything you need to deploy to production is placed in the build folder after the  npm run build is executed.

There are many options (locations) to deploy your React application for the world to see. The best place to start is the Create-React-App deployment docs which contain options, instructions, and links to guide you through the deployment process.

Banner for Beyond the Basics Section

Beyond the Basics

Selecting a Package Manager

There are two main JavaScript Package Managers (NPM and Yarn) that interact with the online NPM Registry and also run commands (“scripts”) locally in the terminal.

If you do not have Yarn installed on your computer, CRA will use NPM to set up the React development environment as well as install any development and production dependencies.

If, however, Yarn is installed when CRA creates a new app, the CLI will use Yarn instead of NPM. If you prefer to use NPM, you can append  --use-npm when running the CRA creation command.

npx create-react-app my-app --use-npm

Uninstalling Old CRA Versions

Before the NPM Package Runner concept (npx) was introduced in npm version 5.2, create-react-app was generally installed globally via  npm install -g create-react-app. While this method of installation is not recommended, it is still an option.

If you have previously installed create-react-app using this method, it is recommended that you uninstall this package to ensure npx always uses the latest version.

You can easily uninstall create-react-app global installations (-g) using one of the following commands (either from npm or yarn).

npm uninstall -g create-react-app

or

yarn global remove create-react-app

Create-React-App using Templates

Create-React-App (CRA) templates serve two purposes:

  1. Local React development environment including build tools and commands as well as NPM code packages required for both development and production
  2. Files and Folders that your React project will contain when initially created

When you run the basic npx command to create your React development environment it uses the Create-React-App official base template named cra-template.

You can now optionally start a new app by appending officially supported templates such as TypeScript (–template typescript), Redux (–template redux), or Redux-Typescript (–template redux-typescript):

npx create-react-app my-app --template redux-typescript

You can also append community-created templates in the same manner. Search NPM ( https://www.npmjs.com/search?q=cra-template-* ) to see the many available options.

npx create-react-app my-app --template [template-name]

You can also build your own template following these official instructions: https://create-react-app.dev/docs/custom-templates/

Banner in Beyond the Basics section

Adding TypeScript to React App

TypeScript is an open-source language that builds on JavaScript by adding optional static type definitions. This brings to JavaScript the tooling and development power of strongly typed languages (such as Java and C#) without losing the reach and flexibility of JavaScript itself. Since any valid JavaScript is automatically valid TypeScript, it can be gradually adopted.

While JavaScript frameworks such as Google’s Angular use TypeScript by default its use in React is optional (but growing). You can start a new React app using TypeScript by appending the officially supported TypeScript template (–template typescript) to the Create-React-App npx command.

npx create-react-app my-app --template typescript

If you want to add TypeScript to an existing React app, just follow these official instructions: https://create-react-app.dev/docs/adding-typescript/

Analyze React App

By default, CRA includes the ability to measure and analyze the performance of your React app using different metrics. In the src folder is a file named reportWebVitals.js. This file contains a function named  reportWebVitals() that accepts a function (such as  console.log ). When this function is included in the index.js file, it is fired when the values of any of the metrics you’re tracking calculate on the page. The captured values can simply to logged locally or sent to an online endpoint.

Measuring app performance is a significant topic in itself. To get started, you can check out the CRA official documentation on web vitals and capturing analytics.

Banner for Conclusion section

Conclusion

React is an awesome JavaScript library loved by developers all over the world. While React’s approach creates lots of options for developers, it can be a little overwhelming to those new to React. Where there are options, there are decisions to make. These decisions include your local development environment and extend into all areas of software development, testing, and optimization.

To avoid the daunting task of setting up and maintaining your build tooling as well as wiring up your initial app, Facebook (creator and maintainer of React) has released an official command-line interface (CLI) tool called Create-React-App (https://create-react-app.dev/) to take care of all this complexity for you.

If you’re an experienced developer and you know you want server-side rendering (SSR), static-site generation (SSG), or any Hybrid combination then you may want to consider starting with Next.js or Gatsby. Otherwise, Create-React-App is what you want to quickly kickstart your next React project, prototype an idea, follow a tutorial or create the next big thing!!!

Good luck and happy coding!!!

BUILD GAMES

FINAL DAYS: Unlock 250+ coding courses, guided learning paths, help from expert mentors, and more.

]]>