Categories
Top React Libraries

Top React Libraries — Measurements, Charts, and Videos

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 Measure

React Measure is an easy to use library to let us get various dimensions of the screen.

To install it, we can run:

npm i react-measure

Then we can use it by writing:

import React from "react";
import { withContentRect } from "react-measure";

function App({ measureRef, measure, contentRect }) {
  return (
    <div>
      <div ref={measureRef}>
        hello world
        <pre>{JSON.stringify(contentRect, null, 2)}</pre>
      </div>
    </div>
  );
}

export default withContentRect("bounds")(App);

We get the measurements with the contentRect prop.

measureRef is passed into the element that we want to get the size of.

Then we can use the withContentRect higher-order component with it.

'bounds' means we get the dimensions of the bounds.

We can also use it to get the dimensions of the offsets, margins, and more.

ReactPlayer

ReactPlayer is a library that we can use to embed videos from various sources.

It supports embedding YouTube, Facebook, Twitch, SoundCloud, Streamable, Vimeo, Wistia, Mixcloud, and DailyMotion videos.

To install it, we run:

npm i react-player

Then we can use it by writing:

import React from "react";
import ReactPlayer from "react-player";

export default function App() {
  return (
    <div>
      <ReactPlayer url="https://www.youtube.com/watch?v=p-5FR1KNA2c" />
    </div>
  );
}

We just pass in the ReactPlayer component with the URL of the video set in the url prop.

In addition to this, we can change various options like looping, controls, width, height, other styles, a player icon, volume, and more.

They’re all available via props passed to ReactPlayer , so we can write:

import React from "react";
import ReactPlayer from "react-player";

export default function App() {
  return (
    <div>
      <ReactPlayer controls url="https://www.youtube.com/watch?v=p-5FR1KNA2c" />
    </div>
  );
}

to show the controls with the controls prop for example.

react-chartjs-2

react-chartjs-2 is a port of the Chart.js library for React.

It comes with various React components to let us add various kinds of graphs.

To install it, we run:

npm i react-chartjs-2 chart.js

Then we can use it by writing:

import React from "react";
import { Line } from "react-chartjs-2";

const data = {
  labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
  datasets: [
    {
      label: "apple",
      data: [33, 53, 85, 41, 44, 65],
      fill: true,
      backgroundColor: "red",
      borderColor: "darkred"
    },
    {
      label: "orange",
      data: [33, 25, 35, 51, 54, 76],
      fill: false,
      borderColor: "orange"
    }
  ]
};

export default function App() {
  return (
    <div>
      <Line data={data} height={300} options={{ maintainAspectRatio: false }} />
    </div>
  );
}

The data has the data that we pass into the data prop.

It includes the labels property with the x-axis labels.

datasets has the datasets for the lines.

label has the content for the legends.

data has the y coordinates for the points.

fill set to true means we have the color between the line and the x-axis.

backgroundColor is the color for the fill.

borderColor has the color for the line.

We pass in the whole object as the value of the data prop in the Line component.

Also, we set the height with the height prop.

options has extra options like whether to maintain aspect ratio.

Many other kinds of charts like bars, doughnuts, scatter charts and more are supported.

Conclusion

React Measure lets us get measurements of a given element.

ReactPlayer is a component that lets us embed videos from various sources.

react-chartjs-2 is a Chart.js port for React.

It can let us add many kinds of charts easily.

Categories
Top React Libraries

Top React Libraries — JSON, Visibility, and Datetime

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-json-view

react-json-view is library to let us render JSON with syntax highlighting on the screen.

To install it, we run:

npm i react-json-view

Then we can use it by writing:

import React from "react";
import ReactJson from "react-json-view";

const App = () => {
  return (
    <>
      <ReactJson src={{ foo: "bar", baz: 1 }} />
    </>
  );
};
export default App;

The ReactJson component lets us render JSON objects on the screen.

The src prop holds the JSON object to render.

Many options can be changed, including default value, styles, theme, icon styles, and more.

There’re also props for listening to add, edit, delete, select events, and more.

react-moment

react-moment is a useful library for letting us format dates.

To use it, we install it by running:

npm i react-moment moment

Then we can use it by writing:

import React from "react";
import Moment from "react-moment";

const dateToFormat = "2020-04-19T12:59-0500";

const App = () => {
  return (
    <>
      <Moment>{dateToFormat}</Moment>
    </>
  );
};
export default App;

The Moment component lets us format dates.

Wd can also pass in a Date instance:

import React from "react";
import Moment from "react-moment";

const dateToFormat = "2020-04-19T12:59-0500";

const App = () => {
  return (
    <>
      <Moment date={dateToFormat} />
    </>
  );
};
export default App;

We can set the interval so that the date updates at a given interval:

import React from "react";
import Moment from "react-moment";

const dateToFormat = "2020-04-19T12:59-0500";

const App = () => {
  return (
    <>
      <Moment interval={30000} date={dateToFormat} />
    </>
  );
};
export default App;

The interval value is in milliseconds.

The format can be changed with the format prop.

For example, we can write:

import React from "react";
import Moment from "react-moment";

const dateToFormat = "2020-04-19T12:59-0500";

const App = () => {
  return (
    <>
      <Moment format="YYYY/MM/DD" date={dateToFormat} />
    </>
  );
};
export default App;

to format the date into YYYY/MM/DD format.

Dates can also be parsed and rendered:

import React from "react";
import Moment from "react-moment";

const App = () => {
  return (
    <>
      <Moment parse="YYYY-MM-DD HH:mm">2020-04-19 12:59</Moment>
    </>
  );
};
export default App;

We pass in the date format string to the parse prop to parse it.

Also, we can get relative time with the fromNow and ago props:

import React from "react";
import Moment from "react-moment";

const App = () => {
  return (
    <>
      <Moment fromNow ago>
        2020-04-19 12:59
      </Moment>{" "}
    </>
  );
};
export default App;

fromNow renders the relative time and ago removes the suffix from it.

We can do many more things with it like changing time zones, elements to render the string in, localization, and more.

React Visibility Sensor

The React Visibility Sensor component lets us detect when something goes out of the window viewport.

To install it, we run:

npm i react-visibility-sensor

Then we can write:

import React from "react";
import VisibilitySensor from "react-visibility-sensor";

function onChange(isVisible) {
  console.log("Element is now %s", isVisible ? "visible" : "hidden");
}

const App = () => {
  return (
    <>
      {Array(100)
        .fill()
        .map((_, i) => (
          <VisibilitySensor onChange={onChange}>
            <div>item {i + 1}</div>
          </VisibilitySensor>
        ))}
    </>
  );
};
export default App;

to detect the visibility of the elements inside the VisibilitySensor component in the viewport.

The onChange function takes an isVisible parameter to let us know whether it’s visible or not.

We can change how it checks for visibility, including adding delays, throttling, offset, checking visibility for non-scrolling events, and more.

Conclusion

react-json-view renders JSON in our app.

react-moment lets us format time in our React app with moment.js.

React Visibility Sensor lets us watch for the visibility of elements.

Categories
Top React Libraries

Top React Libraries — Forms, Sliders, 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.

Formik

To make form handling a lot easier, we can use a form library to do the processing.

Formik is one library we can use.

To install it, we run:

npm i formik

Then we can use it by writing:

import React from "react";
import { Formik } from "formik";

export default function App() {
  return (
    <div className="App">
      <Formik
        initialValues={{ email: "", name: "" }}
        validate={values => {
          const errors = {};
          if (!values.email) {
            errors.email = "Required";
          } else if (
            !/^\[A-Z0-9.\_%+-]+@\[A-Z0-9.-\]+\.\[A-Z]{2,}$/i.test(values.email)
          ) {
            errors.email = "Invalid email address";
          }
          return errors;
        }}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 900);
        }}
      >
        {({
          values,
          errors,
          touched,
          handleChange,
          handleBlur,
          handleSubmit,
          isSubmitting
        }) => (
          <form onSubmit={handleSubmit}>
            <input
              type="email"
              name="email"
              placeholder="email"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.email}
            />
            {errors.email && touched.email && errors.email}
            <input
              type="name"
              name="name"
              placeholder="name"
              onChange={handleChange}
              onBlur={handleBlur}
              value={values.name}
            />
            {errors.name && touched.name && errors.name}
            <button type="submit" disabled={isSubmitting}>
              Submit
            </button>
          </form>
        )}
      </Formik>
    </div>
  );
}

We use the Formik component that comes with the package.

The initialValues prop has the initial values for our fields.

The validate prop has our validation function.

We can get all the values , check them, and return any errors in an object if there are any.

The onSubmit prop takes an on submit handler which has the entered values.

And then we can do something to them to submit them.

It’s only run when all the values are valid.

Between the tags, we have a function with an object with many properties as the parameter.

values has the values.

errors has form validation errors.

touched indicates which field is touched.

handleChange has the input field change handler function.

handleBlur has the handler for handling form fields that go out of focus.

isSubmitting has the boolean for indicating whether it’s submitted.

We pass them all into various parts of the form.

handleChange , handleBlur , and values are passed into the form field.

errors are outside the field.

isSubmitting is passed into the button to disable if it’s being submitted.

rc-slider

We can use the rc-slider package to add a slider component to our React app.

To install it, we can run:

npm i rc-slider

Then we can use the Slider and Range component to add the slider input to our app:

import React from "react";
import Slider, { Range } from "rc-slider";
import "rc-slider/assets/index.css";

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

We can make it a controlled component by adding the value , onChange , and onAfterChange props:

import React from "react";
import Slider from "rc-slider";
import "rc-slider/assets/index.css";

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

  const onSliderChange = value => {
    setValue(value);
  };

  const onAfterChange = value => {
    console.log(value);
  };

  return (
    <div className="App">
      <Slider
        value={value}
        onChange={onSliderChange}
        onAfterChange={onAfterChange}
      />
    </div>
  );
}

onChange will update the selected value as the value of value state.

value has the value that’s selected.

We can customize the steps, marks, handle styles, and more.

rc-animate

We can use the rc-animate to animate React components.

To install it, we run:

npm i rc-animate

Then we can write:

import React from "react";
import Animate from "rc-animate";

const Div = props => {
  const { style, show, ...restProps } = props;
  const newStyle = { ...style, display: show ? "" : "none" };
  return <div {...restProps} style={newStyle} />;
};

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      enter: true
    };
  }

  toggle(field) {
    this.setState({
      \[field\]: !this.state\[field\]
    });
  }

  render() {
    const style = {
      width: "200px",
      height: "200px",
      backgroundColor: "red"
    };
    return (
      <div>
        <label>
          <input
            type="checkbox"
            onChange={this.toggle.bind(this, "enter")}
            checked={this.state.enter}
          />
          show
        </label>
        <br />
        <br />
        <Animate component="" showProp="show" transitionName="fade">
          <Div show={this.state.enter} style={style} />
        </Animate>
      </div>
    );
  }
}

to use it.

We create the Div component to get the styles other props.

Then we use the Animate component to add the transitionName prop to add the fade animation.

We also have a checkbox to toggle the div.

Conclusion

Formik is a useful form handling component.

rc-slider helps us add a slider easily.

rc-animate lets us add animation to our React app.

Categories
Top React Libraries

Top React Libraries — Focus Lock, Toasts, Text Editor, and Day Picker

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-focus-lock

The react-focus-lock package lets us keep the focus of an element.

To install it, we can run:

npm i react-focus-lock

Then we can use it by writing:

import React from "react";
import FocusLock from "react-focus-lock";

export default function App() {
  const onClose = e => console.log(e);

  return (
    <FocusLock>
      <button onClick={onClose}>button</button>
    </FocusLock>
  );
}

We have the FocusLock component to keep the focus on the button.

The options for hos to focus and what component the FocusLock component can be rendered as can be changed.

React-Toastify

The React-Toastify component lets us add toasts to our React app easily.

To install the package, we run:

npm i react-toastify

Then we can use it by writing:

import React from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default function App() {
  const notify = () => toast("toast!");

  return (
    <div>
      <button onClick={notify}>Notify!</button>
      <ToastContainer />
    </div>
  );
}

We import the CSS and the JavaScript module.

Then we can call the toast function to display the toast.

The position, content, update, duration, etc., can all be changed.

React-Ace

The React-Ace is a text editor component that we can add to our React app.

We can install it by running:

npm i react-ace

Then we can use it by writing:

import React from "react";
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-java";
import "ace-builds/src-noconflict/theme-github";

export default function App() {
  function onChange(newValue) {
    console.log("change", newValue);
  }
  return (
    <div>
      <AceEditor
        mode="java"
        theme="github"
        onChange={onChange}
        name="id"
        editorProps={{ $blockScrolling: true }}
      />
    </div>
  );
}

We import the CSS and then we can use the AceEditor component to add the editor.

editorProps has the options for the editor.

We can add listeners for focus, blur, scroll, validate, and more.

The number of lines to display can also be changed.

mode is the language for parsing and code highlighting.

theme has the theme to use to style the editor.

It also comes with the SplitEditor component which can create multiple linked instances of the Ace editor.

Each instance shares a theme and other properties but they have their own value.

For example, we can write:

import React from "react";
import { split as SplitEditor } from "react-ace";
import "ace-builds/src-noconflict/mode-java";
import "ace-builds/src-noconflict/theme-github";

export default function App() {
  return (
    <div>
      <SplitEditor
        mode="java"
        theme="github"
        splits={2}
        orientation="below"
        value={["hi", "hello"]}
        name="id"
        editorProps={{ $blockScrolling: true }}
      />
    </div>
  );
}

to add the split editor.

react-day-picker

react-day-picker is a flexible day picker we can use in our React app.

It’s highly customizable, localizable, and it doesn’t require any external dependencies.

To install it, we run:

npm i react-day-picker

Then we can add the day picker with the DayPicker component:

import React from "react";
import DayPicker from "react-day-picker";
import "react-day-picker/lib/style.css";

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

We can make it a controlled component by passing in the onDayClick and selectedDays props:

import React from "react";
import DayPicker from "react-day-picker";
import "react-day-picker/lib/style.css";

export default function App() {
  const [selectedDay, setSelectedDay] = React.useState();

  const handleDayClick = day => {
    setSelectedDay(day);
  };

  return (
    <div>
      <DayPicker onDayClick={handleDayClick} selectedDays={selectedDay} />
    </div>
  );
}

onDayClick sets the day selected to the selectedDay state.

selectedDays has the value of the selected day from the selectedDay state.

We can style it and it supports localization.

Conclusion

react-focus-lock lets us set the focus on elements on the app.

React-Toastify lets us display toasts easily.

React-Ace is a text editor.

react-day-picker is a day picker that’s styleable and supports localization.

Categories
Top React Libraries

Top React Libraries — Editor, Translation, and Code Splitting

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.

draft-js

Draft.js is a package that lets us add a rich text editor to our React app.

We can install it by running:

npm i draft-js

Then we can use it by writing:

import React from "react";
import { Editor, EditorState } from "draft-js";

export default function App() {
  const [editorState, setEditorState] = React.useState(
    EditorState.createEmpty()
  );

  const editor = React.useRef(null);

  function focusEditor() {
    editor.current.focus();
  }

  React.useEffect(() => {
    focusEditor();
  }, []);

  return (
    <div onClick={focusEditor}>
      <Editor
        ref={editor}
        editorState={editorState}
        onChange={editorState => setEditorState(editorState)}
      />
    </div>
  );
}

We added the Editor component to add the rich text editor.

It will have nothing but a cursor displayed to let us enter text.

We use the setEditorState function to set the editor’s state as we type.

react-i18next

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

To install it, we run:

npm i react-i18next i18next-browser-languagedetector react-i18next

Then we can use it by writing:

import React from "react";
import i18n from "i18next";
import { useTranslation, Trans } from "react-i18next";

import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    // we init with resources
    resources: {
      en: {
        translations: {
          "To get started, edit <1>src/App.js</1> and save to reload.":
            "To get started, edit <1>src/App.js</1> and save to reload.",
          "Welcome to React": "Welcome to React and react-i18next",
          welcome: "Hello <br/> <strong>World</strong>"
        }
      },
      de: {
        translations: {
          "To get started, edit <1>src/App.js</1> and save to reload.":
            "Starte in dem du, <1>src/App.js</1> editierst und speicherst.",
          "Welcome to React": "Willkommen bei React und react-i18next"
        }
      }
    },
    fallbackLng: "en",
    debug: true,
    ns: ["translations"],
    defaultNS: "translations",
    keySeparator: false,
    interpolation: {
      escapeValue: false
    }
  });

export default function App() {
  const { t, i18n } = useTranslation();

  const changeLanguage = lng => {
    i18n.changeLanguage(lng);
  };

  const index = 11;

  return (
    <div className="App">
      <div className="App-header">
        <h2>{t("Welcome to React")}</h2>
        <button onClick={() => changeLanguage("de")}>de</button>
        <button onClick={() => changeLanguage("en")}>en</button>
      </div>
      <div className="App-intro">
        <Trans>
          To get started, edit <code>src/App.js</code> and save to reload.
        </Trans>
        <Trans i18nKey="welcome">trans</Trans>
        <Trans>{index + 1}</Trans>
      </div>
    </div>
  );
}

We added the translations in the init method.

Also, we set the fallback language to English with the fallbackLng option.

ns sets the namespace for translation.

defaultNS is the default namespace.

interpolation has interpolation options.

escapeValue escapes the values when set to true .

Then in App , we have the changeLanguage function to change the language with the i18n.changeLanguage method call.

Finally, we have the Trans component to add the translation.

react-loadable

react-loadable is a package that lets us add code splitting to our app.

To install it, we run:

npm i react-loadable

Then we can use it by writing:

Foo.js

import React from "react";

export default () => {
  return <div>foo</div>;
};

App.js

import React from "react";
import Loadable from "react-loadable";

const LoadableComponent = Loadable({
  loader: () => import("./Foo"),
  loading: () => <p>loading</p>
});

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

We have a Foo component to display something.

Then in App.js , we created the LoadableComponent by importing the Foo component from Foo.js .

The loading property has a component to display when Foo.js is loading.

And then we can use LoadableComponent in App .

Conclusion

draft-js lets us create a customizable text editor.

react-loadable lets us do code splitting by dynamically loading components.

react-i18next is a package for adding translations in our app.