Get started with React Select

When working on web projects three or four years ago, selecting elements used to be one of the easiest things to build. Today, however, there are many elements of build choice, especially when UI and UX are high priorities.

 For example, features such as focusing, fetching data from remote sources, styling selection elements, etc. must be considered. When working on a React project, you probably expect reusable components to exist somewhere in the multiverse.

Fortunately, Jed Watson started an open source project called React Select funded by his company Thinkmill and Atlassian. In this article, we'll explore some of the cool features included in React Select v5, then learn how to get started with a simple example of how to set up and install an Android 4.0 emulator on your computer? Android emulator complete installation graphic tutorial React Select. You can also check out our video tutorial on React Select. let's start!

prerequisites

To follow along with this tutorial, you need the following:

  • Yarn or npm installed on the machine

  • Create a react app installed command-line interface tool

  • Basic understanding of HTML, JavaScript ES6 and CSS

  • Basic understanding of React framework

  • Basic understanding of the command line terminal

Install React Select

With these requirements in place, we'll start by adding the React Select package to our existing React application. In this tutorial, we'll be using the Create React App CLI tool.

If you don't have an existing project, you can create one with the following code:

npx create-react-app my-app
# OR
yarn create react-app my-app

Once done, we can install the React Select package with the following command:

npm install react-select
# OR
yarn add react-select

Now, we will see how to convert VCD to MP3 in React application? Import and use the React Select package in your conversion program in just three steps .

Basic usage of React Select

To start using React Select, we just need to import its component and add an array of objects containing the options and their corresponding labels: Select

// App.js
​
import Select from "react-select";
​
const App = () => {
  const options = [
    { value: "blues", label: "Blues" },
    { value: "rock", label: "Rock" },
    { value: "jazz", label: "Jazz" },
    { value: "orchestra", label: "Orchestra" },
  ];
​
  return (
    <div>
      <Select options={options} />
    </div>
  );
};
​
export default App;

In the code snippet above, we have selected options as music genres, and these options are passed into the component as props. When we run the app, we should see an element that spans the screen from one end to the other: select `` select

In the following sections, we'll see how to style components to extend their functionality and make them more visually appealing. But first, we'll add Bootstrap to our app to help build and prevent our components from taking up the entire width of the page . select``select

Add bootstrap

We can install Bootstrap in our project as follows:

npm install bootstrap
# OR
yarn add boostrap

With Bootstrap installed, we'll take advantage of its utility sitemapper class to restructure our application:

//App.js
import Select from "react-select";
​
// Import Bootstarp CSS
import "bootstrap/dist/css/bootstrap.css";
​
const App = () => {
  const options = [
    { value: "blues", label: "Blues" },
    { value: "rock", label: "Rock" },
    { value: "jazz", label: "Jazz" },
    { value: "orchestra", label: "Orchestra" },
  ];
  return (
    <div className="container">
      <div className="mt-5 m-auto w-50">
        <Select options={options} />
      </div>
    </div>
  );
};
​
export default App;

The above code will give us an element as shown in the image below: select

use and props onChange`` autofocus

Getting a value from a React Select component is comparable to using traditional HTML input; we can do it by leveraging its events along with a React Hook like so: onChange``useState

import { useState } from "react";
import Select from "react-select";
import "bootstrap/dist/css/bootstrap.css";
​
const App = () => {
  const options = [
    { value: "blues", label: "Blues" },
    { value: "rock", label: "Rock" },
    { value: "jazz", label: "Jazz" },
    { value: "orchestra", label: "Orchestra" },
  ];
​
  const [selected, setSelected] = useState(null);
​
  const handleChange = (selectedOption) => {
    setSelected(selectedOption);
    console.log(`Option selected:`, selectedOption);
  };
​
  return (
    <div className="container">
      <div className="mt-5 m-auto w-50">
        <Select options={options} onChange={handleChange} autoFocus={true} />
​
        <div className="mt-4">
          {selected && <>You've selected {selected.value}</>}
        </div>
      </div>
    </div>
  );
};
​
export default App;

In the code above, we've added a function to the event so that whenever the user changes an option in the component, our state is updated with an object containing the selected option's value and label. handleChange onChangeselect

So if we choose as option our console will show something like this: rock

Option selected: {value:"rock", label: "Rock"}

This is useful when we want to manipulate data obtained from React Select components. We also have prop which takes a value and is used to add to the component on page load. To learn more about the props available for use, you can check out React Select's props documentation. autoFocus booleanautoFocus``select

Add custom styles to React Select component

React Select is fully customizable, allowing us to style each unit, such as , , , and many more components. We can do this by passing an additional prop containing the new preferred styles for each cell: control optionsplaceholder selectstyles

Along the way, we also have access and the option to add default styles for each cell. We can also add styles as needed, which means we specify what style the option should have when it is selected or focused, etc.

To try them all out, paste the following code into the file: App.js

import Select from "react-select";
import "bootstrap/dist/css/bootstrap.css";
​
const App = () => {
  const options = [
    { value: "blues", label: "Blues" },
    { value: "rock", label: "Rock" },
    { value: "jazz", label: "Jazz" },
    { value: "orchestra", label: "Orchestra" },
  ];
  const customStyles = {
    option: (defaultStyles, state) => ({
      ...defaultStyles,
      color: state.isSelected ? "#212529" : "#fff",
      backgroundColor: state.isSelected ? "#a0a0a0" : "#212529",
    }),
​
    control: (defaultStyles) => ({
      ...defaultStyles,
      backgroundColor: "#212529",
      padding: "10px",
      border: "none",
      boxShadow: "none",
    }),
    singleValue: (defaultStyles) => ({ ...defaultStyles, color: "#fff" }),
  };
​
  return (
    <div className="container">
      <div className="mt-5 m-auto w-50 text-light">
        <Select options={options} styles={customStyles} />
      </div>
    </div>
  );
};
​
export default App;

In the above code, we modified the component to add custom styles to the select, its options via, and the currently selected option to. We made the changes to give the component a dark mode look. When you run the application, you should have output similar to: select controloption singleValueselect

custom components

Under Styling and State, we discussed two custom components, and one for extending styles. In this section, we'll introduce another one called .option controlselect ``Custom SingleValue

This custom component does what our regular component does, but we'll add a few tricks. In our file, we'll import the and package from React and React Select with the following code: select App.jsReact ``Select

import Select, { components } from 'react-select';
. . .

Once complete, we will have a completed dropdown that looks like this:

In the code block below, we define custom components as methods that extend the base components in the React Select package. In our class we have several props and functions that contribute to the functionality shown in the image above: SingleValue``App

import { useState } from "react";
import "bootstrap/dist/css/bootstrap.css";
import Select, { components } from "react-select";

const Control = ({ children, ...props }) => (
  <components.Control {...props}>
    Click to Select → {children}
  </components.Control>
);

const App = () => {
  const options = [
    { value: "blue", label: "Blue" },
    { value: "green", label: "Green" },
    { value: "orange", label: "Orange" },
    { value: "purple", label: "Purple" },
  ];

  const customStyles = {
    singleValue: (base) => ({
      ...base,
      padding: "5px 10px",
      borderRadius: 5,
      background: selected,
      color: "white",
      display: "flex",
      width: "fit-content",
    }),
  };

  const [selected, setSelected] = useState("");
  var handleChange = (selected) => {
    setSelected(selected.value);
  };

  return (
    <div className="container">
      <div className="mt-5 m-auto w-50">
        <Select
          onChange={handleChange}
          styles={customStyles}
          components={
  
  { Control }}
          options={options}
        />
      </div>
    </div>
  );
};
export default App;

multiple choice

We can configure React Select to allow multiple selections in a single component. This is achieved by including the attribute in the component: select isMultiselect

import { useState } from "react";
import "bootstrap/dist/css/bootstrap.css";
import Select from "react-select";

function App() {
  const options = [
    { value: "blue", label: "Blue" },
    { value: "green", label: "Green" },
    { value: "orange", label: "Orange" },
    { value: "purple", label: "Purple" },
  ];

  const [selectedOption, setSelectedOption] = useState("");

  var handleChange = (selectedOption) => {
    console.log(selectedOption);
    setSelectedOption(selectedOption.value);
  };

  return (
    <div className="container">
      <div className="mt-5 m-auto w-50">
        <Select isMulti onChange={handleChange} options={options} />
      </div>
    </div>
  );
}
export default App;

When we run the code, we will get the following output:

Using React Select with SSR

When you try to use the React Select component with a server-side rendering (SSR) framework such as Next.js, you may receive a reference error like this:

ReferenceError: window is not defined

The browser's window object is not available in SSR until the component is fully mounted. However, React Select relies on the browser object to function. The error occurs because we import the React Select library before mounting the component. window``reference is not defined

We can fix this error in Next.js by using dynamic import feature with disabled option like this: ssr

import dynamic from 'next/dynamic'
const Select = dynamic(() => import("react-select"), {
  ssr: false,
})

You can also implement it in other frameworks using popular packages like the react-no-ssr package.

Asynchronous and fixed options

There are a few other concepts that are important when working with React Select components, one of which is asynchronous components. This component comes in handy when requesting values ​​or options from an API or database query. Asynchronous components include providing useful props such as: select

  • cacheOptions: options for cache acquisition

  • defaultOptions: Set default options before loading remote options

Another component that might come in handy is the fixed options component, which can have fixed options.

in conclusion

In this article, we explored some common use cases for the React Select component. We also learned how to get started with React Select and extend some of its predefined components to suit our needs.

There are tons of features built into the React Select package, some of which will suit your needs, and some of which you will have to customize to suit your use case.

Guess you like

Origin blog.csdn.net/weixin_47967031/article/details/132524863