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.

Categories
Top React Libraries

Top React Libraries — Table, CSS, and Sortable List

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

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

To install it, we run:

npm i react-table

Then we can use it by writing:

import React from "react";
import { useTable } from "react-table";

const tableData = [
  { firstName: "james", lastName: "smith", age: 20 },
  { firstName: "may", lastName: "jones", age: 20 },
  { firstName: "alex", lastName: "smith", age: 20 }
];

function Table({ columns, data }) {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function App() {
  const columns = React.useMemo(
    () => [
      {
        Header: "Name",
        columns: [
          {
            Header: "First Name",
            accessor: "firstName"
          },
          {
            Header: "Last Name",
            accessor: "lastName"
          },
          {
            Header: "Age",
            accessor: "age"
          }
        ]
      }
    ],
    []
  );

  const data = React.useMemo(() => tableData, []);

  return (
    <>
      <Table columns={columns} data={data} />
    </>
  );
}

export default App;

We have an array with some data that we want to display in a table.

Then we create a Table component to display the data.

The component has the columns and data props.

We use that with the useTable hook to get more data needed to display the table.

Then we have the table component which has the getTableProps call to pass the props to the table.

headerGroups have the headers.

We call getHeaderGroupProps to pass the props to the tr.

tbody has the body and we use getTableBodyProps to get the props and pass them into there.

tr has the rows created from the prepareRow function.

We call the row.cells.map method to map them to cells.

The columns are defined in App .

We have the columns function of the Header and columns properties.

Header has the header to display.

accessor has the property name for from the tableData array entry we want to get and render.

Then we pass in the columns and data props to the Table component.

useMemo caches the data so that it’s only reloaded when it changes.

It has many other features like footers, sorting, filtering, and pagination.

ReactCSS

The ReactCSS package lets add inline styles with JavaScript.

It supports React. React Native, auto prefixing, hover, pseudoelements, and media queries.

To install it, we run:

npm i reactcss

Then we can use it by writing:

import React from "react";
import reactCSS from "reactcss";

const styles = reactCSS({
  default: {
    card: {
      background: "green",
      boxShadow: "0 2px 4px rgba(0,0,0,.15)",
      color: "white"
    }
  }
});

function App() {
  return (
    <>
      <div style={styles.card}>hello</div>
    </>
  );
}

export default App;

We created the styles with the reactCSS function.

The card property is an object with the styles.

We pass that into our div with the styles.card property.

Now we get a green background with a box shadow and the text color is white.

react-sortable-hoc

react-sortable-hoc is a package that lets us create sortable lists.

To install it, we can run:

npm i react-sortable-hoc

Then we use it 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>
  );
});

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

SortableItem is a component with the sortable item.

We can drag them to sort them.

SortableList has our list with the SortableItems .

We just render them with map .

Then we have our App component with the items state with the items.

Also, we have the onSortEnd method to do the sorting with the arrayMove function.

It’s a helper that lets us change the position of the items without writing code to do it ourselves.

Now we get a list where we can drag items to move them.

Conclusion

react-table lets us create a table with ease.

ReactCSS create the CSS for us to use in our app.

react-sortable-hoc helps us create a sortable list easily.