Categories
Top React Libraries

Top React Libraries — Date Pickers and Clicks Outside

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 Date Picker

We can add a date picker to our React app with the React Date Picker package.

To install it, we run:

npm i react-datepicker

Then we can use it by writing:

import React from "react";
import DatePicker from "react-datepicker";

import "react-datepicker/dist/react-datepicker.css";

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

  const handleChange = date => {
    setDate(date);
  };

  return (
    <div className="App">
      <DatePicker selected={date} onChange={handleChange} />
    </div>
  );
}

We just use useState to create our state.

Then we pass in the date state as the value of the selected prop.

onChange has the change handler to update the selected value as the new value of the date state.

It’s reusable and configurable.

We can add a timer picker to it.

Also, it supports localization.

We can add a time picker with the showTimeSelect prop:

import React from "react";
import DatePicker from "react-datepicker";

import "react-datepicker/dist/react-datepicker.css";

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

  const handleChange = date => {
    setDate(date);
  };

  return (
    <div className="App">
      <DatePicker showTimeSelect selected={date} onChange={handleChange} />
    </div>
  );
}

It supports most modern browsers include the latest Internet Explorer version.

react-onclickoutside

We can use the react-onclickoutside package to detect clicks outside a component.

To install it, we can run:

npm i react-onclickoutside

Then we can use it by writing:

import React, { useState } from "react";
import onClickOutside from "react-onclickoutside";
import "./styles.css";

const Menu = () => {
  const [isOpen, setIsOpen] = useState(false);
  const toggle = () => setIsOpen(!isOpen);

Menu.handleClickOutside = () => setIsOpen(false);
  return (
    <li className={isOpen ? "m-menu -active" : "m-menu "} onClick={toggle}>
      <div> Open Menu </div>
      <ul className="m-menu__list">
        <li className="m-menu__item">
          <div className="m-menu__link">Log Out</div>
        </li>
      </ul>
    </li>
  );
};

const clickOutsideConfig = {
  handleClickOutside: () => Menu.handleClickOutside
};

const OutsideMenu = onClickOutside(Menu, clickOutsideConfig);

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

In style.css , we write:

.App {
  font-family: sans-serif;
}

.-padding-4 {
  padding: 4px;
}

.m-menu {
  list-style-type: none;
  position: relative;
  z-index: 101;
}
.m-menu.-active .m-menu__icon path {
  fill: #0b3895;
}
.m-menu.-active .m-menu__list {
  transform: scale(1);
}
.m-menu__list {
  position: relative;
  text-align: left;
  width: 100px;
  top: 50%;
  z-index: 101;
  padding: 0;
  border-radius: 8px;
  background-color: #fff;
  transform: scale(0);
  transform-origin: 0 1;
  border: 1px solid gray;
}
.m-menu__item {
  display: block;
  width: 100%;
  padding: 12px;
}
.m-menu__item:hover {
  color: #0b3895;
}
.m-menu__link {
  width: 100%;
  padding: 4px;
  display: inline-block;
  white-space: pre;
}
.m-menu__link:hover {
  color: #0b3895;
  text-decoration: none;
}

to apply the styles.

We use the onClickOutside higher-order component to let us listen to clicks outside the component.

The handleClickOutside function which we used as the click outside listener is added as a property of the component

Then we use it in the higher-order component to let us listen to the click outside events.

And then we can use the menu in App .

In styles.css , we add styles so that the menus is displayed below the button.

We also make it position: relative so that we can see the menu over other items.

It has other options.

We can prevent default behavior or stop the propagation of the click outside event.

And we can enable or disable listening to clicks outside.

Conclusion

We can use React Date Picker to add a date picker to our React app.

The react-onclickoutside package lets us listen to clicks outside a component.

Categories
Top React Libraries

Top React Libraries — Animation, Sizes, and Markdown

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

The React-Motion package lets us animate content our way.

To install it, we can run:

npm i react-motion

Then we can use it by writing:

import React from "react";
import { Motion, spring } from "react-motion";

export default function App() {
  return (
    <div className="App">
      <Motion defaultStyle={{ x: 0 }} style={{ x: spring(100) }}>
        {value => <div>{value.x}</div>}
      </Motion>
    </div>
  );
}

It comes with the Motion component to set the default style.

The x property is displayed by rendering value.x .

Then we use the spring function to animate the number going from 0 to 100.

There’re other kinds of motions that it supports.

For instance, we can use the StaggerMotion component to animate the stretching of 2 boxes:

import React from "react";
import { StaggeredMotion, spring } from "react-motion";

export default function App() {
  return (
    <div className="App">
      <StaggeredMotion
        defaultStyles={[{ h: 0 }, { h: 0 }]}
        styles={prevInterpolatedStyles =>
          prevInterpolatedStyles.map((_, i) => {
            return i === 0
              ? { h: spring(100) }
              : { h: spring(prevInterpolatedStyles[i - 1].h) };
          })
        }
      >
        {interpolatingStyles => (
          <div>
            {interpolatingStyles.map((style, i) => (
              <div key={i} style={{ border: "1px solid", height: style.h }} />
            ))}
          </div>
        )}
      </StaggeredMotion>
    </div>
  );
}

We use the StaggeredMotion component with the defaultStyles having the initial styles for the height.

Then in the styles prop, we have the code to animate the height changes with the spring function.

We animate height the prevInterpolatedStyles to change the height to the intermediate height.

Then in between the tags, we animate the box with the given height.

react-sizeme

The react-sizeme lets us get the size of elements.

To install it, we can run:

npm i react-sizeme

Then we can use it by writing:

import React from "react";
import { SizeMe } from "react-sizeme";

export default function App() {
  return (
    <div className="App">
      <SizeMe>{({ size }) => <div>width: {size.width}px</div>}</SizeMe>
    </div>
  );
}

The SizeMe component has the size of the div.

We get the value with size.width .

We can also use the withSize higher-order component to get the dimensions:

import React from "react";
import { withSize } from "react-sizeme";

function App({ size }) {
  return <div>My width is {size.width}px</div>;
}

export default withSize()(App);

react-markdown

The react-markdown lets us render markdown code in our React app.

To install it, we run:

npm i react-markdown

Then we can use it by writing:

import React from "react";
const ReactMarkdown = require("react-markdown");

const input = `# This is a header

And this is a paragraph

This is a [link]([http://example.com)`](http://example.com%29`);

export default function App() {
  return (
    <div className="App">
      <ReactMarkdown source={input} />
    </div>
  );
}

We have our markdown code in a string.

Then we pass that into the ReactMarkdown component as the value of the source prop to display it.

It can also parse HTML:

import React from "react";
const ReactMarkdown = require("react-markdown");

const input = `# This is a header

And this is a paragraph

<code>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis lacinia consectetur nunc. Morbi suscipit volutpat urna, in feugiat lorem convallis eget. Ut vel diam imperdiet, ultricies ligula et, tempor nibh. Donec congue turpis ex, in rhoncus sem feugiat eu. Donec condimentum volutpat ligula ac venenatis. Fusce lectus ligula, porttitor eu mollis ac, dictum vitae ligula. Pellentesque suscipit facilisis risus, finibus facilisis velit varius a. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Sed consequat justo in euismod volutpat. Cras blandit, nibh nec ornare tincidunt, libero metus tempor risus, non pulvinar nisl justo vitae arcu. Fusce sed mi et augue convallis volutpat et vitae turpis. Vestibulum efficitur ac est id ultrices. Quisque condimentum augue lectus, vulputate auctor ex ultrices sed. Vivamus facilisis est ac urna vestibulum eleifend.</code>`;

export default function App() {
  return (
    <div className="App">
      <ReactMarkdown source={input} escapeHtml={false} />
    </div>
  );
}

It’ll render all the text in the code tag and display them as code.

Conclusion

React-Motion lets us animate anything.

The react-sizeme package gets the size of elements.

react-markdown renders Markdown into HTML.

Categories
Top React Libraries

Top React Libraries — Swipes, Scrolls, and Dropdowns

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

The React Swipeable package lets us add swipe handlers to our components.

To install it, we run:

npm i react-swipeable

Then we can use it by writing:

import React from "react";
import { useSwipeable } from "react-swipeable";

export default function App() {
  const handlers = useSwipeable({
    onSwiped: eventData => console.log("swiped")
  });
  return (
    <div className="App">
      <div {...handlers}> You can swipe here </div>
    </div>
  );
}

We have the handlers object which has the handlers for swiping.

The object has methods like onSwiped , onSwipedLeft , onSwipedRight , onSwipedUp , onSwipedDown , and onSwiping .

The useSwipeable hook will return those automatically.

All we have to do is pass in an event handler for swiping.

We can also use the Swipeable component.

For instance, we can write:

import React from "react";
import { Swipeable } from "react-swipeable";

export default function App() {
  return (
    <div className="App">
      <Swipeable onSwiped={eventData => console.log("swiped")}>
        You can swipe here!
      </Swipeable>
    </div>
  );
}

to do the same thing.

The eventData has lots of data like x and y coordinates change, velocity, and direction.

rc-dropdown

rc-dropdown is a package that provides with a menu component.

To install it, we can run:

npm i rc-dropdown

Then we can write:

import React from "react";
import Dropdown from "rc-dropdown";
import Menu, { Item as MenuItem, Divider } from "rc-menu";
import "rc-dropdown/assets/index.css";

function onSelect({ key }) {
  console.log(`${key} selected`);
}

function onVisibleChange(visible) {
  console.log(visible);
}

const menu = (
  <Menu onSelect={onSelect}>
    <MenuItem disabled>disabled</MenuItem>
    <MenuItem key="1">foo</MenuItem>
    <Divider />
    <MenuItem key="2">bar</MenuItem>
  </Menu>
);

export default function App() {
  return (
    <div>
      <div style={{ margin: 20 }}>
        <div style={{ height: 100 }} />
        <div>
          <Dropdown
            trigger={["click"]}
            overlay={menu}
            animation="slide-up"
            onVisibleChange={onVisibleChange}
          >
            <button style={{ width: 100 }}>open</button>
          </Dropdown>
        </div>
      </div>
    </div>
  );
}

to use it.

We have the Dropdown component with the dropdown.

It has the trigger prop to specify how to trigger the menu.

overlay has the menu overlay.

onVisibleChange is an event handler function that runs when the menu visibility changes.

The menu is in the menu component, we use the Menu component to create the menu.

MenuItem has the menu item.

Divider has the divider.

Menu takes an onSelect prop that runs when an item is selected.

The package also provides its own CSS to style the menu.

Other features include transition, clicks, and more.

React Waypoint

React Waypoint lets us add a component to watch for scrolling to a given position.

To install it, we run:

npm i react-waypoint

Then we can use it by writing:

import React from "react";
import { Waypoint } from "react-waypoint";

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

  return (
    <div>
      <div>
        {Array(1000)
          .fill()
          .map((_, i) => {
            if (i !== 500) {
              return <p key={i}>item {i + 1}</p>;
            }
            return (
              <Waypoint
                key={500}
                onEnter={handleWaypointEnter}
                onLeave={handleWaypointLeave}
              />
            );
          })}
      </div>
    </div>
  );
}

We create an array of p elements.

In the middle of the array, we return the Waypoint component to watch for scrolling to that position.

The onEnter handler runs when we scrolling to the Waypoint and onLeave runs when we scroll away from it.

It takes handlers for onPositionChange , whether to check for horizontal scrolling and more.

Conclusion

React Swipeable lets us handle swipes of a component.

rc-dropdown is a simple dropdown library to let us add them.

React Waypoint is a package that lets us watch for scrolling to a given position.

Categories
Top React Libraries

Top React Libraries — Color and File Pickers, Modals, and Draggable Elements

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

React-Draggable lets us create draggable elements with ease.

To install it, we can run:

npm i react-draggable

to install it.

Then we can use it by writing:

import React from "react";
import Draggable from "react-draggable";

export default function App() {
  const eventLogger = (e, data) => {
    console.log("Event: ", e);
    console.log("Data: ", data);
  };

  return (
    <div className="App">
      <Draggable
        axis="x"
        handle=".handle"
        defaultPosition={{ x: 0, y: 0 }}
        position={null}
        grid={[25, 25]}
        scale={1}
        onStart={eventLogger}
        onDrag={eventLogger}
        onStop={eventLogger}
      >
        <div>
          <div className="handle">Drag me</div>
        </div>
      </Draggable>
    </div>
  );
}

We create a draggable element with the Draggable component.

It has the axis prop to specify which axis we can drag the element in.

handle has the selector of the drag handle element.

defaultPosition has the default position.

position has the position of the draggable element.

scale is the scale.

onStart , onDrag and onDrop are handlers that are run when we start dragging, during dragging, and stop dragging respectively.

react-modal

React-modal is a package that lets us create a modal easily.

To install it, we can run:

npm i react-modal

to install it.

Then we can use it by writing:

import React from "react";
import Modal from "react-modal";

export default function App() {
  const [modalIsOpen, setIsOpen] = React.useState(false);
  function openModal() {
    setIsOpen(true);
  }

  function afterOpenModal() {
    console.log("after modal");
  }

  function closeModal() {
    setIsOpen(false);
  }

  return (
    <div>
      <button onClick={openModal}>Open Modal</button>
      <Modal
        isOpen={modalIsOpen}
        onAfterOpen={afterOpenModal}
        onRequestClose={closeModal}
        contentLabel="Example Modal"
      >
        <h1>Hello</h1>
        <button onClick={closeModal}>close</button>
        <div>Some modal</div>
        <form>
          <input />
          <button>ok</button>
          <button>cancel</button>
          <button>another button</button>
        </form>
      </Modal>
    </div>
  );
}

We create a modal with the Modal component.

It can have lots of stuff in it.

We also passed in several props to the Modal component.

isOpen lets us set the state for when it opens.

onAfterOpen lets us run a function with code after it opens.

onRequestClose has a function that runs when the modal is closed.

contentLabel has the label for the modal.

Inside the tags, we have our content.

We have a button to close the modal with the closeModal function to set the modalIsOpen state to false .

react-dropzone

We can have the react-dropzone package to create a dropzone component in our React app.

To install it, we run:

npm i react-dropzone

to install it.

Then we can use it by using the useDropzone hook:

import React from "react";
import { useDropzone } from "react-dropzone";

export default function App() {
  const [selectedFile, setSelectedFile] = React.useState({});
  const onDrop = React.useCallback(acceptedFiles => {
    setSelectedFile(acceptedFiles[0]);
  }, []);
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      {isDragActive ? (
        <p>Drop the files here ...</p>
      ) : (
        <p>Drag 'n' drop some files here</p>
      )}
      <p>{selectedFile.name}</p>
    </div>
  );
}

We have the useDropzone hook with the onDrop state that comes from the React.useCallback hook.

Once we selected a file, the callback in the useCallback hook will be called.

We get the selected file from the acceptedFile parameter.

Then we can display the name of the selected file with the selectedFile state.

React Color

React Color lets us add color pickers within a React app.

To install it, we can run:

npm i react-color

Then we can use it by writing:

import React from "react";
import { SketchPicker } from "react-color";

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

We added a color picker that looks like the color picker from Autodesk’s Sketch.

To get the color, we can write:

import React from "react";
import { SketchPicker } from "react-color";

export default function App() {
  const [background, setBackground] = React.useState("");
  return (
    <div>
      <SketchPicker
        color={background}
        onChangeComplete={color => setBackground(color.hex)}
      />
      <p>{background}</p>
    </div>
  );
}

We get the hex value of the color with the color.hex property.

Conclusion

There’re packages to add color pickers, draggable elements, models and file pickers.

Categories
Top React Libraries

Top React Libraries — Checkbox, Alignment, and Code Editor

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

The rc-checkbox gives us a styled checkbox component.

To install it, we run:

npm i rc-checkbox

Then we use it by writing:

import React from "react";
import Checkbox from "rc-checkbox";
import "rc-checkbox/assets/index.css";

function onChange(e) {
  console.log(e.target.checked);
}

class App extends React.Component {
  render() {
    return (
      <div style={{ margin: 20 }}>
        <div>
          <p>
            <label>
              <Checkbox checked onChange={onChange} />
              &nbsp; controlled checkbox
            </label>
            &nbsp;&nbsp;
          </p>
          <p>
            <label>
              <input checked type="checkbox" onChange={onChange} />
              &nbsp; controlled checked native checkbox
            </label>
          </p>
        </div>

<div>
          <p>
            <label>
              <Checkbox defaultChecked onChange={onChange} />
              &nbsp; checkbox
            </label>
            &nbsp;&nbsp;
          </p>
          <p>
            <label>
              <input
                type="checkbox"
                defaultChecked
                onChange={onChange}
                disabled
              />
              &nbsp; native
            </label>
            &nbsp;&nbsp;
          </p>
        </div>

<div>
          <p>
            <label>
              <Checkbox
                name="my-checkbox"
                defaultChecked
                onChange={onChange}
                disabled
              />
              &nbsp; defaultChecked rc-checkbox with name
            </label>
            &nbsp;&nbsp;
          </p>
          <p>
            <label>
              <input
                name="my-checkbox"
                type="checkbox"
                defaultChecked
                onChange={onChange}
                disabled
              />
              &nbsp; native with name
            </label>
            &nbsp;&nbsp;
          </p>
        </div>
      </div>
    );
  }
}
export default App;

We use the Checkbox component with the CSS to display checkboxes with styles.

The onChange prop lets us get the checked value.

checked makes it checked.

disabled makes it disabled.

The name has the name.

The type has the input type.

defaultChecked makes it checked by default.

react-codemirror2

react-codemirror2 is a code editor React component.

To install it, we run:

npm i react-codemirror2 codemirror

Then we can use it as an uncontrolled component by writing:

import React from "react";
import { UnControlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/material.css";

const App = () => {
  return (
    <>
      <CodeMirror
        value="<h1>hello world</h1>"
        options={{
          mode: "xml",
          theme: "material",
          lineNumbers: true
        }}
        onChange={(editor, data, value) => {}}
      />
    </>
  );
};
export default App;

We import the CodeMirror compoinent with the styles.

Then we set the value prop with the value to show.

options has some options for displaying the code.

The mode is the language code.

theme is the theme to style the editor.

lineNumbers set to true indicate that we want to show line numbers on the left side.

We can also import a controller component and use that:

import React from "react";
import { Controlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/material.css";

class App extends React.Component {
  state = {
    value: "<h1>hello world</h1>"
  };

  render() {
    return (
      <CodeMirror
        value={this.state.value}
        options={{
          mode: "xml",
          theme: "material",
          lineNumbers: true
        }}
        onBeforeChange={(editor, data, value) => {
          this.setState({ value });
        }}
        onChange={(editor, data, value) => {}}
      />
    );
  }
}
export default App;

We have the state to hold the code in a string.

Then we can use that as the value of value .

options is the same as the uncontrolled version.

We also have onBeforeChange to update the value state with the new inputted value.

It emits many other events, including focus, drag, keypress, and more.

rc-align

rc-align is a package that lets us align an element to a given position.

To install it, we run:

npm i rc-align

Then we can use it by writing:

import React from "react";
import Align from "rc-align";

const align = {
  points: ["0", "0"]
};

class App extends React.Component {
  state = {
    point: null
  };

  onClick = ({ pageX, pageY }) => {
    this.setState({ point: { pageX, pageY } });
  };

  render() {
    return (
      <div style={{ marginBottom: 170 }}>
        <div
          style={{
            margin: 20,
            border: "1px solid green",
            padding: "100px 0",
            textAlign: "center"
          }}
          onClick={this.onClick}
        >
          Click me
        </div>

        <Align ref={this.alignRef} target={this.state.point} align={align}>
          <div
            style={{
              position: "absolute",
              width: 100,
              height: 100,
              background: "lightgreen",
              pointerEvents: "none"
            }}
          >
            Align
          </div>
        </Align>
      </div>
    );
  }
}
export default App;

We created a div inside the Align component.

This is a box that the div inside the Align component will go in if we click it.

When we click it, the onClick function will run and the new coordinate will be set.

align has the align config from the dom-align library.

The target is set to the point state’s value so that the Align div will move inside the box.

Conclusion

rc-checkbox provides us with checkbox components.

react-codemirror2 is a code editor component.

rc-align lets us align elements to a given position.