Categories
Top React Libraries

Top React Libraries — Event Listeners, Text Editors, and Progress Spinners

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-event-listener

We can use the react-event-listener package to add event listeners for various events emitted by the document or window.

To install it, we can run:

npm i react-event-listener

Then we can use it by writing:

import React from "react";
import EventListener, { withOptions } from "react-event-listener";

export default class App extends React.Component {
  handleResize = () => {
    console.log("resize");
  };

  handleScroll = () => {
    console.log("scroll");
  };

  handleMouseMove = () => {
    console.log("mousemove");
  };

  render() {
    return (
      <div>
        <EventListener
          target="window"
          onResize={this.handleResize}
          onScroll={withOptions(this.handleScroll, {
            passive: true,
            capture: false
          })}
        />
        <EventListener
          target={document}
          onMouseMoveCapture={this.handleMouseMove}
        />
      </div>
    );
  }
}

We use the EventListener component to listen to the events we want.

The target is the target element to listen to.

onResize lets us attach a resize event listener for the target element.

onScroll lets us attach an event listener for the scrolling to the target.

We can add some options with the withOptions function.

It lets us change how to attach the listener. We disable event capturing with capture set to false .

passive means preventDefault isn’t called in the handler.

We have a 2nd listener to listen to events emitted by document .

We have the onMouseMoveCapture prop to listen to mouse move events.

slate-react

slate-react lets us add a text editor to our React app

To install it, we run:

npm i slate-react

Then to install the editor, we write:

import React, { useState, useMemo } from "react";
import { createEditor } from "slate";
import { Slate, Editable, withReact } from "slate-react";
import { withHistory } from "slate-history";

const App = () => {
  const [value, setValue] = useState(initialValue);
  const editor = useMemo(() => withHistory(withReact(createEditor())), []);
  return (
    <Slate editor={editor} value={value} onChange={value => setValue(value)}>
      <Editable placeholder="Enter some plain text..." />
    </Slate>
  );
};

const initialValue = [
  {
    children: [{ text: "hello world" }]
  }
];

export default App;

We use the Slate component to add the editor.

It’s a plain text editor that has no options.

editor has the slate editor instance.

value is the value entered.

onChange updates the value state.

Editable has the text editor with the placeholder having the placeholder.

The initialValue has the initial value we use for value .

We can add other kinds of editors, including rich text editors, Markdown editors, and more.

It comes with no styles for anything, so we’ve to add them ourselves.

rc-progress

The rc-progress package lets us add progress spinners or bars.

To install it, we run:

npm i rc-progress

Then we can use it by writing:

import React from "react";
import { Line, Circle } from "rc-progress";

const App = () => {
  return (
    <>
      <Line percent="10" strokeWidth="4" strokeColor="green" />
      <Circle percent="10" strokeWidth="4" strokeColor="green" />
    </>
  );
};

export default App;

We used the Line and Circle from the package with some props.

strokeColor has the color for the filled part.

strokeWidth has the width of the filled part.

percent has the percentage complete.

We can change the class names, styles, and gaps for the components.

Conclusion

react-event-listener lets us add event listeners for window and document.

slate-react is a text editor component that comes with no styles.

rc-progress is the progress bar or spinner for us to use.

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.