Categories
Top React Libraries

Top React Libraries — Virtual Scrolling, Carousels, and Icons

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

The react-virtualized package lets us display a virtualized list.

To install it, we run:

npm i react-virtualized

Then we can use it by writing:

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

const list = Array(1000)
  .fill()
  .map((_, i) => i);

function rowRenderer({ key, index, isScrolling, isVisible, style }) {
  return (
    <div key={key} style={style}>
      {list[index]}
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <List
        width={300}
        height={300}
        rowCount={list.length}
        rowHeight={20}
        rowRenderer={rowRenderer}
      />
    </div>
  );
}

We have the rowRenderer to display the list items.

It takes the following props.

key is the unique key in the array of rows.

index is the index of the row in the collection.

isScrolling is the list that’s currently being scrolled.

isVisible indicates whether the row is visible or not.

sytle is style object to be applied to position the row.

We can also use it to display a grid.

For example, we can write:

import React from "react";
import { Grid } from "react-virtualized";
import * as _ from "lodash";

const list = _.chunk(
  Array(1000)
    .fill()
    .map((_, i) => i),
  3
);

function cellRenderer({ columnIndex, key, rowIndex, style }) {
  return (
    <div key={key} style={style}>
      {list[rowIndex][columnIndex]}
    </div>
  );
}

export default function App() {
  return (
    <div className="App">
      <Grid
        cellRenderer={cellRenderer}
        columnCount={list[0].length}
        columnWidth={100}
        height={300}
        rowCount={list.length}
        rowHeight={30}
        width={300}
      />
    </div>
  );
}

We created a nested array with 3 items in each entry with the Lodash chunk method.

Then we created the cellRenderer to render the cells.

columnIndex has the index of the column.

key has the unique key of the entry.

rowIndex has the row index of the entry.

style has the styles to position the item.

Then in App , we use the Grid component that uses the cellRenderer and pass in the row and column counts.

The heights and width are also set.

This package also comes with components for tables and masonry grid.

react-icons

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

To install it, we can run:

npm i react-icons

Then we can import the icon and use it:

import React from "react";
import { FaBeer } from "react-icons/fa";

export default function App() {
  return (
    <div className="App">
      <h1>
        time for a <FaBeer />
      </h1>
    </div>
  );
}

It comes with icons for many libraries, including Bootstrap, Font Awesome, Github, and much more.

react-slick

The react-slick package lets us add a carousel to our React app.

To install it, we can run:

npm i react-slick slick-carousel

Then we can use it by writing:

import React from "react";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import Slider from "react-slick";

const settings = {
  dots: true,
  infinite: true,
  speed: 500,
  slidesToShow: 1,
  slidesToScroll: 1
};

export default function App() {
  return (
    <div className="App">
      <Slider {...settings}>
        <div>
          <h3>1</h3>
        </div>
        <div>
          <h3>2</h3>
        </div>
        <div>
          <h3>3</h3>
        </div>
        <div>
          <h3>4</h3>
        </div>
        <div>
          <h3>5</h3>
        </div>
        <div>
          <h3>6</h3>
        </div>
      </Slider>
    </div>
  );
}

We used the Slider component to add some slides to our app.

The settings object has the props that we pass in to configure the carousel.

dots lets us choose whether to show the dots for navigation.

infinite sets whether it goes back to the first slide after the last one is reached.

speed is the speed of the slide.

slidesToShow is the number of slides to show at once.

slidesToScroll is the number of slides that we scroll through when we navigate.

There are many other props for styling the dots, slides, and many other parts of the carousel.

Conclusion

The react-virtualized package lets us create a virtual scroll list, table, or masonry grid.

react-icons lets us add icons from many sources.

react-slick is a library to let us add carousels to our app.

Categories
Top React Libraries

Top React Libraries — Date Picker, Input Mask, and Tables

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

The react-datetime package lets us add a date or time picker to our app.

To install it, we run:

npm i react-datetime moment

Then we can use it by writing:

import React from "react";
const Datetime = require("react-datetime");

export default function App() {
  return (
    <div>
      <Datetime />
    </div>
  );
}

This will show a date picker that we can select a date from.

We can also customize the appearance of the date picker by writing:

import React from "react";
const Datetime = require("react-datetime");

const renderDay = (props, currentDate, selectedDate) => {
  const date = currentDate.date();
  return <td {...props}>{date < 10 ? "0" + date : date}</td>;
};

const renderMonth = (props, month, year, selectedDate) => {
  return <td {...props}>{month}</td>;
};

const renderYear = (props, year, selectedDate) => {
  return <td {...props}>{year % 100}</td>;
};

export default function App() {
  return (
    <div>
      <Datetime
        renderDay={renderDay}
        renderMonth={renderMonth}
        renderYear={renderYear}
      />
    </div>
  );
}

We added 3 functions to render the day, month, and year differently than the default way.

We can change the date format, time format, locale, value, and more.

Also, we can make it a controlled component by writing:

import React from "react";
const Datetime = require("react-datetime");

export default function App() {
  const [value, setValue] = React.useState(new Date());

  return (
    <div>
      <Datetime value={value} onChange={val => setValue(val.toDate())} />
    </div>
  );
}

We pass in the value to get the value and onChange to set it.

val is a moment object, so we’ve to convert to a Date instance with toDate .

rc-table

rc-table is a package that lets us add tables easily in our React app.

To install it, we run:

npm i rc-table

Then we write:

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: "Operations",
    dataIndex: "",
    key: "operations",
    render: () => <a href="#">Delete</a>
  }
];

const data = [
  { name: "james", age: 22, address: "some where", key: "1" },
  { name: "mary", age: 33, address: "some where", key: "2" }
];

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

to use it.

We have the columns defined in the columns array.

title has the headings.

dataIndex has the property key of the of the entry to display for that column.

key is the unique key of the column.

width has the column width in pixels.

render has the component to render.

data has the data, which is an array of objects.

In App , we use the provided Table component with the columns prop with the columns. data has the data to display.

react-input-mask

react-input-mask provides us with an easy to use input mask.

To install it, we run:

npm i react-input-mask

Then we can use it by writing:

import React from "react";
import InputMask from "react-input-mask";

export default function App() {
  return (
    <div>
      <InputMask mask="+49 999 999 9999" maskChar=" " />
    </div>
  );
}

We use the InputMask component to add the input.

mask has the pattern to restrict the input to.

maskChar is the character to cover the unfilled parts of the mask.

We can also change the characters for formatting in the mask.

Also, we can use it with Material UI.

We can also turn it to a controlled component with the value and onChange props:

import React from "react";
import InputMask from "react-input-mask";

export default function App() {
  const [value, setValue] = React.useState("");

  return (
    <div>
      <InputMask
        value={value}
        onChange={e => setValue(e.target.value)}
        mask="+49 999 999 9999"
        maskChar=" "
      />
    </div>
  );
}

We use the onChange callback to set the inputted value as the value of the value state.

And we pass the value state as the value of the value prop.

Conclusion

react-datetime is a date and time picker we can use in our React app.

rc-table is a table component.

react-input-mask is an input mask component.

Categories
Top React Libraries

Top React Libraries — Swipes and Collapse

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-swipeable-views

react-swipeable-views is an easy to use package to let us add swipes gesture handling to our React app.

To use it, we install it by running:

npm i react-swipeable-views

Then we can use it by writing:

import React from "react";
import SwipeableViews from "react-swipeable-views";

const styles = {
  slide: {
    padding: 15,
    minHeight: 100,
    color: "black"
  },
  slide1: {
    background: "lightgreen"
  },
  slide2: {
    background: "lightblue"
  },
  slide3: {
    background: "orange"
  }
};

export default function App() {
  return (
    <div>
      <SwipeableViews>
        <div style={Object.assign({}, styles.slide, styles.slide1)}>
          slide 1
        </div>
        <div style={Object.assign({}, styles.slide, styles.slide2)}>
          slide 2
        </div>
        <div style={Object.assign({}, styles.slide, styles.slide3)}>
          slide 3
        </div>
      </SwipeableViews>
    </div>
  );
}

We just import the SwipeableViews component.

Then we add divs to in between the tags to add slides.

It also has experimental support for React Native.

We can also add the resistance bound effect with the resistance prop:

import React from "react";
import SwipeableViews from "react-swipeable-views";

const styles = {
  slide: {
    padding: 15,
    minHeight: 100,
    color: "black"
  },
  slide1: {
    background: "lightgreen"
  },
  slide2: {
    background: "lightblue"
  },
  slide3: {
    background: "orange"
  }
};

export default function App() {
  return (
    <div>
      <SwipeableViews resistance>
        <div style={Object.assign({}, styles.slide, styles.slide1)}>
          slide 1
        </div>
        <div style={Object.assign({}, styles.slide, styles.slide2)}>
          slide 2
        </div>
        <div style={Object.assign({}, styles.slide, styles.slide3)}>
          slide 3
        </div>
      </SwipeableViews>
    </div>
  );
}

Also, we can put our slides in the VirtualizeSwipeableViews component if we have many slides to load.

This way, they’re only loaded when they’re shown:

import React from "react";
import SwipeableViews from "react-swipeable-views";
import { virtualize, bindKeyboard } from "react-swipeable-views-utils";
import { mod } from "react-swipeable-views-core";

const VirtualizeSwipeableViews = bindKeyboard(virtualize(SwipeableViews));

const styles = {
  slide: {
    padding: 15,
    minHeight: 100,
    color: "black"
  },
  slide1: {
    backgroundColor: "lightgreen"
  },
  slide2: {
    backgroundColor: "orange"
  },
  slide3: {
    backgroundColor: "pink"
  }
};

function slideRenderer(params) {
  const { index, key } = params;
  let style;

  switch (mod(index, 3)) {
    case 0:
      style = styles.slide1;
      break;

    case 1:
      style = styles.slide2;
      break;

    case 2:
      style = styles.slide3;
      break;

  default:
      break;
  }

  return (
    <div style={Object.assign({}, styles.slide, style)} key={key}>
      {`slide ${index + 1}`}
    </div>
  );
}

export default function App() {
  const [index, setIndex] = React.useState(0);

  const handleChangeIndex = i => {
    setIndex(i);
  };

  const handleClick = () => {
    setIndex(19);
  };
  return (
    <div>
      <VirtualizeSwipeableViews
        index={index}
        onChangeIndex={handleChangeIndex}
        slideRenderer={slideRenderer}
      />
      <br />
      <button onClick={handleClick}>go to slide 20</button>
    </div>
  );
}

We created the slideRendered component to render the slide.

And then we pass that into the slideRenderer prop.

The index prop has the index of the slide.

We can change that programmatically to jump to the slide we want.

rc-collapse

rc-collapse is a package that we can create collapse components with.

To install it, we run:

npm i rc-collapse

Then we can use it by writing:

import React from "react";
import "rc-collapse/assets/index.css";
import Collapse, { Panel } from "rc-collapse";

const getItems = () => {
  const items = Array(10)
    .fill()
    .map((_, i) => (
      <Panel
        header={`This is panel header`}
        key={i}
        extra={<span>Extra</span>}
        defaultActiveKey="1"
      >
        <p>Panel with extra</p>
      </Panel>
    ));

  return items;
};

export default function App() {
  const [activeKey, setActiveKey] = React.useState(0);

  const onChange = activeKey => {
    setActiveKey(activeKey);
  };

  return (
    <div style={{ margin: 20, width: 400 }}>
      <button onClick={() => setActiveKey(8)}>active header 7</button>
      <br />
      <Collapse accordion activeKey={activeKey} onChange={onChange}>
        {getItems()}
      </Collapse>
    </div>
  );
}

We have the getItems function to return an array of Collapse components, which has a heading, text on the right, and text in the panel.

The extra prop has the text on the right side of the header.

In App , we have the Collapse component with the activeKey prop.

This prop sets the active collapse item. The full panel will be displayed if it’s active.

We set it when we click on the button.

The onChange function changes the activeKey so that the correct item will be expanded.

Conclusion

react-swipeable-views lets us handle swiping of elements.

rc-collapse lets us add collapse component to our React app.

Categories
Top React Libraries

Top React Libraries — Text Boxes and Drag and Drop

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-textarea-autosize

We can use the react-textarea-autosize to add a text area that resizes automatically.

For example, we can run:

npm i react-textarea-autosize

to install it.

Then we can use it by writing:

import React from "react";
import TextareaAutosize from "react-textarea-autosize";

export default function App() {
  const [value, setValue] = React.useState("");
  return (
    <div>
      <TextareaAutosize
        rows={20}
        value={value}
        onChange={e => setValue(e.target.value)}
      />
    </div>
  );
}

We use the TextareaAutosize component that comes with the package.

It can be used as a controlled component as we did in the example.

We added the value prop to add the value and onChange to let us update the value state with it.

react-dnd

react-dnd is a library that lets us add drag and drop features to our React app.

To use it, we can install it by running:

yarn add react-dnd react-dnd-html5-backend

Then we can use it by writing the following code:

import React from "react";
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";

const Box = ({ name }) => {
  const [{ isDragging }, drag] = useDrag({
    item: { name, type: "box" },
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult();
      if (item && dropResult) {
        alert(`You dropped ${item.name} into ${dropResult.name}!`);
      }
    },
    collect: monitor => ({
      isDragging: monitor.isDragging()
    })
  });
  const opacity = isDragging ? 0.4 : 1;
  return (
    <div ref={drag} style={{ opacity }}>
      {name}
    </div>
  );
};

const Dustbin = () => {
  const [{ canDrop, isOver }, drop] = useDrop({
    accept: "box",
    drop: () => ({ name: "Dustbin" }),
    collect: monitor => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop()
    })
  });
  const isActive = canDrop && isOver;
  let backgroundColor = "#222";
  if (isActive) {
    backgroundColor = "yellow";
  } else if (canDrop) {
    backgroundColor = "green";
  }
  return (
    <div ref={drop} style={{ backgroundColor }}>
      {isActive ? "Release to drop" : "Drag a box here"}
    </div>
  );
};

export default function App() {
  return (
    <div>
      <DndProvider backend={HTML5Backend}>
        <Dustbin />
        <Box name="foo" />
        <Box name="bar" />
      </DndProvider>
    </div>
  );
}

We have the DndProvider that wraps around the components that can be dragged or we can drop stuff into.

The Dustbin component is where we can drop stuff into.

We watch for items that we’re dropping with the useDrop hook.

accept is the type of item that it accepts.

drop is the function that runs when something is dropped into it.

collect is a function that returns whether the item can be dropped or not.

We have the isActive variable which checks if the item can be dropped, which is done by checking the type .

isOver checks if the dropping is done.

Then we render the background and text according to that.

We created a draggable item by creating the Box component.

We used the useDrag hook to create a draggabkle component.

The name prop has the content of the draggable element.

We get the result of the dragging with the end callback in the useDrag hook.

collect has a function that runs to check if it’s being dragged.

Now we can drag the Box to the Dustbin and we’ll get an alert every time we do so.

React-Input-Autosize

We get an autoresize input box with the React-Input-Autoresize package.

To install it, we can run:

npm i react-input-autosize

Then we use it by writing:

import React from "react";
import AutosizeInput from "react-input-autosize";

export default function App() {
  const [value, setValue] = React.useState("example");
  return (
    <div>
      <AutosizeInput
        name="form-field"
        value={value}
        onChange={e => setValue(e.target.value)}
      />
    </div>
  );
}

We created a controlled text box that resizes according to the inputted value by setting the value prop with a state and the onChange with a function to change the state.

Conclusion

React-dnd is a useful drag and drop library that lets us do many things.

React-textarea-autoresize and React-input-autoresize are 2 popular resizable text boxes we can use to enter text.

Categories
Top React Libraries

Top React Libraries — Tooltip, Clipboard, Dates, and Portal

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

react-tooltip is an easy to use tooltip component.

To install it, we can run:

npm i react-tooltip

Then we can use it by writing:

import React from "react";
import ReactTooltip from "react-tooltip";

export default function App() {
  return (
    <>
      <p data-tip="hello world">Tooltip</p>
      <ReactTooltip />
    </>
  );
}

We add an element with the data-tip attribute with the value being the text that we want to display in the tooltip.

Then we add the ReactTooltip component.

This will display the text in the tooltip when we hover it.

We can change many other things like offsets, delays, borders, arrow colors, and much more.

react-copy-to-clipboard

react-copy-to-clipboard is a package that lets us copy things to the clipboard easier when the user does something our React app.

To install it, we can write:

npm i react-copy-to-clipboard

Then we can use it by writing:

import React from "react";
import { CopyToClipboard } from "react-copy-to-clipboard";

export default function App() {
  const [value, setValue] = React.useState("");
  const [copied, setCopied] = React.useState(false);
  return (
    <>
      <div>
        <input
          value={value}
          onChange={({ target: { value } }) => setValue(value)}
        />

        <CopyToClipboard text={value} onCopy={() => setCopied(true)}>
          <span>Copy to clipboard with span</span>
        </CopyToClipboard>

        <CopyToClipboard text={value} onCopy={() => setCopied(true)}>
          <button>Copy to clipboard with button</button>
        </CopyToClipboard>

{copied ? <span style={{ color: "red" }}>Copied.</span> : null}
      </div>
    </>
  );
}

We have the CopyToClipboard component which surrounds the component that we to let user use to copy content to the clipboard.

The text prop has the values that we want to let the user copy to the clipboard.

React-portal

React-portal is a package that lets us use the React portal feature easily.

It lets us render our component as a child of any element we want.

We can install it by running:

npm i react-portal

Then we can use it by writing:

import React from "react";
import { Portal } from "react-portal";

export default function App() {
  return (
    <>
      <Portal>This text is portaled at the end of document.body!</Portal>

      <Portal node={document && document.getElementById("foo")}>
        This text is portaled into foo
      </Portal>
    </>
  );
}

We use the Portal component to render our content in the location we want in the DOM.

If there’s node prop, then it’s rendered in the body.

Otherwise, it’s rendered in the element that we specified.

react-dates

react-dates is a date picker library for our React app.

To install it, we can run:

npm i react-dates

Then we can use it by writing:

import React from "react";
import { DateRangePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

export default function App() {
  const [startDate, setStartDate] = React.useState(null);
  const [endDate, setEndDate] = React.useState(null);
  const [focusedInput, setFocusedInput] = React.useState(null);
  return (
    <>
      <DateRangePicker
        startDateId="startDate"
        endDateId="endDate"
        startDate={startDate}
        endDate={endDate}
        onDatesChange={({ startDate, endDate }) => {
          setStartDate(startDate);
          setEndDate(endDate);
        }}
        focusedInput={focusedInput}
        onFocusChange={focusedInput => {
          setFocusedInput(focusedInput);
        }}
      />
    </>
  );
}

We have the startDateId to set the name of the start date field.

We do the same with the end date with the endDateId

startDate has the value of the start date.

endDate has the end date value.

onDatesChange has a function that updates the state of the start date.

focusedInput has the input that’s focused.

onFocusChange has the function to set which date input is focused.

We also have to import the initialize module and the CSS to make the pickers display properly.

Conclusion

react-tooltip lets us add a tooltip easily.

react-copy-to-clipboard lets us add a copy to clipboard feature in our React app.

React-portal has makes using the portal feature easy.

react-dates lets us add a start and end date picker.