React-select Onchange Cannot Read Property 'value' of Undefined

Editor'southward note: This react-select tutorial was updated on Jan 12, 2021.

Introduction

Building select elements used to be one of the easiest things to build when working on a web project three or four years ago. At present, in that location is so much that goes into building select elements especially when UI/UX is a high priority.

I has to consider features such every bit on-focus, styling select elements, fetching data from a remote source and the list goes on. You lot may have had this thought when working on that React projection and wished a reusable component existed somewhere in the multiverse.

What is react-select?

Well, luckily for us, Jed Watson started an open source projection, funded past Thinkmill (his company) and Atlassian, chosen react-select.

There were several limitations with version ane of react-select, which gave birth to v2. In this article, we'll be going over the awesome features embodied in react-select  v2 also as getting on a launchpad to innovate us to react-select v2 and how to get started.

Installation and basic usage of react-select

Prerequisites

  1. Yarn/npm  installed
  2. create react app CLI tool installed
  3. A basic agreement of HTML, JavaScript (ES6) and CSS
  4. A basic understanding of React JS and using create react app
  5. A bones understanding of the control line concluding

Installing react-select

With all of those requirements out of the way, information technology's fourth dimension for us add together the react-select package to our existing React application. For the sake of this tutorial, we'll be using the create react-app CLI tool. If you don't already have an existing projection you can provision one like this:

$ yarn create react-app react

Later that is washed, we'll install the react-select bundle from npm:

$ yarn add react-select

At present, we'll take a look at how we can import and use the react-select package in a react awarding.

Basic usage of react-select

In theApp.js file, we import ii items at the top of the file, the react and react-select packet respectively like this:

//App.js  import React from 'react'; import Select from 'react-select';  ...

With those two packages imported, nosotros will be able to have access to the react-select ( <Select />) and likewise extend the React.Component class. In traditional HTML, the <select> tag houses multiple options and values. Our react-select component follows the same convention but the options and values are passed in as props.

//App.js  //Import React and Select   const options = [   { value: 'blues', label: 'Dejection' },   { value: 'rock', label: 'Rock' },   { value: 'jazz', label: 'Jazz' },   { value: 'orchestra' characterization: 'Orchestra' }  ];  form App extends React.Component {   render(){     render (       <Select options = {options} />     );   } }  export default App;

In the code snippet above, we accept our select options as music genres which is passed into the select component equally props. The class App is exported and then that information technology could be rendered to our App component in the DOM. When nosotros run this application we should run into a select element that spans beyond the screen from one end to the other.

App import react select

If yous got that output when you ran your react awarding, kudos. In the coming sections, nosotros'll wait at how we can style the select component to extend its functionalities and make it visually pleasing.

Custom styling your select components

In this section, we'll be discussing how we tin can add beauty and aesthetics to our select component. First things first, nosotros will leverage bootstrap CSS to resize our select component then it doesn't take up the whole width of the web folio. We'll install bootstrap in our projection like so:

$ yarn add [electronic mail protected]

With bootstrap installed, nosotros'll add our styling to our select component.

//App.js  import 'bootstrap/dist/css/bootstrap.css'; //Import react and select   return(   <Select className="mt-iv col-doctor-8 col-first-4"     options = { options }   /> );  ...

For better results, we'll enclose our root DOM element in index.html in a bootstrap container.

<!-- alphabetize.html --> ...  <div class="container">     <div id="root"></div> </div>  ...

This volition give u.s.a. a select chemical element that looks exactly like the prototype below:

Custom styling select components react-select

In this section, nosotros volition look at how we tin can extend the out-of-the-box default styling, and also look at how we can style the entire component. The code cake higher up where we added some bootstrap styling is a adept sit-in of extending the default styling which comes with the select component. To elaborate further, nosotros will tweak the await and feel of the select component:

//App.js  //Import react and select  const customStyles = {   option: (provided, land) => ({     ...provided,     borderBottom: '2px dotted light-green',     color: state.isSelected ? 'yellowish' : 'blackness',     backgroundColor: country.isSelected ? 'greenish' : 'white'   }),   control: (provided) => ({     ...provided,     marginTop: "five%",   }) }  ...  return(   <Select className="col-md-8 col-showtime-iv"     styles = { customStyles }     options = { options }   /> );  ...

There are two component backdrop (option and control) we tweaked to extend and customize the look and feel of the select component. There are many properties provided by react-select which gives us, the consumers, a lot of room to build to our needs and sense of taste. We will talk over custom components in detail in a later on section of this article. For the sake of this section, nosotros will briefly hash out the 2 custom components stated above.

Option: This is the component responsible for displaying the options. By targeting this component nosotros were able to get the select chemical element below:

display options react-select

In the prototype to a higher place we were able to set the background of a selected selection to light-green and alter the text color to xanthous. This was made possible past extending its default styling by spreading information technology into the provided variable …provided

Command: This is the component responsible for the ValueContainer and IndicatorsContainer . With this, we were able to add a margin-pinnacle belongings of 5% which moved the whole select component away from the elevation of the page as shown in the image above as opposed to the very offset image of the select component in the bones usage section.

Using onChange, autofocus, and options Props

In this section, nosotros will have a look at some of the major props we use to customize the functionalities of our select component. Below is an example of how some of these props come in handy.

//App.js  //Import react and select  state = {   selectedOption: null, } handleChange = (selectedOption) => {   this.setState({ selectedOption });   console.log(`Choice selected:`, selectedOption); } return(){   const { selectedOption } = this.country; }  return (   <Select className="mt-4 col-md-half-dozen col-offset-4"   onChange={this.handleChange}   options={options}   autoFocus={true}   /> )

Above is the state managing director prop onChange, which we employ to become the information nearly the currently select item. Supposing nosotros select rock equally an selection in our console we'll get something along the lines of Option selected: {value:"rock", label: "Rock"} this will come in handy when we want to dispense the data gotten from our select component. Other props seen are the options and autoFocus props. The options prop is used to pass in select options to the select component. The options used in the code block above are:

const options = [   { value: 'blues', label: 'Dejection' },   { value: 'rock', label: 'Rock' },   { value: 'jazz', label: 'Jazz' },   { value: 'orchestra' label: 'Orchestra' }  ];

The autoFocus prop which has a data type of boolean is used to add autoFocus to the select component on folio load. To know almost props which are available for use you lot tin can check out the props documentation for react-select.

Custom components

Under styles and states, we discussed ii custom components (option and control) which nosotros used to extend the select styling. In this section, we'll take a wait at some other custom component called the Custom SingleValue . This custom component does what our regular select component does but we're going to add a little bit of finesse. In our App.js file, nosotros'll import the React and Select packages from react and react-select respectively like so:

//App.js  import React, { type ElementConfig } from 'react'; import Select, { components } from 'react-select'; ...

By the time we are done, we accept a finished product that looks something similar this:

customizing states and styles react-select

In the code block below, we define our custom component SingleValue equally a method which extends the base component in the react-select bundle. In our App course, we have a couple of props and functions which contribute to the functionality (equally shown in the image above) such every bit:

handleChange: This method is triggered by a land manager prop called the onChange . This method is responsible for storing the value of the selected selection in our country object called selectedOption

styles: In this prop, we extend the style modifier method singleValue where we modify the styling already attainable to us past default past spreading default styles into the base object. The line responsible for adding a groundwork color to each selected option is the groundwork: this.country.selectedOption.value where we become the current option selected from the state and use it to update the background

components: In the component prop we pass in the SingleValue component, the main function of the component is to brandish in the input for a single select.

options: The options prop that we all know by now is how nosotros laissez passer in our array object of select items which in this case are colors like so.

className: In this prop is where we add our bootstrap styling to position our select component abroad from the top margin as well as centralize our select component nicely.

//App.js     const SingleValue = ({ children, ...props }) => (    <components.SingleValue {...props}>      {children}    </components.SingleValue>  );    class App extends React.Component {    state = {};    state = {      selectedOption: null,    }    handleChange = (selectedOption) => {      this.setState({ selectedOption });    }    render() {      return (        <Select            className="mt-4 col-md-vi col-kickoff-4"            onChange={this.handleChange}            styles={{ singleValue: (base) => ({ ...base of operations, padding: 5, borderRadius: 5, background: this.land.selectedOption.value, color: 'white', brandish: 'flex' }) }}            components={{ SingleValue }}            options={colourOptions}          />      );    }  }  consign default App;

Using built-in blithe components

In this section, we will have a expect at how nosotros tin add together a little blitheness to our react select component. All we need to add together animation to our select component is to import the animated component which in this case is named makeAnimated so reference makeAnimated in our component's props similar and then:

//App.js  import React from 'react'; import Select, { components } from 'react-select'; import makeAnimated from 'react-select/lib/animated'; import 'bootstrap/dist/css/bootstrap.css';  const colourOptions = [] //our array of colours  class App extends React.Component {   render(){     return (       <Select         className="mt-iv col-md-6 col-outset-4"         components={makeAnimated()}         isMulti         options={colourOptions}         />     );   } }  export default App;

TheisMulti prop is used to make us select more than one option at once as we can see in the gif below:

TheisMulti prop react-select

Other concepts

At that place are other concepts which are important to know in regards to working with the react-select component. One of which is the Async component which is imported like this:

import Async from 'react-select/lib/Async';

This component comes in handy when we want to request our select values or options from an API or a database query. This component helps to add Async belongings to our select component which comes bootstrapped with helper props such equally
cacheOptions for caching options and also an outcome listener props onInputChange.This component can be implemented through the use of callbacks or promises.

Another component which may come up in handy is the stock-still options component. This component makes it possible to take fixed options as already selected values which can't be removed.

Decision

In the grade of this article, we take learned some common use cases of the react-select component, how to get started and also how to extend some of the predefined components to suit our needs. At that place are a plethora of functionalities built into the react-select package, some of which will fit your needs, some of which you'll demand to customize to fit your employ example. Here'due south a link to the official documentation to go your hands muddied. Feel free to leave a comment if you lot accept questions or get stuck I'll lend a helping mitt.

Total visibility into production React apps

Debugging React applications can exist difficult, specially when users experience bug that are difficult to reproduce. If you lot're interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, attempt LogRocket. LogRocket Dashboard Free Trial Banner

LogRocket is like a DVR for spider web and mobile apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you tin can aggregate and written report on what state your application was in when an issue occurred. LogRocket also monitors your app's functioning, reporting with metrics similar client CPU load, client retentiveness usage, and more than.

The LogRocket Redux middleware bundle adds an extra layer of visibility into your user sessions. LogRocket logs all actions and country from your Redux stores.

Modernize how you debug your React apps — first monitoring for free.

mitchellcatir1937.blogspot.com

Source: https://blog.logrocket.com/getting-started-with-react-select/

0 Response to "React-select Onchange Cannot Read Property 'value' of Undefined"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel