Categories
React

More Ways to Render Large Lists with React

We often have to render large lists in React apps.

In this article, we’ll look at ways to render large lists in React apps.

Virtual Scrolling

The react-virtualized library lets us add a virtualized list into our React app.

It only loads data that is shown on the screen.

To use it, we install it by running:

npm i react-virtualized

Then we can use it bu writing:

import React from "react";
import { List } from "react-virtualized";

export default function App() {
  const data = new Array(1000).fill().map((value, id) => ({
    id: id,
    title: id,
    body: id
  }));

  const renderRow = ({ index, key, style }) => (
    <div>
      <div key={key} style={style} className="post">
        <h3>{data[index].title}</h3>
        <p>item {data[index].body}</p>
      </div>
    </div>
  );
  return (
    <List
      width={window.innerWidth * 0.95}
      height={300}
      rowRenderer={renderRow}
      rowCount={data.length}
      rowHeight={120}
    />
  );
}

We just create the renderRiw function to render the items by their index and style .

The style is computed by react-virtualized to fit the data in the list.

We get the row from data[index] .

rowCount is set to the total row count.

height has the height of the list.

rowHeight has the row’s height.

react-window

The react-window is another virtualized scrolling component.

To install it, we run:

npm i react-window

Then we can add the list by writing:

import React from "react";
import { FixedSizeList as List } from "react-window";

export default function App() {
  const data = new Array(1000).fill().map((value, id) => ({
    id: id,
    title: id,
    body: id
  }));

  const Row = ({ index, key, style }) => (
    <div>
      <div key={key} style={style} className="post">
        <h3>{data[index].title}</h3>
        <p>item {data[index].body}</p>
      </div>
    </div>
  );
  return (
    <List
      width={window.innerWidth * 0.95}
      height={300}
      itemCount={data.length}
      itemSize={120}
    >
      {Row}
    </List>
  );
}

We have the Row component that has the row data.

It’s the same as the previous example’s renderRow function.

We have the List component with the width and height so it can compute the row sizes.

itemSize has the row’s height.

itemCount has the number of items to render.

react-window is faster and smaller than react-virtualized .

Conclusion

We can render large lists with virtual scrolling.

Categories
React

Ways to Render Large Lists with React

We often have to render large lists in React apps.

In this article, we’ll look at ways to render large lists in React apps.

Pagination

We can use the react-paginate library to add pagination to our React lists.

To install it, we run:

npm i react-paginate

Then we can use it by writing:

import React, { useEffect, useState } from "react";
import ReactPaginate from "react-paginate";

export default function App() {
  const [pagination, setPagination] = useState({
    data: new Array(1000).fill().map((value, index) => ({
      id: index,
      title: index,
      body: index
    })),
    offset: 0,
    numberPerPage: 10,
    pageCount: 0,
    currentData: []
  });
  useEffect(() => {
    setPagination((prevState) => ({
      ...prevState,
      pageCount: prevState.data.length / prevState.numberPerPage,
      currentData: prevState.data.slice(
        pagination.offset,
        pagination.offset + pagination.numberPerPage
      )
    }));
  }, [pagination.numberPerPage, pagination.offset]);
  const handlePageClick = (event) => {
    const selected = event.selected;
    const offset = selected * pagination.numberPerPage;
    setPagination({ ...pagination, offset });
  };
  return (
    <div>
      {pagination.currentData &&
        pagination.currentData.map((item, index) => (
          <div key={item.id} className="post">
            <h3>{item.title}</h3>
            <p>item {item.body}</p>
          </div>
        ))}
      <ReactPaginate
        previousLabel="previous"
        nextLabel="next"
        breakLabel="..."
        pageCount={pagination.pageCount}
        marginPagesDisplayed={2}
        pageRangeDisplayed={5}
        onPageChange={handlePageClick}
        containerClassName={"pagination"}
        activeClassName={"active"}
      />
    </div>
  );
}

The ReactPaginate component lets us add pagination controls into our React app.

We have the handlePageClick method to get the data from the array and slice it to get the items we want given the page number.

currentData has the data for the current page.

We get the page number from the event.selected property.

With pagination, we load a small amount of data per page.

Infinite Scroll

Another way to load large amounts of data is to use infinite scrolling.

When we scroll down, we tet more data attached to the list.

To add infinite scrolling, we can use the react-infinite-scroll-component library.

We can install it by running:

npm i react-infinite-scroll-component

Then we can use it by writing:

import React, { useState } from "react";
import InfiniteScroll from "react-infinite-scroll-component";

export default function App() {
  const data = new Array(1000).fill().map((value, id) => ({
    id: id,
    title: id,
    body: id
  }));

  const [count, setCount] = useState({
    prev: 0,
    next: 10
  });
  const [hasMore, setHasMore] = useState(true);
  const [current, setCurrent] = useState(data.slice(count.prev, count.next));

  const getMoreData = () => {
    if (current.length === data.length) {
      setHasMore(false);
      return;
    }
    setTimeout(() => {
      setCurrent(current.concat(data.slice(count.prev + 10, count.next + 10)));
    }, 2000);
    setCount((prevState) => ({
      prev: prevState.prev + 10,
      next: prevState.next + 10
    }));
  };

  return (
    <InfiniteScroll
      dataLength={current.length}
      next={getMoreData}
      hasMore={hasMore}
      loader={<h4>Loading...</h4>}
    >
      <div>
        {current &&
          current.map((item, index) => (
            <div key={index} className="post">
              <h3>{item.title}</h3>
              <p>item {item.body}</p>
            </div>
          ))}
      </div>
    </InfiniteScroll>
  );
}

We add the InfiniteScroll component to add the infinite scrolling container.

dataLength has the number of items to load when we scroll down.

We get more data from the array with the getMoreData method.

And we load the new data and add it to the current array in the setTimeout callback.

Then update the count.prev and count.next properties to update the indexes of the items we want to get.

Conclusion

We can add pagination and infinite scrolling into our React app to load lots of data in an efficient manner.

Categories
JavaScript Basics

JavaScript Cheat Sheet — JSON, Loops, and Promises

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript

JSON

We can create JSON strings from JavaScript objects with the JSON.stringify method:

const obj = {
  "name": "Jane",
  "age": 18,
  "city": "Chicago"
};
const json = JSON.stringify(obj);

And we can convert JSON strings back to JavaScript objects with JSON.parse :

const obj = JSON.parse(json);

We can use it to store data in local storage.

We’ve to convert objects into strings first to store them.

To store objects we call localStorage.setItem :

const obj = {
  "name": "Jane",
  "age": 18,
  "city": "Chicago"
};
const json = JSON.stringify(obj);
`localStorage.setItem('json', json);`

The first argument is the key.

And we can get data by their keys with getItem :

localStorage.getItem('json')

Loops

JavaScript comes with various kinds of loops.

One kind of loop is the for loop:

for (let i = 0; i < 10; i++) {
  console.log(i);
}

We can loop through any kind of iterable object with the for-of loop:

for (let i of custOrder) {
  console.log(i);
}

Some iterable objects include arrays, strings, and node lists.

Another kind of loop is the while loop:

let i = 1;
while (i < 100) {
  i *= 2;
  console.log(i);
}

There’s also the do-while loop:

let i = 1;
do {
  i *= 2;
  console.log(i);
} while (i < 100)

The break keyword lets us end the loop early:

for (let i = 0; i < 10; i++) {
  if (i == 5) {
    break;
  }
  console.log(i);
}

The continue keyword lets us skip to the next iteration:

for (let i = 0; i < 10; i++) {
  if (i == 5) {
    continue;
  }
  console.log(i);
}

Data Types

JavaScript comes with various data types.

They include:

let age = 18;                           // number
let name = "Jane";                      // string
let name = { first: "Jane", last: "Doe" };  // object
let truth = false;                      // boolean
let sheets = ["HTML", "CSS", "JS"];       // array
let a; typeof a;                        // undefined
let a = null;                           // value null

Objects

We can create an object with curly braces:

let student = {
  firstName: "Bob",
  lastName: "Doe",
  age: 18,
  height: 170,
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
};

It has properties and methods.

this is the student object itself.

We can call fullName with student.fullName() .

And we can assign values to properties with:

student.age = 19;

Promises

We can create promises with the Promise constructor:

function add(a, b) {
  return Promise((resolve, reject) => {
    setTimeout(() => {
      if (typeof a !== "number" || typeof b !== "number") {
        return reject(new TypeError("Inputs must be numbers"));
      }
      resolve(a + b);
    }, 1000);
  });
}

We can resolve to fulfill the promise with the sum.

And we call reject to reject the promise with an error.

Then we can call then to get the resolved value and catch to get the error values:

const p = sum(10, 5);
p.then((result) => {
  console.log(result)
}).catch((err) => {
  console.error(err);
});

Conclusion

We can work with JSON, local storage, promises, and loops with JavaScript.

Categories
JavaScript Basics

JavaScript Cheat Sheet — Numbers, Strings, and Regex

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Numbers

The toFixed method lets us round a number:

(3.14).toFixed(0);  // returns 3

The toPrecision method lets us round a number:

(3.14).`toPrecision`(1);  // returns 3.1

The valueOf method returns a number:

(3.14).valueOf();

The Number function lets us convert anything to a number:

Number(true);

parseInt converts non-numeric values to an integer:

parseInt("3 months");

parseFloat converts non-numeric values to a floating-point number:

parseFloat("3.5 days");

The Number function also comes with some constant properties.

They include:

  • Number.MAX_VALUE — largest possible JS number
  • Number.MIN_VALUE — smallest possible JS number
  • Number.NEGATIVE_INFINITY —  negative infinity
  • Number.POSITIVE_INFINITY — positive infinity

Math

We can do various mathematical operations with the Math object.

Math.round rounds a number to an integer:

Math.round(4.1);

Math.pow raises a base to an exponent:

Math.pow(2, 8)

Math.sqrt takes the square root of a number:

Math.sqrt(49);

Math.abs takes the absolute value of a number:

Math.abs(-3.14);

Math.ceil takes the ceiling of a number:

Math.ceil(3.14);

Math.floor takes the floor of a number:

Math.floor(3.14);

Math.sin takes the sine of a number:

Math.sin(0);

Math.cos takes the cosine of a number:

Math.cos(0);

Math.min returns the minimum number in the list:

Math.min(1, 2, 3)

Math.max returns the max number in the list:

Math.max(1, 2, 3)

Math.log takes the natural log of a number:

Math.log(1);

Math.exp raises e to the given power:

Math.exp(1);

Math.random() generates a number between 0 and 1 randomly:

Math.random();

We can generate any random number by using Math.floor and Math.random together:

Math.floor(Math.random() * 5) + 1;

5 is the max number and 1 is the min.

Global Functions

We can use the String function to convert non-string values to strings:

String(23);

We can also call toString on primitive values and objects to do the same:

(23).toString();

The Number function lets us convert non-numbers to numbers:

Number("23");

decodeURI unescapes URLs:

decodeURI(enc);

encodeURI encodes URLs:

encodeURI(uri);

We can decode URI components with decodeURIComponent:

decodeURIComponent(enc);

And we can encode a string into a URI string with encodeURIComponent :

encodeURIComponent(uri);

isFinite lets us check whether a number is finite.

isNaN lets us check whether a value is NaN .

parseFloat lets us parse a value into a floating-point number.

parseInt lets us parse non-number values to integers.

Regex

JavaScript regex has the following modifiers:

  • i — perform case-insensitive matching
  • g — perform a global match
  • m — perform multiline matching

And they can have the following patterns:

  • “ — Escape character
  • d — find a digit
  • s — find a whitespace character
  • b — find a match at the beginning or end of a word
  • n+ — contains at least one n
  • n* — contains zero or more occurrences of n
  • n? — contains zero or one occurrence of n
  • ^ — start of string
  • $ — end of string
  • uxxxx — find the Unicode character
  • . — Any single character
  • (a|b) — a or b
  • (...) — Group section
  • [abc] — In range (a, b or c)
  • [0–9] — any of the digits between the brackets
  • [^abc] — Not in range
  • s — White space
  • a? — Zero or one of a
  • a* — Zero or more of a
  • a*? — Zero or more, ungreedy
  • a+ — One or more of a
  • a+? — One or more, ungreedy
  • a{2} — Exactly 2 of a
  • a{2,} — 2 or more of a
  • a{,5} — Up to 5 of a
  • a{2,5} — 2 to 5 of a
  • a{2,5}? — 2 to 5 of a, ungreedy
  • [:punct:] — Any punctu­ation symbol
  • [:space:] — Any space character
  • [:blank:] — Space or tab

Conclusion

JavaScript comes with many useful functions.

We can use regex to match patterns in strings.

Categories
JavaScript Basics

JavaScript Cheat Sheet — Errors and Strings

JavaScript is one of the most popular programming languages for web programming.

In this article, we’ll look at the basic syntax of modern JavaScript.

Errors

We can use the try-catch block to catch errors from code that may raise errors:

try {
  undefinedFunction();
} catch (err) {
  console.log(err.message);
}

We can run code regardless of whether an error is thrown with the finally block:

try {
  undefinedFunction();
} catch (err) {
  console.log(err.message);
} finally {
  console.log('done');
}

We can throw errors by writing:

throw new Error('error')

JavaScript comes with various kinds of error classes:

  • RangeError — A number is out of range
  • ReferenceError — An illegal reference has occurred
  • SyntaxError — A syntax error has occurred
  • TypeError — A type error has occurred
  • URIError — An encodeURI() error has occurred

Input Values

We can get the entered value from an input element with the value property:

const val = document.querySelector("input").value;

NaN

We can check for NaN values with isNaN :

isNaN(x)

Run Code After a Delay

We can run code after a delay with the setTimeout function:

setTimeout(() => {

}, 1000);

Functions

We can declare functions with the function keyword:

function addNumbers(a, b) {
  return a + b;;
}

Update DOM Element Content

We can update DOM element content by setting the innerHTML property:

document.getElementById("elementID").innerHTML = "Hello World";

Output Data

To log data to the console, we call console.log :

console.log(a);

We can also show an alert box with alert :

alert(a);

Also, we can show a confirm dialog box by calling confirm :

confirm("Are you sure?");

We can ask the user for inputs with the prompt function:

prompt("What's your age?", "0");

Comments

We can add comments to our JavaScript code with // :

// One line

And we can add a multiline comment with:

/* Multi line
comment */

Strings

We can declare strings with quotes:

let abc = "abcde";

Also, we can add a new line character with n :

let esc = 'I don't n know';

We get the length of a string with the length property:

let len = abc.length;

We get the index of a substring in a given string with indexOf :

abc.indexOf("abc");

Also, we can get the last occurrence of a substring in a string with lastIndexOf :

abc.lastIndexOf("de");

We can get a substring between the given indexes with the slice method:

abc.slice(3, 6);

The replace method lets us replace a substring with another substring:

abc.replace("abc","123");

We can convert a string to upper case with toUpperCase :

abc.toUpperCase();

We can convert a string to upper case with toLowerCase :

abc.toLowerCase();

We can combine one string with another with concat :

abc.concat(" ", str2);

And we can get the character at the given index with charAt or [] :

abc.charAt(2);
abc[2];

The charCodeAt method lets us get the character code at the given index:

abc.charCodeAt(2);

The split method lets us split a string by the given separator:

abc.split(",");

We can split a string by an empty string:

abc.split("");

to split a string into an array of characters.

And we can convert a number to a string with the given base with toString :

128.toString(16);

Conclusion

We can throw and catch errors with JavaScript.

And we can use various methods to work with strings.