Categories
Top React Libraries

Top React Libraries — Date Picker, Rich Text Editor, and Pagination

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

rc-calendar is a date picker library.

To install it, we run:

npm i rc-calendar

Then we can use it by writing:

import React from "react";
import Calendar from "rc-calendar";
import "rc-calendar/assets/index.css";

export default class App extends React.Component {
  state = {
    mode: "date",
    rangeStartMode: "date",
    rangeEndMode: "date"
  };

  handlePanelChange = (...args) => {
    console.log("on panel change", ...args);
  };

  render() {
    return (
      <div style={{ zIndex: 1000, position: "relative" }}>
        <Calendar
          mode={this.state.mode}
          onPanelChange={this.handlePanelChange}
        />
      </div>
    );
  }
}

We use the Calendar component to add a date picker.

The mode can also be 'time', 'decade', 'month' or 'year' to let us pick the month or year to let us select those.

Also, we can use the RangeCalendar component to let us select a date range:

import React from "react";
import RangeCalendar from "rc-calendar/lib/RangeCalendar";
import "rc-calendar/assets/index.css";

export default class App extends React.Component {
  state = {
    mode: "date",
    rangeStartMode: "date",
    rangeEndMode: "date"
  };

  handleRangePanelChange = (...args) => {
    console.log("on panel change", ...args);
  };

  render() {
    return (
      <div style={{ zIndex: 1000, position: "relative" }}>
        <RangeCalendar
          mode={[this.state.rangeStartMode, this.state.rangeEndMode]}
          onPanelChange={this.handleRangePanelChange}
        />
      </div>
    );
  }
}

We switched to the RangeCalendar component to get a date range picker.

mode is an array with the mode for picking the start and end range.

The options for those are the same as the Calendar .

There’re many other choices for configuring the calendar.

We can change styles, set the locale, render the date our way, and more.

react-paginate

We can use the react-paginate package to let us add a pagination links container in our app.

To install it, we can run:

npm i react-paginate

Then we can use it by writing:

import React from "react";
import ReactPaginate from "react-paginate";

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [],
      offset: 0
    };
  }

  componentDidMount() {}

  handlePageClick = data => {
    let selected = data.selected;
    let offset = Math.ceil(selected * this.props.perPage);

    this.setState({ offset });
  };

  render() {
    return (
      <div className="commentBox">
        <ReactPaginate
          previousLabel={"previous"}
          nextLabel={"next"}
          breakLabel={"..."}
          breakClassName={"break"}
          pageCount={this.state.pageCount}
          marginPagesDisplayed={2}
          pageRangeDisplayed={5}
          onPageChange={this.handlePageClick}
          containerClassName={"pagination"}
          subContainerClassName={"pages pagination"}
          activeClassName={"active"}
        />
      </div>
    );
  }
}

We have the ReactPagination component to display a pagination bar with some props.

previousLabel is the text for the previous page link.

nextLabel is the text for the next page link.

breakLabel is the text for the break to skip page numbers.

breakClassName is the class name for the break.

pageCount is the prop for the page count.

marginPagesDisplayed is the number of pages to display for margins.

pageRangeDisplayed is the range of pages to display.

onPageChange is a function we run when we click on a page link.

containerClassName is the class name for the container.

subContainerClassName is the class name for the child container.

activeClassName is the class for the active link.

It comes with no styles, so we can add the styles we want to style them our way.

React-Quill

React-Quill is an easy to use text editor package for React apps.

To install it, we run:

npm i react-quill

Then we can use it by writing:

import React from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { text: "" };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(value) {
    this.setState({ text: value });
  }

  render() {
    return <ReactQuill value={this.state.text} onChange={this.handleChange} />;
  }
}

The ReactQuill component is used to add the rich text editor.

It takes a value prop that’s set to the text state.

onChange updates the state with the inputted value with the handleChange method.

We also need the CSS to display the text editor properly.

It supports all the things that a normal text editor has include bolding, italics, underline, lists, links, and more.

The toolbar and editing area can be customized.

Conclusion

The rc-calendar can be used to add a date or time pickers.

react-paginate lets us add pagination links to our app.

And React-Quill is a rich text editor made to React with various customization choices.

Categories
Top React Libraries

Top React Libraries — Forms and Sizes

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 Final Form

React Final Form is a package that lets us create forms with data handling with ease.

We can also use it to add our own validation logic.

To install it, we run:

npm i react-final-form

Then we can use it by writing:

import React from "react";
import { Form, Field } from "react-final-form";

export default function App() {
  const onSubmit = values => {
    window.alert(JSON.stringify(values, 0, 2));
  };

return (
    <div className="app">
      <Form
        onSubmit={onSubmit}
        validate={values => {
          const errors = {};
          if (!values.username) {
            errors.username = "Username is required";
          }
          if (!values.password) {
            errors.password = "Password is required";
          }
          if (!values.confirm) {
            errors.confirm = "Confirm password is required";
          } else if (values.confirm !== values.password) {
            errors.confirm = "Passwords must match";
          }
          return errors;
        }}
        render={({ handleSubmit, form, submitting, pristine, values }) => (
          <form onSubmit={handleSubmit}>
            <Field name="username">
              {({ input, meta }) => (
                <div>
                  <label>Username</label>
                  <input {...input} type="text" placeholder="Username" />
                  {meta.error && meta.touched && <span>{meta.error}</span>}
                </div>
              )}
            </Field>
            <Field name="password">
              {({ input, meta }) => (
                <div>
                  <label>Password</label>
                  <input {...input} type="password" placeholder="Password" />
                  {meta.error && meta.touched && <span>{meta.error}</span>}
                </div>
              )}
            </Field>
            <Field name="confirm">
              {({ input, meta }) => (
                <div>
                  <label>Confirm</label>
                  <input {...input} type="password" placeholder="Confirm" />
                  {meta.error && meta.touched && <span>{meta.error}</span>}
                </div>
              )}
            </Field>
            <div className="buttons">
              <button type="submit" disabled={submitting}>
                Submit
              </button>
              <button
                type="button"
                onClick={form.reset}
                disabled={submitting || pristine}
              >
                Reset
              </button>
            </div>
          </form>
        )}
      />
    </div>
  );
}

We use the provided Form component with the onSubmit prop that takes the entered values.

validate is our validation function.

It takes the entered values as the parameter and we can check for the validity of the inputted values inside.

It returns an object with the errors.

Then we have a render prop with the form we render.

The handleSubmit function is passed to the onSubmit prop.

input has the props for the input.

meta has the form metadata like errors and its touched state.

submitting is the status when of submission.

pristine indicates whether it’s been interacted with or not.

The Field component surrounds each field and provide us with all those properties.

We can do many things with this library.

react-resize-detector

We can use the react-resize-detector package to watch for element resizing.

To install it, we run:

npm i react-resize-detector

Then we can use the provided ReactResizeDetector component to watch for width and height changes of the viewport:

import React from "react";
import ReactResizeDetector from "react-resize-detector";

export default function App() {
  return (
    <div className="app">
      <ReactResizeDetector handleWidth handleHeight>
        {({ width, height }) => <div>{`${width}x${height}`}</div>}
      </ReactResizeDetector>
    </div>
  );
}

We use the ReactResizeDetector component with the handleWidth and handleHeight to watch for width and height changes.

Also, we can use the withResizeDetector higher order component to let us create components with the width and height props:

import React from "react";
import { withResizeDetector } from "react-resize-detector";

const Comp = withResizeDetector(({ width, height }) => (
  <div>{`${width}x${height}`}</div>
));

export default function App() {
  return (
    <div className="app">
      <Comp />
    </div>
  );
}

We passed in a component to the withResizeDetector higher order component to watch for the width and height props.

This way, we get the width and height props in the component.

We can also throttle or denounce the refresh of the height and width.

Conclusion

The React Final Form library lets us create forms with validation.

react-resize-detector is a library to let us watch for the change in the width and height of the viewport.

Categories
Top React Libraries

Top React Libraries — Forms, Lazy Loading, and Animations

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

We can use the rc-form package to help us with handling form inputs.

To install it, we run:

npm i rc-form

Then we can use it by writing:

import React from "react";
import { createForm, formShape } from "rc-form";

class App extends React.Component {
  static propTypes = {
    form: formShape
  };

  submit = () => {
    this.props.form.validateFields((error, value) => {
      console.log(error, value);
    });
  };

  render() {
    let errors;
    const { getFieldProps, getFieldError } = this.props.form;
    return (
      <div>
        <input {...getFieldProps("normal")} placeholder="first name" />
        <input
          placeholder="last name"
          {...getFieldProps("required", {
            onChange() {},
            rules: [{ required: true }]
          })}
        />
        {(errors = getFieldError("required")) ? errors.join(",") : null}
        <button onClick={this.submit}>submit</button>
      </div>
    );
  }
}

export default createForm()(App);

We have 2 input fields with the props that are generated from the rc-form package passed into them.

Also, we specify the prop types for the forms prop to have the FormShape structure.

The rules are passed into the input with the getFieldProps function.

The required attribute is added with an object to specify the actual rule.

The errors come from the getFieldError function.

The submit method is called when we click on the submit button.

We get the form prop when we pass in our component to the createForm higher-order function.

react-lazyload

The react-lazyload package lets us add lazy loading content to our app.

This means that they only show when they’re on the screen.

To install it, we can run:

npm i react-lazyload

Then we can use it by writing:

import React from "react";
import LazyLoad from "react-lazyload";

export default function App() {
  return (
    <div className="list">
      <LazyLoad height={200}>
        <img src="http://placekitten.com/200/200" alt="cat" />
      </LazyLoad>
      <LazyLoad height={200} once>
        <img src="http://placekitten.com/200/200" alt="cat" />
      </LazyLoad>
      <LazyLoad height={200} offset={100}>
        <img src="http://placekitten.com/200/200" alt="cat" />
      </LazyLoad>
      <LazyLoad>
        <img src="http://placekitten.com/200/200" alt="cat" />
      </LazyLoad>
    </div>
  );
}

We just use the LazyLoad component and put whatever we want top lazy load inside.

The height of the content is set with the height prop.

once means that once it’s loaded, it won’t be managed by the LazyLoad component.

offset means the component will be loaded when it’s top edge is 100px from the viewport.

react-smooth

react-smooth is an animation library that we can use in a React app.

To install it, we run:

npm i react-smooth

Then we can use the Animate component by writing:

import React from "react";
import Animate from "react-smooth";

export default function App() {
  return (
    <div className="app">
      <Animate to="0" from="1" attributeName="opacity">
        <div>hello</div>
      </Animate>
    </div>
  );
}

We specify the to and from prop to specify the animation.

attributeName has the CSS property that will change with the animation.

Also, we can specify each step individually.

For example, we can write:

import React from "react";
import Animate from "react-smooth";

const steps = [
  {
    style: {
      opacity: 0
    },
    duration: 400
  },
  {
    style: {
      opacity: 1,
      transform: "translate(0, 0)"
    },
    duration: 2000
  },
  {
    style: {
      transform: "translate(300px, 300px)"
    },
    duration: 1200
  }
];

export default function App() {
  return (
    <div className="app">
      <Animate steps={steps}>
        <div>hello</div>
      </Animate>
    </div>
  );
}

to specify the steps of the animation un the steps array.

We specify the CSS properties to change and the values to change them to in the style property.

duration is the length of each step.

We pass the array into the steps prop to do animation with the given steps.

Now we get some opacity changes and translation with these array entries.

Also, we can specify the CSS property to change and easing.

Along with that, the code between the tags can be changed to a function with the style value we can use:

import React from "react";
import Animate from "react-smooth";

export default function App() {
  return (
    <div className="app">
      <Animate from={{ opacity: 0 }} to={{ opacity: 1 }} easing="ease-in">
        {({ opacity }) => <div style={{ opacity }}>hello</div>}
      </Animate>
    </div>
  );
}

from and to have the style at the beginning or end of the animation.

easing has the easing function to use with the animation.

Then we get the styles in the parameter of the function and use that in the style prop.

Conclusion

rc-form lets us build forms with data handling with less code.

react-lazyload lets us do lazy loading in our app.

react-smooth lets us create animations in our app.

Categories
Top React Libraries

Top React Libraries — Formatting Numbers and Infinite Scrolling

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-number-format

The react-number-format package lets us format numbers our way.

To install it, we run:

npm i react-number-format

Then we can use the NumberFormat component to display numbers formatted our way.

For example, we can write:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat
        value={585950}
        displayType={"text"}
        thousandSeparator={true}
        prefix={"$"}
      />
    </div>
  );
}

value has the value we want to format.

displayType is how we want to display the number.

thousandSeparator indicates that we want a separator.

prefix has the symbol that comes before the formatted number.

We can also add our own custom render function with the renderText prop:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat
        value={57595995}
        displayType={"text"}
        thousandSeparator={true}
        prefix={"$"}
        renderText={value => <div>{value}</div>}
      />
    </div>
  );
}

And we can enter our own format string:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat
        value={4111111111111111}
        displayType={"text"}
        format="#### #### #### ####"
      />
    </div>
  );
}

If we don’t have the displayType set to 'text' , then it’ll be displayed as an input:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat format="#### #### #### ####" />
    </div>
  );
}

We also have the format prop to specify how to format the number.

We can also add a character for the mask with the mask prop:

import React from "react";
import NumberFormat from "react-number-format";

export default function App() {
  return (
    <div className="App">
      <NumberFormat format="#### #### #### ####" mask="_" />
    </div>
  );
}

This lets us show the hints with the _ character.

We can do a lot more with it, like manipulating the element itself and add custom inputs.

React Infinite Scroller

React Infinite Scroller is an infinite scrolling component for our React app.

To install it, we can run:

npm i react-infinite-scroller

Then we can use it by writing:

import React from "react";
import InfiniteScroll from "react-infinite-scroller";

export default function App() {
  const [arr, setArr] = React.useState(
    Array(50)
      .fill()
      .map((_, i) => i)
  );
  return (
    <div className="App">
      <InfiniteScroll
        pageStart={0}
        loadMore={() =>
          setArr(arr => [
            ...arr,
            ...Array(50)
              .fill()
              .map((_, i) => i)
          ])
        }
        hasMore
        loader={
          <div className="loader" key={0}>
            Loading ...
          </div>
        }
      >
        {arr.map(a => (
          <p>{a}</p>
        ))}
      </InfiniteScroll>
    </div>
  );
}

We use the InfiniteScroll component with the loadMore prop to load more data when we reach the bottom of the page.

The loader prop has the component to show when data is loading.

pageStart has the starting page to load.

hasMore indicates whether we have more items to load.

In between the tags, we show the items with the code.

Also, we can set the useWindow prop to false to listen to DOM scroll events.

For example, we can write:

import React from "react";
import InfiniteScroll from "react-infinite-scroller";

export default function App() {
  const [arr, setArr] = React.useState(
    Array(50)
      .fill()
      .map((_, i) => i)
  );
  return (
    <div className="App">
      <div style={{ height: 300, overflow: "auto" }}>
        <InfiniteScroll
          pageStart={0}
          loadMore={() =>
            setArr(arr => [
              ...arr,
              ...Array(50)
                .fill()
                .map((_, i) => i)
            ])
          }
          hasMore
          useWindow={false}
          loader={
            <div className="loader" key={0}>
              Loading ...
            </div>
          }
        >
          {arr.map(a => (
            <p>{a}</p>
          ))}
        </InfiniteScroll>
      </div>
    </div>
  );
}

We have a div that’s 300px tall.

Also, we set the overflow to 'auto' so that the div has a scrollbar when the items overflow the div.

Then we have the InfiniteScroll component to display the items.

useWindow is set to false so that we watch if we scrolled to the bottom of the div instead of the window.

The rest of the code is the same.

Conclusion

react-number-format lets us format numbers and display them as text or in an input box.

React Infinite Scroller is an easy to use infinite scroll package.

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.