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
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.

Categories
React

Add Animation to HTML Elements in a React App with React Motion

The react-motion library lets us add a component to add HTML elements in a React app.

In this article, we’ll look at how to use this to add animations to various HTML elements.

Installation

We can install the package by running:

npm install --save react-motion

Simple Animation

We can add simple animation by using the Motion component.

For instance, we can write:

import React from "react";
import { Motion, spring } from "react-motion";

export default function App() {
  return (
    <div className="App">
      <Motion defaultStyle={{ x: 0 }} style={{ x: spring(10) }}>
        {(value) => <div>{value.x}</div>}
      </Motion>
    </div>
  );
}

The defaultStyle has an object with the initial value.

style has the animation we want to run.

The x property will be animated from 0 to 10.

value has the objects with the x property, and x has numbers between 0 and 10.

Now we should see the number 10 displayed an animation is added.

StaggeredMotion

The StaggeredMotion component lets us animate a collection of items.

The collection must have a constant length.

For example, we can use it by writing:

import React from "react";
import { StaggeredMotion, spring } from "react-motion";

export default function App() {
  return (
    <div className="App">
      <StaggeredMotion
        defaultStyles={[{ h: 0 }, { h: 0 }, { h: 0 }]}
        styles={(prevInterpolatedStyles) =>
          prevInterpolatedStyles.map((_, i) => {
            return i === 0
              ? { h: spring(100) }
              : { h: spring(prevInterpolatedStyles[i - 1].h) };
          })
        }
      >
        {(interpolatingStyles) => (
          <div>
            {interpolatingStyles.map((style, i) => (
              <div key={i} style={{ border: "1px solid", height: style.h }} />
            ))}
          </div>
        )}
      </StaggeredMotion>
    </div>
  );
}

The defaultStyles has an array of styles with the initial styles, h is used to animate the heights.

The styles prop has the styles to map the initial styles to the end styles.

spring animated the height from 0 to 100px if it’s the first element.

Otherwise, we animate it to the height of the previous element.

Then in the child in between the tags, we set the height of the divs.

TransitionMotion

The TransitionMotion lets us do mounting and unmounting animation.

For example, we can write:

import React, { useEffect } from "react";
import { TransitionMotion, spring } from "react-motion";

export default function App() {
  const [items, setItems] = React.useState([
    { key: "a", size: 10 },
    { key: "b", size: 20 },
    { key: "c", size: 30 }
  ]);

useEffect(() => {
    setItems([
      { key: "a", size: 10 },
      { key: "b", size: 20 }
    ]);
  }, []);

const willLeave = () => {
    return { width: spring(0), height: spring(0) };
  };

  return (
    <div className="App">
      <TransitionMotion
        willLeave={willLeave}
        styles={items.map((item) => ({
          key: item.key,
          style: { width: item.size, height: item.size }
        }))}
      >
        {(interpolatedStyles) => (
          <div>
            {interpolatedStyles.map((config) => {
              return (
                <div
                  key={config.key}
                  style={{ ...config.style, border: "1px solid" }}
                />
              );
            })}
          </div>
        )}
      </TransitionMotion>
    </div>
  );
}

We set the items with an array with 3 entries.

They’re used to render 3 squares.

Then in the useEffect hook, we call setItems to set the items.

We removed the last entry, so we removed the shape.

willLeave is called to shrink the square to 0 to make it disappear.

The TransitionMotion component does the animation.

willLeave is run when the element is removed.

The function in between the tags with by mapping the interpolatedStyles into the divs we render.

The styles prop has the styles we display for each item.

It has the values of items and we map to the latest styles.

This way, we see the animation displayed.

Conclusion

React Motion lets us animate shapes easily by changing the styles from the initial ones to the latest ones with transition effects.

Categories
React

Add a Stacked Bar Chart Easily with the react-horizontal-stacked-bar-chart Library

The react-horizontal-stacked-bar-chart library lets us add a bar chart easily in our React app.

In this article, we’ll look at how to use it to add a stacked bar chart to our React app.

Installation

We can install the library by running:

npm i react-horizontal-stacked-bar-chart

Simple Chart

After we installed the package, we write:

import React from "react";
import HSBar from "react-horizontal-stacked-bar-chart";

export default function App() {
  return (
    <div className="App">
      <HSBar data={[{ value: 10 }, { value: 20 }]} />
    </div>
  );
}

to add 2 bars stacked together with the HSBar component.

There is nothing else displayed except the bars.

Complete Chart

To add a complete chart with the labels, we write:

import React from "react";
import HSBar from "react-horizontal-stacked-bar-chart";

export default function App() {
  return (
    <div className="App">
      <HSBar
        height={50}
        showTextIn
        showTextUp
        showTextDown
        outlineWidth={0.5}
        outlineColor="black"
        id="chart"
        fontColor="rgb(50,20,100)"
        data={[
          {
            name: "Owed",
            value: 80,
            description: "$80,00",
            color: "red"
          },
          {
            name: "Paid",
            value: 200,
            description: "$200,00",
            color: "lightgreen"
          }
        ]}
        onClick={(e) => console.log(e.bar)}
      />
    </div>
  );
}

The showTextIn prop shows text inside the bars.

showTextUp shows the label text above the bars.

showTextDown shows the label text below the bars.

outlineWidth has the width of the border.

outlineColor has the color of the border.

fontColor has the font color.

data has the data for the stacked bars.

The name has the name that is displayed in the labels.

value has the length of the bar.

description has the description shown before the name .

color has the color of the bar.

onClick is a function that’s called when the bar is clicked.

A single bar would be displayed with the bars with thedata array stacked together.

Conclusion

The react-horizontal-stacked-bar-chart library lets us add a stacked bar chart within a React app with a single bar.