Categories
Top React Libraries

Top React Libraries — Media Queries and Autosuggest

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *