Git in the Command Line for Beginners

Create a new folder using this command (insert your folder name in the placeholder):

mkdir folder-name

Now we’ll use this command to initialize an empty Git repository within our new folder:

git init

This command initializes an empty Git repository within the folder. The folder is now considered a “working directory.”

Working directory: The directory the .git directory is placed in

You won’t be able to see the .git file in the file system, though. In the Command Line, you have to type the following command to see the hidden files within your working directory in order to see the .git file:

ls -a

In order to commit your files so that you can start tracking changes in them, you must first add your files to the staging area.

Staging area: intermediate place where you can pick and choose which files inside your working directory that you want to commit

Use this command to see which files are currently untracked:

git status

Untracked files will show up in red.

Use this command to add files to your Git staging area (insert your file name in the placeholder):

git add your-file

Use this command to commit all files within the staging area to Version Control:

git commit -m "Initial Commit"

It’s recommended to add a commit message whenever you make a commit so you can differentiate the purpose behind different commits in the same project.

Use this command to see any previous commits you’ve made:

git log

When you have multiple files, it can get tedious adding each one of them to the staging area individually. You can use this command to add every (untracked) file in the working directory to the staging area:

git add .

Files flow in this sequence: Working directory -> staging area -> local repository

Even if we mess up our file(s), we still have access to any versions that were saved under Version Control. We can get access to these previous versions of our files using this command:

git checkout your-file

If you wanted to look at the differences between the current version of a file and the last version saved in Git Version Control, you can use this command:

git diff your-file

Setup React Front-End in Existing Project

Let’s say you’re building with the MERN stack, for example. You have an existing project folder in which you’ve set up your entire backend server with Express and connecting your MongoDB database. Now you want to append a React frontend to the project. How do you setup a new React project within your existing overall project folder?

cd into your existing project folder and run this command:

npx create-react-app [your-folder-name]

This line basically creates a React application within a folder with whatever name you choose (ex. client) within your current project directory. npx is a tool that comes with Node.js that allows us to run create-react-app without having to install it globally on our machine.

To run your React project to make sure everything installed successfully, run these commands:

cd [your-folder-name]
yarn start

Run Frontend and Backend at the Same Time

We can run our frontend React app and backend Node.js server at the same time using the development tool concurrently.

Install concurrently as a development dependency:

npm i -D concurrently

Define the necessary scripts within your package.json:

"scripts": {
    "start": "node server",
    "server": "nodemon server",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
},

The “dev” script uses concurrently to run the “server” and “client” scripts at the same time– with one single command.

In the root folder, run the “dev” script:

npm run dev

Installing Dependencies Within the React Project

You install dependencies within a submerged React project the same way you would within an non-submerged React project.

First, make sure you’re inside the React project folder. My folder name is client so:

cd client

Then, install dependencies with npm

npm i react-redux axios ...

Get Ride of Default Git Repository Within React App

Within the React app, a git repository is automatically initialized on the creation of the React app. If you already have a Git repository within your root project, you don’t necessarily need another one for your React project. If you wanted to delete the React repository, you would

  1. Delete the .gitignore and README.md files within the React folder
  2. Delete the Git folder

This is the command to delete the git folder. Make sure you cd into your React folder before running this command or you might delete your root repository:

rm -rf .git

How to Toggle the Minimap in Visual Studio Code

What is the minimap?

On the far-right side of your Visual Studio workspace, you may have a small file preview panel that shows a faint outline of the entire file that you’re currently in.

This little panel is called the minimap. Visual Studio Code’s definition of the minimap is as follows:

“A Minimap (code outline) gives you a high-level overview of your source code, which is useful for quick navigation and code understanding. A file’s minimap is shown on the right side of the editor. You can click or drag the shaded area to quickly jump to different sections of your file.”

The minimap can be annoying in some circumstances; for example, by limiting the length of your coding window.

How to Toggle the Minimap

  1. Go to View > Command Palette (Ctrl + Shift + P on Windows, Cmd + Shift + P on Mac)
  2. Type “minimap”
  3. Press on ‘View: Toggle Minimap’ to toggle it on and off

JWTs (JSON Web Tokens)

What is JWT used for?

It is used for authorization, not authentication. Authentication is checking if a username and password are correct then logging a user in. Authorization is making sure that the user that is sending requests to your server is the same user that actually logged in during the authentication process.

The basic idea of JWT is a simple way for securely transmitting information between parties as a JSON object

What is the JSON Web Token structure?

A JWT is basically just a bunch of random characters. The token is separated into 3 sections: Header, Payload, and Signature. These sections are separated by dots (.) The structure looks like the following:

xxxxx.yyyyy.zzzzz

The JWT website (https://jwt.io) offers a great breakdown of an actual token:

Header

The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used. Here’s an example:

{
   "alg": "SHA256", 
   "typ": "JWT" 
}

Then, this JSON is Base64Url encoded to form the first part of the JWT.

Payload

The payload is the data that you want to send within the token. In the example, the data being sent is a variable called name with a value of John Doe.

{ 
   "sub": "1234567890", 
   "name": "John Doe",
   "admin": true 
}

Another example might be sending an id variable with a unique value that differentiates all of the users of a website.

Signature

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

The signature is used to verify the message wasn’t changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

The output is three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments.

Implementing JWT in Node applications

First, install the jsonwebtoken package with npm.

npm i jsonwebtoken

Get access to JWT in the file

const jwt = require("jsonwebtoken");

Create the payload

const payload = { 
   user: { 
      id: user.id 
   }
}

Sign the token. Pass in the payload, pass in the secret, and inside the callback, we’ll either get the error or a token. If we get a token, we’ll send a response back to the client with that token.

jwt.sign(
   payload, 
   config.get('jwtSecret'), 
   { expiresIn: 360000 }, 
   (err, token) => {
      if (err) throw err;
      res.json({ token });
});

When you create a new user, if everything is successful, the callback should return a token like this:

{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7ImlkIjoiNWYwMjY2ZWM3ZjE4Y2JmNTg0NjgwZDM0In0sImlhdCI6MTU5Mzk5Mjk0MCwiZXhwIjoxNTk0MzUyOTQwfQ.8qiRsqHH-mSSrr9itAQzmSLUu8easVTNdeoUxg0AC0U"
}

If we paste this token that we’ve just created into the website that I showed you earlier, we can breakdown it’s header, payload, and signature:

In the payload, you can see our User object with its unique Mongo id (“user”, “id”), the date that the token was issued at (“iat”), and the expiration date that we defined (“exp”).

Event Handling in React

This is the App.jsx file. You would render an App Component in the ReactDOM.render method inside the index.js file. You can create your own HTML pages and CSS styles.

import React, { useState } from "react";

function App() {
   const [isMousedOver, setMouseOver] = useState(false);

   function handleMouseOver() {
      setMouseOver(true);
   }

   function handleMouseOver() {
      setMouseOver(false);
   }

   return (
      <div>
         <button
            style={{ backgroundColor: isMousedOver ? "black" : "white" }}
            onMouseOver={handleMouseOver}
            onMouseOut = {handleMouseOut}
         >
            Hover
         </button>
      </div>
   );
}

export default App;

State in React

State is a React concept that allows us to make our apps more interactive and mutable.

React components has a built-in state object. 

The user interfaces re-renders based on the value of state variables.

Declarative programming: the use of variables such as state to change an object’s property

Imperative programming: explicitly setting an object’s property

Imperative programming is about how a program works while Declarative programming is about what a program does. 

Using regular variables to declaratively change the user interface of a React component will not work. You need a special kind of variable in order to cause React elements to re-render: State variables. You also need special functions called Hooks that look– or hook— into the state of your app to read and modify it.

You use the useState hook in order to get access to the component’s state.

import React from "react";

function App() {
   const state = React.useState();
}

Whatever we put into the parentheses of the useState function is the initial state of the component.

const state = React.useState(123);

If we wanted to access the state variable we just created, we would extract the first element of the state array:

console.log(state[0])
// prints out 123

Whenever you change state, React updates any UI elements corresponding w/ that piece of state automatically.

Using state[0] to access state variables is kind of unintuitive though and not the most efficient way to code. So we can use destructuring to make it easier on us as programmers:

const [count] = useState(123);

console.log(count);
//prints 123

How do we change the value of state variables?

const [count, setCount] = useState(123);

setCount(count - 1);

console.log(count);
// prints 122

React Conditional Rendering with the Ternary Operator & AND Operator

JSX only allows you to use JavaScript expressions within curly braces. It does not allow you to enclose JavaScript statements.

So if you wanted to use a condition to decide which content to render on the screen, you COULD NOT use a statement like this:

return <div>{
   if (isLoggedIn === true){
      return <h1>My Favorite Foods</h1>
   } else {
      return <p>My Least Favorite Foods</p>
   }
}</div>;

Instead, you would have to use a ternary operator. This is how ternary operators work:

condition ? do if true : do if false
foodAtHome === true ? makeFood() : buyFood()

So this is how you would accomplish the task from above:

return <div>{
   isLoggedIn === true ? <h1>My Favorite Foods</h1> : <p> My Least Favorite Foods</p>
}</div>;

Another way you can incorporate logic into your JSX objects is with the AND operator. The AND operator in React checks if the first condition is true or false. If true, it looks to see if the expression is also true then displays the expression. If the statement is false, it will not even look at the expression.

condition && expression
true && expression
false && -expression-

Here’s an example of the AND operator:

return <div>{
   currentTime > 12 && <h1>It's not the morning</h1>
}</div>;

JavaScript ES6 Arrow Functions

Arrow functions are just a shorter way of writing a JavaScript function.

This is an example of using a square function within the JS map function to easily loop through a list of numbers.

var numbers = [1, 2, 3, 4, 5];

const newNumbers = numbers.map(function square(x) {
   return x * x;
});

We can remove the word “square” from our function. Now, the function within the map function is an anonymous function.

var numbers = [1, 2, 3, 4, 5];

const newNumbers = numbers.map(function(x) {
   return x * x;
});

We can make this even simpler by turning the anonymous function into an arrow function.

var numbers = [1, 2, 3, 4, 5];

const newNumbers = numbers.map(x => x * x);

The first x is the parameter; the x * x is an expression. Since the contents of the function are only 1 line, we can remove the return keyword and the curly braces. We can also remove the parentheses from around the parameter since there is only 1 parameter.

Here are some more arrow function examples.

const newNumbers = numbers.map((x, y) => x * y);
const newNumbers = numbers.map(x => {
   return x * x;
});

Mapping React Components

We can use the JavaScript map function to make our code a lot cleaner when creating multiple components of the same type from a JSON-type data source.

So instead of having something like this:

function App() {
   return (
      <div>
         <Card 
            name={contacts[0].name}
            img={contacts[0].img}
            tel={contacts[0].phone}
          />
          <Card 
            name={contacts[1].name}
            img={contacts[1].img}
            tel={contacts[1].phone}
           />
          <Card 
            name={contacts[2].name}
            img={contacts[2].img}
            tel={contacts[2].phone}
           />
         ...

We can use something like this:

function createCard(contact) {
   return <Card name={contact.name} img={contact.img} />
}

function App() {
   return (
      <div>
         {contacts.map(createCard)}
         ...

We still have something to fix though. Once you run your new code, you should get this warning:

This is because we don’t have a key prop in our child components. The key must be unique among each of the mapped components.

function createCard(contact) {
   return <Card 
      key={contact.id}
      name={contact.name} 
      img={contact.img} 
   />
}

The key CANNOT be used as a property in the component’s props array. The key is for React to use, not us.

How to Set up React DevTools on Google Chrome

Sometimes it will make sense to have components within components. Or components within components within components. Over time, if you accumulate a lot of properties and components, it can be hard to keep track of everything. React DevTools can help with that.

React DevTools show your React DOM tree.

How to Install React DevTools

  1. Open Google Chrome
  2. Go to https://chrome.google.com/webstore
  3. Search and open “React Developer Tools”
  4. Press the “Add to Chrome” button

Once it is done installing, you should see a new symbol show up next to your search bar

How to Use React DevTools

  1. Open up Chrome Developer Tools (View > Developer > Developer Tools)
  2. Open the Components tab
  3. You should see your React DOM tree