React-Select: Getting multiple onChange values from dropdown - reactjs

import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'all', label: 'all' },
{ value: 'destroyed', label: 'Destroyed' },
{ value: 'damaged', label: 'Damaged' },
{ value: 'physicalDamage', label: 'PhysicalDamage' }
]
class SearchFilters extends React.Component {
_onChange = (e, options) => {
const onChangeData = {
value: e.value,
name: e.label,
result: options.find(item => item.value === e.value)
};
console.log(onChangeData.value);
return onChangeData;
};
render(){
return(
<div>
<Select
options={options}
onChange={e => this._onChange(e, options)}
isMulti={true}
/>
</div>
)
}
}
export default SearchFilters
From the above code if isMulti is false in select, I'm able to print the value of the selected option in console, but if I change it to true, I get the value as undefined.
I need help in fixing this. Thanks in advance.
Ouput:

Related

How can I update State in React using the React-Select Component and User Selection?

I'm trying to update a State in my project based on a User Selection from a dropdown menu.
I passed the 2 states (roomType & occupants) along with their setter/change functions (onRoomTypeChange & onOccupantsChange) from the parent Component.
I’ve tried to read through the React Select Library, but having trouble.
Wondering if someone could point me in the right direction.
import React from 'react';
import Select from 'react-select';
const roomOptions = [
{ value: 'Standard', label: 'Standard' },
{ value: 'Delux', label: 'Delux' }
];
const occupantOptions = [
{ value: 1, label: '1' },
{ value: 2, label: '2' },
{ value: 3, label: '3' },
{ value: 4, label: '4' },
];
const RoomDetails = (props) => {
let {
roomType,
onRoomTypeChange,
occupants,
onOccupantsChange
} = props;
const handleChange = (e) => {
onRoomTypeChange(e.target.value);
};
return (
<div>
<div className="form-group">
<label className="select-label">Room Type: {roomType} </label>
<Select
// value={e.target.value}
onChange={handleChange}
options={roomOptions}
theme={theme}
/>
<label className="select-label">Guests: {occupants}</label>
<Select
value={occupants}
onDatachange={onOccupantsChange}
options={occupantOptions}
theme={theme}
/>
</div >
</div>
);
};
export default RoomDetails;
I resolved the and wanted to post an update:
I had installed another package called “react-dropdown-select” that I removed from my package.json, I believe was interfering with my react-select package .
The return object was not an event, it was the selected object from the corresponding options array. I destructured the value property in the parameter and used the Setter Function on the value only.
I originally included a Value= attribute on the Select Component, which was set to my current state value
<Select
value={stateProperty}
/>
When I removed the Value attribute, the bug was gone
(Here is the solution)
import React from 'react';
import Select from 'react-select';
const roomOptions = [
{ value: 'Standard', label: 'Standard' },
{ value: 'Delux', label: 'Delux' }
];
const occupantOptions = [
{ value: 1, label: '1' },
{ value: 2, label: '2' },
{ value: 3, label: '3' },
{ value: 4, label: '4' },
];
const RoomDetails = (props) => {
let {
onRoomTypeChange,
onOccupantsChange
} = props;
const handleChangeRoom = ({ value }) => {
console.log(value);
onRoomTypeChange(value);
};
const handleChangeOccupants = ({ value }) => {
console.log(value);
onOccupantsChange(value);
};
return (
<div>
<div className="form-group mb-2">
<span className="form-label mt-3">Room Type </span>
<Select
onChange={handleChangeRoom}
options={roomOptions}
theme={theme}
placeholder="Room Type"
/>
<span className="form-label mt-3">Guests</span>
<Select
onChange={handleChangeOccupants}
options={occupantOptions}
theme={theme}
placeholder="Number of Guests"
/>
</div >
</div>
);
};
export default RoomDetails;

How can i render the selected option using React_Select?

I made a example in following:
I am new to React and i am using React Select
import React, { Component, Fragment } from "react";
import Select from 'react-select';
const options = [
{ value: 'blues', label: 'Blues' },
{ value: 'rock', label: 'Rock' },
{ value: 'jazz', label: 'Jazz' },
{ value: 'orchestra', label: 'Orchestra' }
];
class DropDown3 extends Component {
constructor(props){
super(props)
this.state = {
selectOptions : [],
id: "",
name: ''
}
}
handleChange = (selectedOption) =>
{
console.log("selected",selectedOption)
this.setState({ selectedOption });
};
render()
{
const { selectedOption } = this.state;
return (
<Fragment>
<Select
options = {options}
onChange ={this.handleChange}
value = {selectedOption}
defaultValue={{ value: 'jazz', label: 'Jazz' }}
/>
<div>Hello you select {this.state.selectedOption}</div>
</Fragment>
);
}
}
export default DropDown3;
what i want is to display what i have selected in the dropdown so that i can pass it to another component.
The abouve code didnt run everytime i choose a menu
and it run only i comment out the
"Hello you select {this.state.selectedOption}"
thanks
You should initialize the selectedOption in the state, and when you update the state you should take the value of the selectedOption object.
import React, { Component, Fragment } from "react";
import Select from "react-select";
const options = [
{ value: "blues", label: "Blues" },
{ value: "rock", label: "Rock" },
{ value: "jazz", label: "Jazz" },
{ value: "orchestra", label: "Orchestra" }
];
class DropDown3 extends Component {
constructor(props) {
super(props);
this.state = {
selectOptions: [],
selectedOption: "",
id: "",
name: ""
};
}
handleChange = (selectedOption) => {
console.log("selected", selectedOption);
this.setState({ selectedOption: selectedOption.value });
};
render() {
const { selectedOption } = this.state;
return (
<Fragment>
<Select
options={options}
onChange={this.handleChange}
value={selectedOption}
defaultValue={{ value: "jazz", label: "Jazz" }}
/>
<div>Hello you select {this.state.selectedOption}</div>
</Fragment>
);
}
}
export default DropDown3;

How to display multiple selected values from a dropdown in React

I'm new to React and I wanted to create a dropdown which can select multiple values. For that I used the react-select plugin. In my React dev tool the selected values are getting stored but I'm not able to display all the selected values.
Any help is highly appreciated.
TIA
import React, { useState } from "react";
import Select from 'react-select'
const options = [
{ value: 'React', label: 'React' },
{ value: 'Vue', label: 'Vue' },
{ value: 'Angular', label: 'Angular' },
{ value: 'Java', label: 'Java' },
]
const [skills, setSkills] = useState([]);
const handleChange = (skill) => {
setSkills({skill})
console.log("skills", skill);
}
return (
<>
<h2>Please select all your skills</h2>
<form>
<Select
options={options}
onChange={handleChange}
isMulti={true}
value={value}
/>
<button>Next</button>
</form>
</>
)
}
export default UserSkills;
When I'm commenting isMulti prop, I'm getting that one selected value, but I'm not getting anything with isMulti prop.
You are controlling the Select component by giving it a value, and since you are not updating value in the handleChange function it will not be updated.
You could use the skills array as value instead and it will update as expected.
CodeSandbox
const options = [
{ value: "React", label: "React" },
{ value: "Vue", label: "Vue" },
{ value: "Angular", label: "Angular" },
{ value: "Java", label: "Java" }
];
function UserSkills() {
const [skills, setSkills] = useState([]);
const handleChange = (skills) => {
setSkills(skills || []);
};
return (
<>
<h2>Please select all your skills</h2>
<form>
<Select
options={options}
onChange={handleChange}
value={skills}
isMulti
/>
<button>Next</button>
</form>
</>
);
}
export default UserSkills;

Can't deselect initial values from Select component with options and values as an object

I can't unselect the default values I have set in state.
I'm pulling from an example in Grommet's codesandbox.
Only change thus far is adding an object array instead of an array of strings. See VALUE prop in docs mention object array..
const OPTIONS = [
{
label: "Expansion",
value: "1"
},
{
label: "Rollout",
value: "2"
}
];
export default class extends Component {
state = {
value: [
{
label: "Rollout",
value: "2"
}
],
options: OPTIONS
};
render() {
const { options, value } = this.state;
return (
<Select
multiple={true}
value={value}
labelKey="label"
valueKey="value"
onSearch={searchText => {
const regexp = new RegExp(searchText, "i");
this.setState({ options: OPTIONS.filter(o => o.match(regexp)) });
}}
onChange={event => {
console.log({ event });
this.setState({
value: event.value,
options: OPTIONS
});
}}
options={options}
/>
);
}
}
In the logs, I'm getting selected: [ -1, 1 ] when I attempt to unselect the Rollout option, and Rollout is still visually highlighted/selected in the view.
Here is your working code, You need to check if currently clicked value is already there in selection then remove it from values and if it is not in selected then add in values.
I changed onChange function as below.
Let me know if any issues.
import React, { Component } from "react";
import { Select } from "grommet";
import SandboxComponent from "./SandboxComponent";
const OPTIONS = [
{
label: "Expansion",
value: "1"
},
{
label: "Rollout",
value: "2"
}
];
export default class extends Component {
state = {
value: [
{
label: "Rollout",
value: "2"
}
],
options: OPTIONS
};
render() {
const { options, value } = this.state;
return (
<Select
multiple={true}
value={value}
labelKey="label"
valueKey="value"
selected={0}
onSearch={searchText => {
const regexp = new RegExp(searchText, "i");
this.setState({ options: OPTIONS.filter(o => o.match(regexp)) });
}}
onChange={event => {
let isExist = value.find(item => {
return item.value === event.option.value;
});
let newValue;
if (isExist) {
newValue = value.filter(item => {
return item.value !== event.option.value;
});
} else {
newValue = value;
newValue.push(event.option);
}
this.setState({
value: newValue
});
}}
options={options}
/>
);
}
}

How to set & get only value string in react-select's state

I have tried following code, but it sets & gets the entire json of the selected value. How to set & get only the value of the selectedOption & not the entire json of the selectedOption from state after the selection. The code given in the the official documentation is given below:
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class App extends React.Component {
state = {
selectedOption: null,
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}
you should bind handleChange in constructor
because react-reselect by default bind all methods in code line https://github.com/JedWatson/react-select/blob/master/.babelrc#L4
transform-class-properties in .babelrc bind by default
Do bind like this:
https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56
And the answer to your question here:
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class App extends React.Component {
state = {
selectedOption: null,
}
constructor() {
this.handleChange = this.handleChange.bind(this)
}
handleChange = (selectedOption) => {
console.log('selectedOption', selectedOption); // log here before set state
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}
Best way is to actually make your component wrapper around react-select component example:
const CustomSelect = ({onChange, options, value, isMulti}) => {
return(
<Select
options={options}
onChange={(val) => isMulti
? onChange(val.map((c) => c.value))
: onChange(val.value)
}
value={isMulti
? options.filter((c) => value.includes(c.value))
: options.find((c) => c.value === value)
}
isMulti={isMulti}
/>
)
}
Extract selected value and pass to handler
onChange={(e) => this.handleChange(e.value)}
...
import React from 'react';
import Select from 'react-select';
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
];
class App extends React.Component {
state = {
selectedOption: null,
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={(e) => this.handleChange(e.value)}
options={options}
/>
);
}
}

Resources