Categories
JavaScript Basics

Highlights of JavaScript — Alerts, Variables, Numbers, and Strings

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Alerts

The alert function displays an alert box with some text we pass in.

The text comes from the string argument.

For instance, can write:

alert("hello world!");

and ‘hello world’ would be displayed.

It is a global function, so it’s a property of window . window.alert is the same as alert .

The short form is fine for inclusion in our code.

Variables and Strings

Strings are basic elements of JavaScript code. They store text data.

A variable with the given name can only be declared once.

They can be stored in variables. Variables are names that we choose and assign values to so that we can store them for use later.

For example, we can write:

let name = "james";

to store names.

We can set a variable declared with let to a new value.

For example, we can write:

let name = "james";
name = "mark";

Then the value of name will be "mark" .

We can declare a variable and leave it undefined.

For instance, we can write:

let name;
name = "james";

We can do this with variables declared with let .

Variables can be declared with any name that isn’t in the reserved keywords list.

The list is at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords.

Variables aren’t enclosed in quotes and text strings are enclosed in quotes.

JavaScript strings can be enclosed in single or double-quotes.

They can also be enclosed with backticks.

If they’re enclosed with backticks, then they have to have variables embedded in them.

For example, we can write:

let firstName = 'james';
let lastName = 'smith';
let name = `${firstName} ${lastName}`;

We interpolate the value of firstName and lastName into the string. So name should be 'james smith' .

This is a template literal. We can put any expression inside the strings.

This is a very convenient way to combine various expressions into a string.

Now we can assign variables, we can pass variables into alert instead of passing the whole string.

For example, we can write:

let text = "hello world!"
alert(text);

We pass in text into alert as an argument to display the alert.

We can reference text anywhere after it’s defined.

Variables and Numbers

Numbers are another primitive data type with JavaScript.

We can also assign them to variables.

For example, we can write:

let length = 100;

This makes doing operations on it easy. For example, we can add a number to length :

length + 10

then the sum of length and 10 is 110.

We know that length isn’t a variable because it’s not enclosed in quotes.

And numbers alone can be used variable names, so JavaScript knows it’s a number.

We can replace 10 with a variable by assigning it to a variable.

For example, we can write:

let length = 100;
let additionalLength = 10;
let totalLength = length + additionaLength;

We have the additionalLength variable that we add to the length and assign the sum to the totalLength variable.

Conclusion

We can create variables to store numbers and strings and use them with alerts.

Categories
JavaScript Basics

Highlights of JavaScript — Variables and Math Expressions

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Variable Naming

We can’t have variable names that start with a number, but we can have variables that have numbers in the middle.

For example, we can write:

let name1 = "james";

but not:

let 1name = "james";

There are more rules to JavaScript variable naming.

A variable name can’t have any spaces.

Variable names can only have letters, numbers, dollar signs and underscores.

Variable names can’t be a reserved JavaScript keyword, but they can contain them.

Capital letters can be used, but we must be aware that variable names are case sensitive.

So name isn’t the same as Name .

JavaScript variable names are usually camelCase. They let us form variables with multiple words and we can read them all easily.

So we can write variable names like firstName to make the 2 words in the variable name clear.

Math Expressions

Most JavaScript programs will do math. Therefore, JavaScript comes with operators for various common math operations.

For example, we can add with the + operator:

let num = 2 + 2;

To subtract, we can use the - operator:

let num = 2 - 2;

Multiplication is done with the * operator:

let num = 2 * 2;

And division is done with the / operator:

let num = 2 / 2;

There’s also the % modulus operator to find the remainder of the left operand divided by the right one.

For example, we can write:

let num = 2 % 2;

We get 0 because 2 is evenly divisible by itself.

The exponentiation operator is denoted by ** . For example, we can use it by writing:

let num =  2 ** 2;

Then we raise 2 to the 2nd power.

The ++ operator adds the variable’s value by 1 and assign it to the variable.

For example:

num++;

is the same as:

num = num + 1;

We can use the expressions with the assignment operator, but we may get results that we don’t expect.

For example, if we have:

let num = 1;
let newNum = num++;

Then newNum is 1 since the original value of num is returned.

On the other hand, if we have:

let num = 1;
let newNum = ++num;

Then newNum is 1 since the latest value of num is returned if ++ is before the num .

Likewise, JavaScript has the -- operator to subtract a variable by 1 and assign the latest value to the variable.

For example, we can write:

let num = 1;
let newNum = num--;

And we get 1 for newNum and:

let num = 1;
let newNum = --num;

then we get 0 for newNum .

How the values are returned work the same way as ++ .

Conclusion

We have to name JavaScript variables by following its rules.

Also, JavaScript comes with many operators for doing math operations.

Categories
JavaScript Basics

Highlights of JavaScript — Math Expressions and Prompts

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Math Expressions

We should eliminate ambiguity with JavaScript math expressions.

For example, if we have:

let totalCost = 1 + 3 * 10;

then readers may be confused about which operation comes first.

JavaScript has precedence rules for operators. They generally follow the same rules as normal math.

However, we can make everyone’s lives easier by wrapping parentheses around expressions that have higher precedence.

For example, we can write:

let totalCost = 1 + (3 * 10);

then we wrap the expressions around the multiplication.

Now we know the multiplication operation comes first.

If we move the parentheses, then the operations would be done in a different order.

For instance, if we have:

let totalCost = (1 + 3) * 10;

then the addition is done before the multiplication.

Concatenating Strings

Strings are text values and they can be combined with concatenation.

For example, we can write:

alert("Thanks, " + userName + "!");

to combine the 3 expressions into 1 with the + operator.

If userName is 'james' , then we have:

'Thanks, james!'

The 3 parts are combined together and returned as one string.

We can concatenate strings with any other JavaScript expressions.

They’ll be converted to strings automatically so that they can be concatenated together.

So if we have:

alert("2 plus 3 equals " + 2 + 3);

Then we get '2 plus 3 equals 23' .

This is because 2 and 3 are converted to strings before they’re concatenated.

A more convenient way to combine strings and other expressions is to use template literals.

For example, we can write:

alert(`2 plus 3 equals ${2 + 3}`);

We replaced the quotes with the backticks.

Then we use the ${} symbols to surround the JavaScripot expressions to interpolate the expressions.

This way, we have 2 + 3 returning a number since they’re concatenated with strings.

So we get '2 plus 3 equals 5' .

Prompts

A prompt box lets us ask use for some information and provide a response field for the answer.

For example, we can write:

let name = prompt("Your name?", "mary");

We call prompt with the question string as the first argument.

The 2nd argument is the default answer returned.

If we call that, the browser will show an alert box with an input box to let us enter our answer.

Then when we click OK, then the response is returned if it’s entered.

Otherwise, the default answer is returned.

If we omit the default answer in the 2nd argument and we entered nothing, then it returned null .

prompt is a global function, so window.prompt is the same as prompt .

But we can just write prompt .

Conclusion

We can take text answers from a user with the prompt function.

Math expressions can be made clearer with parentheses.

Categories
React

Add Sortable Lists to our React App with React Sortable HOC

The React Sortable HOC library lets us add sortable lists to our React app.

In this article, we’ll look at how to use it to add the lists.

Installation

We install the library by running:

npm install react-sortable-hoc --save

Sortable List

We can use the library to create a sortable list by writing:

import React from "react";
import { SortableContainer, SortableElement } from "react-sortable-hoc";
import arrayMove from "array-move";

const SortableItem = SortableElement(({ value }) => <li>{value}</li>);

const SortableList = SortableContainer(({ items }) => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </ul>
  );
});

class SortableComponent extends React.Component {
  state = {
    items: Array(6)
      .fill()
      .map((_, i) => `item ${i}`)
  };
  onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(({ items }) => ({
      items: arrayMove(items, oldIndex, newIndex)
    }));
  };
  render() {
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
  }
}
export default function App() {
  return (
    <div className="App">
      <SortableComponent />
    </div>
  );
}

We use the SortableElement function to return an element that can be sortable.

Then we created the SortableList component with the SortableContainer that can sort the SortableElement components.

In the SortableComponent component, we add the onSortEnd method to let us swap the positions of the items as we drag and drop them in different positions.

The SortableList component takes the items prop for the items and onSortEnd takes a function to change the indexes.

oldIndex and newIndex are the old and new index respectively.

We use the array-move package to let us swap the positions of the array easily.

Props

The SortableList takes many other props.

axis sets the axis to sort by.

localAxis lets us lock the movement of an axis while sorting.

helperClass lets us set a class to style the list and items.

transtionDuration sets the transition duration when element shift positions.

keyCodes has an object with an array of keycodes for keyword accessible actions.

pressDelay lets us set the delay after clicking the item before we can sort the item.

onSortStart , onSortMove , and onSortOver are functions that are run when sorting starts, when we move the item, and when sorting is done respectively.

useDragHandle lets us set whether we want to show the drag handle.

getHelperDimensions lets us set the computed dimensions of the SortHelper .

Conclusion

The React Sortable HOC lets us create sortable lists easily within a React app.

Categories
React

Create Tables with Virtual Scrolling in a React App with the react-window Library

We can create tables that use virtual scrolling with the react-window library.

A virtual scrolling table is more efficient than a regular one since it loads the data only when it’s displayed on the screen.

In this article, we’ll look at how to create tables with the react-window library.

Installation

We can install the package by running:

yarn add react-window

or

npm install --save react-window

Creating the Table

We can create a simple table by writing:

App.js

import React from "react";
import { FixedSizeList as List } from "react-window";
import AutoSizer from "react-virtualized-auto-sizer";
import "./styles.css";

const Row = ({ index, style }) => (
  <div className={index % 2 ? "ListItemOdd" : "ListItemEven"} style={style}>
    Row {index}
  </div>
);

const Table = () => (
  <AutoSizer>
    {({ height, width }) => (
      <List
        className="List"
        height={height}
        itemCount={1000}
        itemSize={35}
        width={width}
      >
        {Row}
      </List>
    )}
  </AutoSizer>
);

export default function App() {
  return (
    <div className="App" style={{ height: 300 }}>
      <Table />
    </div>
  );
}

style.css

.List {
  border: 1px solid yellow;
}

.ListItemEven,
.ListItemOdd {
  display: flex;
  align-items: center;
  justify-content: center;
}

.ListItemEven {
  background-color: yellow;
}

We created the Row component with that we use as the row.

It takes the index and style props with the index of the entry and the styles respectively.

The Table component uses the AutoSizer component from react-virtualized-auto-sizer to size the list and its items properly.

className is the class name for the list.

height is the height of the list, which is calculated automatically by AutoSizer .

itemCount has the number of rows.

itemSize has the number of items to load each time.

width has the width of the rows, which is also automatically calculated.

The Row component is added as the child of List to display it.

Then we set the height of the div in App to display the list.

Create a Table

We can create a table by using the Grid component.

For example, we can write:

import React, { forwardRef } from "react";
import { FixedSizeGrid as Grid } from "react-window";
import "./styles.css";
const GUTTER_SIZE = 5;
const COLUMN_WIDTH = 100;
const ROW_HEIGHT = 35;

const Cell = ({ columnIndex, rowIndex, style }) => (
  <div
    className="GridItem"
    style={{
      ...style,
      left: style.left + GUTTER_SIZE,
      top: style.top + GUTTER_SIZE,
      width: style.width - GUTTER_SIZE,
      height: style.height - GUTTER_SIZE
    }}
  >
    row {rowIndex}, col {columnIndex}
  </div>
);

const Table = () => (
  <Grid
    className="Grid"
    columnCount={20}
    columnWidth={COLUMN_WIDTH + GUTTER_SIZE}
    height={300}
    innerElementType={innerElementType}
    rowCount={100}
    rowHeight={ROW_HEIGHT + GUTTER_SIZE}
    width={400}
  >
    {Cell}
  </Grid>
);

const innerElementType = forwardRef(({ style, ...rest }, ref) => (
  <div
    ref={ref}
    style={{
      ...style,
      paddingLeft: GUTTER_SIZE,
      paddingTop: GUTTER_SIZE
    }}
    {...rest}
  />
));

export default function App() {
  return (
    <div className="App" style={{ height: 500 }}>
      <Table />
    </div>
  );
}

We create the Cell component for the table by getting the coumnIndex , rowIndex , and style .

style is passed to the style prop.

Also, we make a gutter by adding the GUTTER_SIZE to left and top and subtract it from width and height .

We display the rowIndex and columnIndex as the content.

The Cell s are used in the Grid component.

We set the columnCount to set the number of columns to display.

columnWidth sets the width of the column.

height has the height of the table.

innerElementType is a ref to the component with the given styles for the grid used for the cell container.

rowCount has the number of rows.

rowHeight has the row’s height.

width has the width of the table.

We then use the Table component in our App component.

Now we should see a 400px by 300px table displayed.

Conclusion

We can create a table with the react-window component by setting the computed dimensions to the cells and table container.