Categories
Top React Libraries

Top React Libraries — Table, CSS, and Sortable List

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

The react-table package lets us add a table to our React app.

To install it, we run:

npm i react-table

Then we can use it by writing:

import React from "react";
import { useTable } from "react-table";

const tableData = [
  { firstName: "james", lastName: "smith", age: 20 },
  { firstName: "may", lastName: "jones", age: 20 },
  { firstName: "alex", lastName: "smith", age: 20 }
];

function Table({ columns, data }) {
  const {
    getTableProps,
    getTableBodyProps,
    headerGroups,
    rows,
    prepareRow
  } = useTable({
    columns,
    data
  });

  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function App() {
  const columns = React.useMemo(
    () => [
      {
        Header: "Name",
        columns: [
          {
            Header: "First Name",
            accessor: "firstName"
          },
          {
            Header: "Last Name",
            accessor: "lastName"
          },
          {
            Header: "Age",
            accessor: "age"
          }
        ]
      }
    ],
    []
  );

  const data = React.useMemo(() => tableData, []);

  return (
    <>
      <Table columns={columns} data={data} />
    </>
  );
}

export default App;

We have an array with some data that we want to display in a table.

Then we create a Table component to display the data.

The component has the columns and data props.

We use that with the useTable hook to get more data needed to display the table.

Then we have the table component which has the getTableProps call to pass the props to the table.

headerGroups have the headers.

We call getHeaderGroupProps to pass the props to the tr.

tbody has the body and we use getTableBodyProps to get the props and pass them into there.

tr has the rows created from the prepareRow function.

We call the row.cells.map method to map them to cells.

The columns are defined in App .

We have the columns function of the Header and columns properties.

Header has the header to display.

accessor has the property name for from the tableData array entry we want to get and render.

Then we pass in the columns and data props to the Table component.

useMemo caches the data so that it’s only reloaded when it changes.

It has many other features like footers, sorting, filtering, and pagination.

ReactCSS

The ReactCSS package lets add inline styles with JavaScript.

It supports React. React Native, auto prefixing, hover, pseudoelements, and media queries.

To install it, we run:

npm i reactcss

Then we can use it by writing:

import React from "react";
import reactCSS from "reactcss";

const styles = reactCSS({
  default: {
    card: {
      background: "green",
      boxShadow: "0 2px 4px rgba(0,0,0,.15)",
      color: "white"
    }
  }
});

function App() {
  return (
    <>
      <div style={styles.card}>hello</div>
    </>
  );
}

export default App;

We created the styles with the reactCSS function.

The card property is an object with the styles.

We pass that into our div with the styles.card property.

Now we get a green background with a box shadow and the text color is white.

react-sortable-hoc

react-sortable-hoc is a package that lets us create sortable lists.

To install it, we can run:

npm i react-sortable-hoc

Then we use it by writing:

import React from "react";
import { SortableContainer, SortableElement } from "react-sortable-hoc";
import arrayMove from "array-move";

const SortableItem = SortableElement(({ value }) => <li>{value}</li>);

const SortableList = SortableContainer(({ items }) => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem key={`item-${value}`} index={index} value={value} />
      ))}
    </ul>
  );
});

export default class App extends React.Component {
  state = {
    items: Array(20)
      .fill()
      .map((_, i) => `item ${i + 1}`)
  };
  onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState(({ items }) => ({
      items: arrayMove(items, oldIndex, newIndex)
    }));
  };
  render() {
    return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
  }
}

SortableItem is a component with the sortable item.

We can drag them to sort them.

SortableList has our list with the SortableItems .

We just render them with map .

Then we have our App component with the items state with the items.

Also, we have the onSortEnd method to do the sorting with the arrayMove function.

It’s a helper that lets us change the position of the items without writing code to do it ourselves.

Now we get a list where we can drag items to move them.

Conclusion

react-table lets us create a table with ease.

ReactCSS create the CSS for us to use in our app.

react-sortable-hoc helps us create a sortable list easily.

Categories
Top React Libraries

Top React Libraries — Scrolling and Menus

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 Scroll

The React Scroll library lets us animate vertical scrolling.

To install it, we run:

npm i react-scroll

Then we can use it by writing:

import React from "react";
import { animateScroll as scroll } from "react-scroll";

export default function App() {
  const scrollToTop = () => {
    scroll.scrollToTop();
  };

  const scrollToBottom = () => {
    scroll.scrollToBottom();
  };

  return (
    <div>
      <button onClick={scrollToBottom}>scroll to bottom</button>
      {Array(150)
        .fill()
        .map((_, i) => (
          <p>item {i + 1}</p>
        ))}
      <button onClick={scrollToTop}>scroll to top</button>
    </div>
  );
}

We use the scroll object that comes with the package to do the scrolling.

The scrolling will have an animation effect applied to it.

It also comes with a Link component to let us add links for scrolling to an anchor element.

For example, we can write:

import React from "react";
import { Link } from "react-scroll";

export default function App() {
  const handleSetActive = to => {
    console.log(to);
  };

  return (
    <div>
      <Link
        activeClass="active"
        to="item-100"
        spy={true}
        smooth={true}
        offset={50}
        duration={500}
        onSetActive={handleSetActive}
      >
        scroll to item 100
      </Link>
      {Array(150)
        .fill()
        .map((_, i) => (
          <p id={`item-${i + 1}`}>item {i + 1}</p>
        ))}
    </div>
  );
}

to scroll to the item with ID item-100 .

The onSetActive prop has the function that runs when the scrolling is done.

smooth means that the scrolling will have a smooth scrolling effect.

offset has the distance to scroll to once it reached the element.

duration is the length of the scrolling animation.

It comes with many other options for adjusting the scrolling.

rc-menu

rc-menu is a useful React menu component to let us add menu items easily to our app.

We can install it by running:

npm i rc-menu

Then we can use it by writing:

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

const titleRight = <span>sub menu</span>;
const titleRight1 = <span>sub menu 1</span>;
const titleRight2 = <span>sub menu 2</span>;
const titleRight3 = <span>sub menu 3</span>;

function handleSelect(info) {
  console.log("selected ", info);
}

function handleClick(info) {
  console.log("click ", info);
}

export default function App() {
  return (
    <div>
      <Menu onSelect={handleSelect} defaultActiveFirst onClick={handleClick}>
        <SubMenu title={titleRight} key="1">
          <MenuItem key="1-1">0-1</MenuItem>
          <MenuItem key="1-2">0-2</MenuItem>
        </SubMenu>
        <MenuItem>
          <a href="http://example.com" target="_blank">
            link
          </a>
        </MenuItem>
        <MenuItem key="3">outer</MenuItem>
        <SubMenu title={titleRight1} key="4">
          <MenuItem key="4-1">inner inner</MenuItem>
          <Divider />
          <SubMenu key="4-2" title={titleRight2}>
            <MenuItem key="4-2-1">inner menu</MenuItem>
            <SubMenu title={titleRight3} key="4-2-2">
              <MenuItem key="4-2-2-1">inner inner</MenuItem>
              <MenuItem key="4-2-2-2">inner inner2</MenuItem>
            </SubMenu>
          </SubMenu>
        </SubMenu>
        <MenuItem disabled>disabled</MenuItem>
        <MenuItem key="4-3">another item</MenuItem>
      </Menu>
    </div>
  );
}

We have the Menu , MenuItem , SubMenu and Divider components to build the menu.

Menu is the root menu component.

MenuItem has the menu item components.

SubMenu have the nested menu items.

The title prop has the title of the submenu.

Divider is a menu divider.

It has many other options like transitions, changing the expand and item icons, and more.

react-window

rc-pagination is a component that lets us add a virtualized scroll list to our React app

To add it, we run:

npm i react-window

to install it.

Then we can use it by writing:

import React from "react";
import { FixedSizeList as List } from "react-window";

const Row = ({ index, style }) => <div style={style}>Row {index}</div>;

export default function App() {
  return (
    <div>
      <List height={150} itemCount={1000} itemSize={35} width={300}>
        {Row}
      </List>
    </div>
  );
}

We add the Row component to let us render the row.

style has the position. index has the index of the row.

Then we used the List component to render the Row .

height is the height of the list.

itemCount is the number of items.

itemSize is the size of the row.

width is the width of the row.

We can change the style, make the list have variable size, add scrolling indicators, and more.

Conclusion

React Scroll is a React library that lets us add smooth scrolling effects to our app.

rc-menu lets us add a menu to our app.

react-window is an easy to use virtualized scroll list library.

Categories
Top React Libraries

Top React Libraries — Tooltips, Dialogs, and Cookies

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 Tooltip

React Tooltip is an easy to use tooltip library to let us add a tooltip to our app.

To install it, we run:

npm i react-popper-tooltip

Then we can use it by writing:

import React from "react";
import TooltipTrigger from "react-popper-tooltip";
import "react-popper-tooltip/dist/styles.css";

const Tooltip = ({
  arrowRef,
  tooltipRef,
  getArrowProps,
  getTooltipProps,
  placement
}) => (
  <div
    {...getTooltipProps({
      ref: tooltipRef,
      className: "tooltip-container"
    })}
  >
    <div
      {...getArrowProps({
        ref: arrowRef,
        className: "tooltip-arrow",
        "data-placement": placement
      })}
    />
    Hello, World
  </div>
);

const Trigger = ({ getTriggerProps, triggerRef }) => (
  <span
    {...getTriggerProps({
      ref: triggerRef,
      className: "trigger"
    })}
  >
    Click Me
  </span>
);

export default function App() {
  return (
    <div className="App">
      <TooltipTrigger placement="right" trigger="click" tooltip={Tooltip}>
        {Trigger}
      </TooltipTrigger>
    </div>
  );
}

We import the CSS so that we see some styles in our tooltips.

Then we add the Tooltip component to ley us display the tooltip.

It takes several props including some refs for the arrow and tooltip.

Also, there’s one prop to let us set the tooltip placement to be beside the trigger element which we expect.

The content of the tooltip is also in the same component.

Trigger is a component that lets us trigger the tooltip.

It’s passed in as the child of the TooltipTrigger component.

This lets us set the placement with the placement prop and the event that triggers the tooltip with the trigger prop.

We can configure how the tooltip is triggered with the components that this package comes with.

rc-dialog

rc-dialog is a React package to let us add a dialog easily in our app.

To install it, we run:

npm i rc-dialog

Then we can use it by writing:

import React from "react";
import "rc-dialog/assets/bootstrap.css";
const Dialog = require("rc-dialog");

export default function App() {
  const [visible, setVisible] = React.useState(false);

  const onClose = () => setVisible(false);

  return (
    <div className="App">
      <button onClick={() => setVisible(true)}>open</button>
      <Dialog
        visible={visible}
        animation="slide-fade"
        maskAnimation="fade"
        title="hello world"
        onClose={onClose}
      >
        <p>first dialog</p>
      </Dialog>
    </div>
  );
}

We import the styles with the dialog.

Then in the App component, we have a button to open the dialog box.

When we click the button, we set the visible state to true .

Then we have the Dialog component.

We set the visible prop to the visible state.

animation has the animation we want to show when we open the dialoh.

maskAnimation is set to fade as the mask animation’s class name.

title has the dialog title.

onClose has a function that runs when we click the ‘x’ or when we click away from the dialog to close it.

The content of the dialog is between the tags.

It also supports many other options like disabling closing, enable or disable closing with the keyboard, the icon for the close button, and more.

react-cookie

react-cookie is an easy to use package for managing client-side cookies in a React app.

To use it, we install it by running:

npm i react-cookie

Then we can use it by writing:

import React, { useEffect } from "react";
import { useCookies } from "react-cookie";

export default function App() {
  const [cookies, setCookie] = useCookies(["name"]);

  useEffect(() => {
    setCookie("name", "mary", { path: "/" });
  }, []);

  return <div>{cookies.name && <h1>Hello {cookies.name}!</h1>}</div>;
}

It comes with the useCookies hook which takes an array with the cookie keys we want to get.

It returns the cookies state with the cookie keys and values.

And it returns the setCookie function to let us set cookies.

It takes the key as the first argument.

The value is the second argument.

The 3rd argument has additional parameters that we can set for the cookies like the path and expiry.

There’re also functions to remove cookies, and it comes with the withCookies higher-order component to let us access cookies data and functions via props.

We can get, set, and remove cookie values.

Server-side rendering is also supported.

Conclusion

React Tooltip is an easy to use package for displaying tooltips.

rc-dialog lets us add dialog boxes in our app.

react-cookie lets us manage client-side cookies with ease.

Categories
Top React Libraries

Top React Libraries — Scrolling and Menus

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 Scroll

The React Scroll library lets us animate vertical scrolling.

To install it, we run:

npm i react-scroll

Then we can use it by writing:

import React from "react";
import { animateScroll as scroll } from "react-scroll";

export default function App() {
  const scrollToTop = () => {
    scroll.scrollToTop();
  };

  const scrollToBottom = () => {
    scroll.scrollToBottom();
  };

  return (
    <div>
      <button onClick={scrollToBottom}>scroll to bottom</button>
      {Array(150)
        .fill()
        .map((_, i) => (
          <p>item {i + 1}</p>
        ))}
      <button onClick={scrollToTop}>scroll to top</button>
    </div>
  );
}

We use the scroll object that comes with the package to do the scrolling.

The scrolling will have an animation effect applied to it.

It also comes with a Link component to let us add links for scrolling to an anchor element.

For example, we can write:

import React from "react";
import { Link } from "react-scroll";

export default function App() {
  const handleSetActive = to => {
    console.log(to);
  };

  return (
    <div>
      <Link
        activeClass="active"
        to="item-100"
        spy={true}
        smooth={true}
        offset={50}
        duration={500}
        onSetActive={handleSetActive}
      >
        scroll to item 100
      </Link>
      {Array(150)
        .fill()
        .map((_, i) => (
          <p id={`item-${i + 1}`}>item {i + 1}</p>
        ))}
    </div>
  );
}

to scroll to the item with ID item-100 .

The onSetActive prop has the function that runs when the scrolling is done.

smooth means that the scrolling will have a smooth scrolling effect.

offset has the distance to scroll to once it reached the element.

duration is the length of the scrolling animation.

It comes with many other options for adjusting the scrolling.

rc-menu

rc-menu is a useful React menu component to let us add menu items easily to our app.

We can install it by running:

npm i rc-menu

Then we can use it by writing:

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

const titleRight = <span>sub menu</span>;
const titleRight1 = <span>sub menu 1</span>;
const titleRight2 = <span>sub menu 2</span>;
const titleRight3 = <span>sub menu 3</span>;

function handleSelect(info) {
  console.log("selected ", info);
}

function handleClick(info) {
  console.log("click ", info);
}

export default function App() {
  return (
    <div>
      <Menu onSelect={handleSelect} defaultActiveFirst onClick={handleClick}>
        <SubMenu title={titleRight} key="1">
          <MenuItem key="1-1">0-1</MenuItem>
          <MenuItem key="1-2">0-2</MenuItem>
        </SubMenu>
        <MenuItem>
          <a href="http://example.com" target="_blank">
            link
          </a>
        </MenuItem>
        <MenuItem key="3">outer</MenuItem>
        <SubMenu title={titleRight1} key="4">
          <MenuItem key="4-1">inner inner</MenuItem>
          <Divider />
          <SubMenu key="4-2" title={titleRight2}>
            <MenuItem key="4-2-1">inner menu</MenuItem>
            <SubMenu title={titleRight3} key="4-2-2">
              <MenuItem key="4-2-2-1">inner inner</MenuItem>
              <MenuItem key="4-2-2-2">inner inner2</MenuItem>
            </SubMenu>
          </SubMenu>
        </SubMenu>
        <MenuItem disabled>disabled</MenuItem>
        <MenuItem key="4-3">another item</MenuItem>
      </Menu>
    </div>
  );
}

We have the Menu , MenuItem , SubMenu and Divider components to build the menu.

Menu is the root menu component.

MenuItem has the menu item components.

SubMenu have the nested menu items.

The title prop has the title of the submenu.

Divider is a menu divider.

It has many other options like transitions, changing the expand and item icons, and more.

react-window

rc-pagination is a component that lets us add a virtualized scroll list to our React app

To add it, we run:

npm i react-window

to install it.

Then we can use it by writing:

import React from "react";
import { FixedSizeList as List } from "react-window";

const Row = ({ index, style }) => <div style={style}>Row {index}</div>;

export default function App() {
  return (
    <div>
      <List height={150} itemCount={1000} itemSize={35} width={300}>
        {Row}
      </List>
    </div>
  );
}

We add the Row component to let us render the row.

style has the position. index has the index of the row.

Then we used the List component to render the Row .

height is the height of the list.

itemCount is the number of items.

itemSize is the size of the row.

width is the width of the row.

We can change the style, make the list have variable size, add scrolling indicators, and more.

Conclusion

React Scroll is a React library that lets us add smooth scrolling effects to our app.

rc-menu lets us add a menu to our app.

react-window is an easy to use virtualized scroll list library.

Categories
Top React Libraries

Top React Libraries — Media Queries and Autosuggest

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

The react-responsive package can detect screen sizes based on media queries.

We can install it by running:

npm i react-responsive

Then we can use it by writing:

import React from "react";
import { useMediaQuery } from "react-responsive";

export default function App() {
  const isDesktopOrLaptop = useMediaQuery({
    query: "(min-device-width: 1200px)"
  });
  const isBigScreen = useMediaQuery({ query: "(min-device-width: 1800px)" });
  const isTabletOrMobile = useMediaQuery({ query: "(max-width: 1200px)" });
  const isTabletOrMobileDevice = useMediaQuery({
    query: "(max-device-width: 1200px)"
  });
  const isPortrait = useMediaQuery({ query: "(orientation: portrait)" });
  const isRetina = useMediaQuery({ query: "(min-resolution: 2dppx)" });

  return (
    <div>
      {isDesktopOrLaptop && (
        <>
          <p>desktop or laptop</p>
          {isBigScreen && <p>big screen</p>}
          {isTabletOrMobile && <p>tablet or mobile phone</p>}
        </>
      )}
      {isTabletOrMobileDevice && <p>tablet or mobile phone</p>}
      <p>{isPortrait ? "portrait" : "landscape"} orientation</p>
      {isRetina && <p>retina</p>}
    </div>
  );
}

The useMediaQuery is what we use to detect various screen sizes.

We just use a regular media query in a string to detect the sizes.

We can also use widths as breakpoints:

import React from "react";
import { useMediaQuery } from "react-responsive";

const Desktop = ({ children }) => {
  const isDesktop = useMediaQuery({ minWidth: 1000 });
  return isDesktop ? children : null;
};
const Tablet = ({ children }) => {
  const isTablet = useMediaQuery({ minWidth: 800, maxWidth: 999 });
  return isTablet ? children : null;
};
const Mobile = ({ children }) => {
  const isMobile = useMediaQuery({ maxWidth: 800 });
  return isMobile ? children : null;
};
const Default = ({ children }) => {
  const isNotMobile = useMediaQuery({ minWidth: 800 });
  return isNotMobile ? children : null;
};

export default function App() {
  return (
    <div>
      <Desktop>Desktop or laptop</Desktop>
      <Tablet>Tablet</Tablet>
      <Mobile>Mobile</Mobile>
      <Default>Not mobile</Default>
    </div>
  );
}

We detect screen sizes with the minWidth and maxWidth properties.

It’ll detect the size of the viewport automatically and display the content we want.

React Autosuggest

React Autosuggest is a autocomplete input library for React.

To use it, we can run:

npm i react-autosuggest

to install it.

Then we can use it by writing:

import React from "react";
import Autosuggest from "react-autosuggest";

const fruits = [
  {
    name: "apple"
  },
  {
    name: "orange"
  },
  {
    name: "grape"
  }
];

const getSuggestions = (value = "") => {
  const inputValue = value.trim().toLowerCase();
  const inputLength = inputValue.length;

  return inputLength === 0
    ? []
    : fruits.filter(
        fruit => fruit.name.toLowerCase().slice(0, inputLength) === inputValue
      );
};

const getSuggestionValue = suggestion => suggestion.name;

const renderSuggestion = suggestion => <div>{suggestion.name}</div>;

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

    this.state = {
      value: "",
      suggestions: []
    };
  }

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue
    });
  };

  onSuggestionsFetchRequested = ({ value }) => {
    this.setState({
      suggestions: getSuggestions(value)
    });
  };

  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

  render() {
    const { value, suggestions } = this.state;

    const inputProps = {
      placeholder: "Type a fruit",
      value,
      onChange: this.onChange
    };

    return (
      <Autosuggest
        suggestions={suggestions}
        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        getSuggestionValue={getSuggestionValue}
        renderSuggestion={renderSuggestion}
        inputProps={inputProps}
      />
    );
  }
}

We have fruits array with the suggestions.

The getSuggestions function returns the suggestion by matching the name field.

And we have the getSuggestionValue to get the name property from the suggested item.

renderSuggestion renders the suggestion entry below the input.

Then in our App component, we have the onChange function to set the value state to the state that’s entered.

onSuggestionsClearRequested clears the suggestions.

onSuggestionFetchRequested gets the suggestion according to the entered value.

We then pass in the inputProps to set the attributes of the input.

The other props are the functions that we created.

The functions or objects with the same name are passed in.

onSuggestionsFetchRequested is run as we type.

onSuggestionsClearRequested is run when we clear the input.

suggestions has the suggested items.

Once we did that, we’ll get the suggestions displayed as we type if something matches.

Conclusion

react-responsive detects the size of the screen with media queries.

React Autosuggest is an autocomplete input for React apps.