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.

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.