Categories
Top React Libraries

Top React Libraries — Tables, Masks, and Scroll Bars

To make developing React apps easier, we can add some libraries to make our lives easier.

In this article, we’ll look at some popular libraries for React apps.

rc-table

rc-table is a library for adding simple tables in our React app.

To use it, we can run:

npm i rc-table

to install it.

Then we can use it by writing:

import React from "react";
import Table from "rc-table";

const columns = [
  {
    title: "Name",
    dataIndex: "name",
    key: "name",
    width: 100
  },
  {
    title: "Age",
    dataIndex: "age",
    key: "age",
    width: 100
  },
  {
    title: "Address",
    dataIndex: "address",
    key: "address",
    width: 200
  },
  {
    title: "",
    dataIndex: "",
    key: "operations",
    render: () => <a href="#">Delete</a>
  }
];

const data = [
  { name: "james", age: 18, address: "address", key: "1" },
  { name: "mary", age: 26, address: "address", key: "2" }
];

export default function App() {
  return (
    <div className="App">
      <Table columns={columns} data={data} />
    </div>
  );
}

We specify the columns in the columns array.

The title is the displayed text.

dataIndex is the property name to display in the column.

key is the unique ID of the column.

width has the width.

render is a function that returns some components.

We also have the data array with the objects we want to display.

In App , we pass them all into the Table component as props to render the table.

It provides us with many other options like changing table layout, styles, making the table expandable, and more.

simplebar-react

simplebar-react lets us add a styled scrollbar to our app.

To install it, we run:

npm i simplebar-react

Then we can use it by writing:

import React from "react";
import SimpleBar from "simplebar-react";
import "simplebar/dist/simplebar.min.css";

export default function App() {
  return (
    <div className="App">
      <SimpleBar style={{ maxHeight: 300 }}>
        {Array(1000)
          .fill()
          .map((_, i) => (
            <p>{i + 1}</p>
          ))}
      </SimpleBar>
    </div>
  );
}

We just use the SimpleBar component with the bundled CSS.

The style prop is set to an object with the maxHeight .

Then we display an array of p elements within the SimpleBar component.

Then we’ll see the scrollbar provided by the package displayed.

There are also other options like forcing the scrollbar to be visible and auto-hiding scrollbars.

We can also access the SimpleBar instance with refs.

React Input Mask

The React Input Mask package is a component to let us add input masks to our app.

To install it, we run:

npm i react-text-mask

Then we can use it by writing:

import React from "react";
import MaskedInput from "react-text-mask";

export default function App() {
  return (
    <div className="App">
      <MaskedInput
        mask={[
          "(",
          /[1-9]/,
          /d/,
          /d/,
          ")",
          " ",
          /d/,
          /d/,
          /d/,
          "-",
          /d/,
          /d/,
          /d/,
          /d/
        ]}
      />
    </div>
  );
}

We use the MaskedInput component with the mask prop.

It has an array of the parts of the pattern we want to restrict the inputted value to.

It can be customized with custom components.

Also, we can add placeholders, class names, and blur and change handlers:

import React from "react";
import MaskedInput from "react-text-mask";

export default function App() {
  return (
    <div className="App">
      <MaskedInput
        mask={[
          "(",
          /[1-9]/,
          /d/,
          /d/,
          ")",
          " ",
          /d/,
          /d/,
          /d/,
          "-",
          /d/,
          /d/,
          /d/,
          /d/
        ]}
        className="form-control"
        placeholder="Enter a phone number"
        guide={false}
        id="phone-input"
        onBlur={() => {}}
        onChange={() => {}}
      />
    </div>
  );
}

We add the class name and placeholder to add styles and placeholders to them.

Also, we have the onBlur and onChange props to add those handlers to our app.

The guide is a boolean to indicate whether we want to show the characters with hints.

Conclusion

rc-table lets us add a simple table with ease.

simplebar-react is a scrollbar component for our React app.

React Input Mask lets us add an input mask to our app.

Categories
Modern JavaScript

Best of Modern JavaScript —Template Literals

Since 2015, JavaScript has improved immensely.

It’s much more pleasant to use it now than ever.

In this article, we’ll look at JavaScript template literals.

Template Literals

A template literal is a string literal where we can interpolate JavaScript expressions right into the string.

For example, we can write:

const firstName = 'james';
console.log(`Hello ${firstName}`);

Then we get:

'Hello james'

It’s delimited by backticks instead of single and double-quotes.

Escaping in Template Literals

The backslash is used for escaping inside template literals.

For example, we can write:

`\``

and get:

'`'

However, we can’t write:

`${`

since we’ll get a SyntaxError.

Other than that, they work like regular string literals.

Line terminators in template literals are always LF.

LF is the line feed character, which is n or U+000A which is used by Unix and macOS.

CR, which is r or U+900D is used by old Mac OS.

CRLF, which is rn is used by Windows.

They’re all normalized to LF in template literals.

Tagged Template Literals

Tagged template literals is putting a tag in front of a template literal.

For example, we can write:

tagFunction`Hello ${firstName} ${lastName}`

where tagFunction is a function that we call on the string.

It’s the same as writing:

`tagFunction(['Hello ',` `' '],` `firstName,` `lastName)`

The tag takes the template string and substitutions for the placeholder.

The substitutions are done at runtime.

But template strings are known statically at compile time.

Tag functions also gets the raw version which isn’t interpreted.

It also gets the final version where the backslashes are special.

Raw Strings

ES6 has the String.raw template tag for raw strings.

It returns the string with all the backslashes intact.

For example, we can write:

const str = String.raw`Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus fringilla mauris vel erat facilisis lacinia. n

Vivamus tincidunt, massa sit amet fermentum rhoncus, nibh mi convallis elit, eget bibendum eros ipsum elementum purus. Donec tristique ligula mi, non dapibus quam finibus et. Orci varius natoque penatibus et magnis dis parturient montes`

with the n intact.

This is useful whenever we need to keep the backslashes in our strings.

We can use the sh template tag to run shell commands.

For example, we can write:

`const` `proc` `=` ``sh`ps ax | grep ${pid}`;``

Packages like the sh Template Tag package provides us with the sh template tag to run commands with the tag.

Facebook GraphQL

Facebook Relay lets us make queries to a GraphQL API.

For example, we can use it by writing:

import React from "react"
import { createFragmentContainer, graphql, QueryRenderer } from "react-relay"
import environment from "./lib/createRelayEnvironment"
import ArtistHeader from "./ArtistHeader"

export default function ArtistRenderer({artistID}) {
  return (
    <QueryRenderer
      environment={environment}
      query={graphql`
        query QueryRenderersArtistQuery($artistID: String!) {
          # The root field for the query
          artist(id: $artistID) {
            # A reference to your fragment container
            ...ArtistHeader_artist
          }
        }
      `}
      variables={{artistID}}
      render={({error, props}) => {
        if (error) {
          return <div>{error.message}</div>;
        } else if (props) {
          return <Artist artist={props.artist} />;
        }
        return <div>Loading</div>;
      }}
    />
  );
}

using the example from https://relay.dev/.

We just pass in our own template string into the graphql tag to make the request.

Conclusion

Template strings are useful.

They let us interpolate expressions and call them with tags.

Categories
Top React Libraries

Top React Libraries — Tabs, Notifications, Numeric Inputs, and File Upload

To make developing React apps easier, we can add some libraries to make our lives easier.

In this article, we’ll look at some popular libraries for React apps.

react-tabs

The react-tabs package lets us add tabs to our React app.

To install it, we run:

npm i react-tabs

Then we can use it by writing:

import React from "react";
import { Tab, Tabs, TabList, TabPanel } from "react-tabs";
import "react-tabs/style/react-tabs.css";

export default function App() {
  return (
    <div>
      <Tabs>
        <TabList>
          <Tab>tab 1</Tab>
          <Tab>tab 2</Tab>
        </TabList>

        <TabPanel>
          <h2>some content</h2>
        </TabPanel>
        <TabPanel>
          <h2>more content</h2>
        </TabPanel>
      </Tabs>
    </div>
  );
}

We import the CSS and components that comes with the package.

Then we use the Tabs component with the TabList for adding the tab links.

TabList has the tabs links inside.

Tab is the button we can click on to switch tabs.

TabPanel has the content for each tab.

Now we get tabs with content without doing much work.

rc-upload

rc-tree is a package that provides us with a file input component.

To use it, we install it by running:

npm i rc-upload

Then we can use it by writing:

import React from "react";
import Upload from "rc-upload";

const uploaderProps = {
  action: "/upload",
  data: { foo: 1, bar: 2 },
  headers: {
    Authorization: "token"
  },
  multiple: true,
  beforeUpload(file) {
    console.log("beforeUpload", file.name);
  },
  onStart: file => {
    console.log("onStart", file.name);
  },
  onSuccess(file) {
    console.log("onSuccess", file);
  },
  onProgress(step, file) {
    console.log("onProgress", Math.round(step.percent), file.name);
  },
  onError(err) {
    console.log("onError", err);
  }
};

export default function App() {
  return (
    <div>
      <div
        style={{
          margin: 100
        }}
      >
        <div>
          <Upload {...uploaderProps}>upload file</Upload>
        </div>

        <div
          style={{
            height: 200,
            overflow: "auto",
            border: "1px solid red"
          }}
        >
          <div
            style={{
              height: 500
            }}
          >
            <Upload
              {...this.uploaderProps}
              id="test"
              component="div"
              style={{ display: "inline-block" }}
            >
              another uploader
            </Upload>
          </div>
          <label>Label for Upload</label>
        </div>
      </div>
    </div>
  );
}

We have the Uploader component which has the file upload input.

uploaderProps has an object with the upload URL, headers, data and more.

data has the request data.

action has the URL.

And we also pass in various event handlers that run in various situations.

It takes handlers for before upload, when upload starts, success, error, and progress.

rc-input-number

rc-input-number provides us with numeric input.

To install it, we run:

npm i rc-input-number

Then we use the InputNumber component that comes with the library:

import React from "react";
import InputNumber from "rc-input-number";

export default function App() {
  return (
    <div>
      <InputNumber defaultValue={100} />
    </div>
  );
}

The defaultValue has the value for the input.

We can make it a controlled input with the value and onChange props:

import React from "react";
import InputNumber from "rc-input-number";

export default function App() {
  const [value, setValue] = React.useState(100);
  const onChange = value => {
    setValue(value);
  };

  return (
    <div>
      <InputNumber value={value} onChange={onChange} />
    </div>
  );
}

We have a function to set the value state and get the value and pass it to the value prop as with any other inputs.

Also, we can make it read-only or disable it.

The formatting of the number can also change.

rc-notification

rc-notification provides us with a UI component for adding notifications in a React app.

To install it, we run:

npm i rc-notification

Then we can use it by writing:

import React, { useEffect } from "react";
import Notification from "rc-notification";

export default function App() {
  useEffect(() => {
    Notification.newInstance({}, notification => {
      notification.notice({
        content: "content"
      });
    });
  }, []);

  return <div />;
}

We import the Notification object and call the newInstance method to display a notification within the callback.

The notice method shows the notification content.

content has the notification content.

By default, it displays for 1.5 seconds.

We can change the duration of that it’s displayed, the styles, and more.

We can also remove the notification programmatically.

Conclusion

react-tabs lets us add tabs.

rc-upload is a file uploader component.

rc-input-number is a numerical input for React apps.

rc-notification is a simple notification component.

Categories
JavaScript Basics

Highlights of JavaScript — do…while Loops and Scripts

To learn JavaScript, we must learn the basics.

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

do…while Loops

We can use the do...while loop to repeatedly run code.

The do block is always run, so the first iteration is always run.

For example, we can write:

let i = 0;
do {
  console.log(i);
  i++;
} while (i <= 3);

The do block is always run because the while condition is checked after the iteration of a loop is done.

Script Tags

To run JavaScript code in the browser, we have to add script tags to our code.

For example, we can write:

<script>
  function sayHi() {
    alert("hi");
  }

  function sayBye() {
    alert("bye");
  }
</script>

We define the sayHi and sayBye functions in the script tag.

We can have any JavaScript code in our script tags.

JavaScript code is just text, so we can add them to HTML files easily, since they’re also text.

If we have lots of code in between the script tags, then we should move them to their own file.

For example, we can write:

<script src="script.js"></script>

We create a script.js file and then reference it with the src attribute.

This way, we can keep our code files short.

Comments

We can add comments to our JavaScript code to explain what we’re doing what our code.

For example, we can write:

// This is a comment
for (let i = 0; i < 10; i++) {
  console.log(i);
}

The // indicates the start of a comment. It’ll be ignored by the browser.

We can write multiline comments by writing:

/*
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas at volutpat ipsum, dapibus tincidunt nisl. Donec vestibulum ultricies laoreet. Suspendisse sit amet faucibus justo.
*/
for (let i = 0; i < 10; i++) {
  console.log(i);
}

We have a long comment that spans multiple lines. It’s delimited by /* and */ .

Link Events

When we click links, we can listen to events emitted by the links when we do something to them like clicking it.

This is handy for using it to do something in addition to letting us click to go to a different page.

For example, we can write:

<a href="#" onClick="alert('hello');">Click</a>

We add the onClick attribute to an a tag so that we can run JavaScript code in it.

onClick isn’t case sensitive.

href='#' tells the browser to reload the page, which is probably not what we want when we want to run JavaScript code when we click the link.

To prevent the page from being refreshed, we can write:

<a href="javaScript:void(0)" onClick="alert('hello');">Click</a>

We add the javaScript.void(0) code to avoid the refresh.

If we want to write multiple statements, we can write:

<a href="javaScript:void(0)" onClick="let greeting='hi'; alert(greeting);">Click</a>

We separate the statements with a semicolon.

Conclusion

We can use the do...while loop to run a loop where the first iteration always runs.

Also, we can embed JavaScript in various ways within our HTML code.

Categories
JavaScript Basics

Highlights of JavaScript — Variables, Switch, and While Loops

To learn JavaScript, we must learn the basics.

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

Local vs Global Variables

JavaScript has local and global variables.

Local variables are accessible only within a block.

And global variables are available throughout the app.

With JavaScript, we create local variables with the let and const keywords.

They are all block-level, so they’re all only available within a block like functions, and if blocks.

let creates a variable, and const creates constants.

Constants can’t be reassigned a new after it’s assigned a value.

But the content may still change.

Constants must have an initial value assigned to it when it’s created.

For example, if we have:

function addNumbers() {  
  let theSum = 2 + 2;  
}

The theSum is only available within the addNumbers function.

But if we have:

function addNumbers() {  
  theSum = 2 + 2;  
}

then theSum is a global variable.

We can access the value anywhere.

If a variable is global, then it’s attached property of the window global object.

We should avoid global variables since it’s easy to create global variables with the same name.

Therefore, it’s easy to have conflicts.

And it’s hard to track how variables are changed.

Switch Statements

The switch statement lets us do different things for different cases in one statement.

For example, we can write:

switch (dayOfWk) {  
  case "Sat":  
    alert("very happy");  
    break;  
  case "Sun":  
    alert("happy");  
    break;  
  case "Fri":  
    alert("happy friday");  
    break;  
  default:  
    alert("sad");  
}

We check the value of dayOfWk to let us do different things when it has the given values.

If dayOfWk is 'Sat' , then we show a 'very happy' alert.

If dayOfWk is 'Sun' , then we show a 'happy' alert.

If dayOfWk is 'Fri' , then we show a 'happy friday' alert.

The default clause is run when dayOfWk has any other value, and we show the 'sad' alert.

The break keyword is required so that the rest of the switch statement won’t run after a case is found.

The switch statement above is the same as:

if (dayOfWk === "Sat") {  
  alert("very happy");  
} else if (dayOfWk === "Sun") {  
  alert("happy");  
} else if (dayOfWk === "Fri") {  
  alert("hapopy friday");  
} else {  
  alert("sad");  
}

default in the switch statement is the same as the else in the if statement.

While Loops

The JavaScript while loop is another kind of loop that we may use.

It lets us run a loop when a given condition is true .

For example, we can write:

let i = 0;  
while (i <= 3) {  
  console.log(i);  
  i++;  
}

In the loop above, when i is less than or equal to 3, then we run the loop.

Inside the loop body, we update i so that we work toward ending the loop.

We indent the loop block with 2 spaces for easy typing and readability.

Conclusion

JavaScript has a while loop to let us repeatedly run code.

Also, we should use local variables and avoid global variables.

switch statements lets us run code given some value of a variable.