How to make react-select always display the option list
By default it toggles when you click on the array button or when you start typing something
var Select = require('react-select');
var options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' }
];
function logChange(val) {
console.log('Selected: ', val);
}
<Select
name="form-field-name"
value="one"
options={options}
onChange={logChange}
/>
Use props
defaultMenuIsOpen
This will make dropdown open by default
<Select
defaultMenuIsOpen
name="form-field-name"
value="one"
options={options}
onChange={logChange}
/>
you can do one thing if you want to show all option without click on select list.
open select on Focus and give default Focus to select on it's mount as bellow.
var Select = require('react-select');
var options = [
{ value: 'one', label: 'One' },
{ value: 'two', label: 'Two' }
];
function logChange(val) {
console.log('Selected: ', val);
}
<Select
name="form-field-name"
value="one"
options={options}
onChange={logChange}
openOnFocus={true}
autofocus={true}
/>
After selection of option from list,Selected value will be displayed and others value automatically dropped.
UPD 2023
Just use menuIsOpen, defaultMenuIsOpen, menuIsOpen attributes:
<Select
defaultMenuIsOpen
autoFocus
menuIsOpen
...
/>
Related
I have below list in react.
<select
id="sponsor"
name="sponsor"
className="form-control"
placeholder="Sponsor"
}
>
<option value="" selected>Please select the sponsor</option>
{
active && result.map((sponsor:Sponsor,index:number)=>
<option value={sponsor.id} >{sponsor.name}</option>
)
}
</select>
it is working perfectly fine. now I need to change it to searchable list. I did below.
import VirtualizedSelect from 'react-virtualized-select'
import "react-virtualized-select/styles.css";
import 'react-virtualized/styles.css'
<VirtualizedSelect
id="sponsor"
name="sponsor"
className="form-control"
placeholder="Sponsor"
options={ active && result.map((sponsor:Sponsor,index:number)=>
{sponsor.name}
)}
>
</VirtualizedSelect>
now nothing is coming in list. basically my requirement is to make list searchable and insert data of API into that list.
Could you please help me with same? Any other option will also be very helpful
Edit1:-
I need list like below. first line "Please choose sponsor"
according to VirtualizedSelect docs here https://www.npmjs.com/package/react-virtualized-select, the component accept array of objects like :
const options = [
{ label: "One", value: 1 },
{ label: "Two", value: 2 },
{ label: "Three", value: 3, disabled: true }
// And so on...
]
not array of strings and I think this is way its not working, I'd suggest to change your code to :
<VirtualizedSelect
id="sponsor"
name="sponsor"
className="form-control"
placeholder="Sponsor"
options={ active && result.map((sponsor:Sponsor,index:number)=>
({label: sponsor.name, value: sponsor.name})
)}
>
</VirtualizedSelect>
I have two radio buttons: radio1 and radio2, and one select input.
The Select values depend on the radio buttons.
I want to set the select value to 1 whenever I select radio1.
I've tried setting defaultValue and value to the select input but every time I switch back to radio1 from radio2, the value is always set to 2.
Here's my code, any help is truly appreciated:
import "./styles.css";
import { useState } from "react";
const selectItems = {
name: "size",
fields: {
radio1: [
{
value: "1"
},
{
value: "2"
}
],
radio2: [
{
value: "2"
},
{
value: "3"
},
{
value: "4"
}
]
}
};
const App = () => {
const [values, setValues] = useState({ radio: "radio1", select: "2" });
const handleChange = (name, value) => {
setValues((s) => {
return { ...s, [name]: value };
});
};
return (
<div className="App">
<h2>
How do I make the Select always be '1' when Radio1 is selected after
selecting Radio2?
</h2>
<input
type="radio"
id="radio1"
value="radio1"
name="radio"
onChange={() => handleChange("radio", "radio1")}
/>
<label htmlFor="radio1">Radio1</label>
<input
type="radio"
id="radio2"
value="radio2"
name="radio"
onChange={() => handleChange("radio", "radio2")}
/>
<label htmlFor="radio2">Radio2</label>
<br />
<select
id="size"
name="size"
onChange={(e) => handleChange("select", e.target.value)}
>
{selectItems.fields[values.radio].map(({ value }) => {
return (
<option key={value} value={value}>
{value}
</option>
);
})}
</select>
</div>
);
};
export default App;
example: https://codesandbox.io/s/goofy-danny-p1l3s?file=/src/App.js:0-1460
Edit:
As suggested by some answers, I have tried setting 'selected' as true. In fact, I have tried this before and forgot to mention it on my question. This seem to work, it gives me the desired effect on the browser, but then I get this error on the console:
Warning: Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>.
The main problem here is <option> is taking the same key value. When you are selecting radio2, key becomes 2.Then you are selecting radio1 and for that <select> has <option> with key=2. That is why <select> value not changing. The proof is if you change all <option> values unique, example for radio1 {1, 2} and for radio2 {3, 4, 5} your code works fine.
There may be multiple workarounds but the proper way to solve this is having unique id for each of the <option>.
const selectItems = {
name: "size",
fields: {
radio1: [
{
value: "1",
id: 1
},
{
value: "2",
id: 2
}
],
radio2: [
{
value: "2",
id: 3
},
{
value: "3",
id: 4
},
{
value: "4",
id: 5
}
]
}
};
------------------------------------------
<select
id="size"
name="size"
onChange={(e) => handleChange("select", e.target.value)}
>
{selectItems.fields[values.radio].map(({ value, id }) => {
return (
<option key={id} value={value}>
{value}
</option>
);
})}
</select>
Element <option> has property selected that is responsible for determining which item is currently selected.
That is the property that will help you to decide which item should be currently selected at any given time.
To illustrate this, I have added the following check to your element:
<element selected={value === '1'}> and now every time you change the radio from radio1 to radio2 the value changes to 1 as you asked in your question.
My response here is more of a guidance, do not treat as exact step by step instruction as I did not think of any other ways that your program might work or handle different behaviours.
You can define a new state which is called defaultValue. As a result, with setting the value property of select tag by defaultValue, you can achieve your goal:
const App = () => {
const [values, setValues] = useState({ radio: "radio1", select: "2" });
const [defaultValue, setDefaultValue] = useState(0);
const handleChange = (name, value) => {
setValues((s) => {
return { ...s, [name]: value };
});
};
useEffect(() => {
setDefaultValue(selectItems.fields[values.radio][0].value);
}, [values]);
return (
<div className="App">
<h2>
How do I make the Select always be '1' when Radio1 is selected after
selecting Radio2?
</h2>
<input
type="radio"
id="radio1"
value="radio1"
name="radio"
onChange={() => handleChange("radio", "radio1")}
/>
<label for="radio1">Radio1</label>
<input
type="radio"
id="radio2"
value="radio2"
name="radio"
onChange={() => handleChange("radio", "radio2")}
/>
<label for="radio2">Radio2</label>
<br />
<select
id="size"
name="size"
value={defaultValue}
onChange={(e) => handleChange("select", e.target.value)}
>
{selectItems.fields[values.radio].map(({ value }, index) => {
return (
<option key={value} value={value}>
{value}
</option>
);
})}
</select>
</div>
);
};
export default App;
I am new to React. I'm using react-select and I've used the following code. The dropdown is displayed but I'm unable to see names and unable to view after selecting.
<Select
variant="outlined"
margin="normal"
fullWidth
value={this.state.selected}
options={RewardAutomationsList}
name="selected"
onChange={this.handleChange}
placeholder='None'
>
{RewardAutomationsList.map((option) => (
<option key={option.id} value ={option.name} label={option.name}>
{option.name}
</option>
))}
</Select>
handleChange = event => {
this.setState({
selected: event.name
});
};
The RewardAutomationsList looks like this:
RewardAutomationsList:
0:{name: "TEST 1 (INR 100)", id: "123"}
1:{name: "test 2 (INR 250)", id: "456"}
Can someone help with this?
same npm package use like this block code.
import React, { Component } from 'react'
import Select from 'react-select'
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const MyComponent = () => (
<Select options={options} />
)
react-select accepts an array of objects having label and value keys. Your option objects in RewardAutomationsList have id and name keys, so it can't be displayed. You need to change them.
Also, when you subscribe to change events with react-select's onChange prop, the callback function you provide receives the selectedOption, not the event.
The following should work:
const RewardAutomationsList = [
{ label: "TEST 1 (INR 100)", value: "123" },
{ label: "test 2 (INR 250)", value: "456" },
];
class App extends React.Component {
state = {
selected: null,
}
handleChange = (selectedOption) => {
this.setState({
selected: selectedOption,
});
};
render() {
return (
<React.Fragment>
<Select
fullWidth
margin="normal"
name="selected"
onChange={this.handleChange}
options={RewardAutomationsList}
placeholder="None"
value={this.state.selected}
variant="outlined"
/>
{/* It's not necessary and it's only here to show the current state */}
<pre>{JSON.stringify(this.state, null, 2)}</pre>
</React.Fragment>
);
}
}
I'm new to react and trying to learn on my own. I started using react-select to create a dropdown on a form and now I'm trying to pass the value of the option selected. My state looks like this.
this.state = {
part_id: "",
failure: ""
};
Then in my render
const {
part_id,
failure
} = this.state;
My form looks has 2 fields
<FormGroup>
<Label for="failure">Failure</Label>
<Input
type="text"
name="failure"
placeholder="Failure"
value={failure}
onChange={this.changeHandler}
required
/>
</FormGroup>
<FormGroup>
<Label for="part_id">Part</Label>
<Select
name="part_id"
value={part_id}
onChange={this.changeHandler}
options={option}
/>
</FormGroup>
the changeHandler looks like this
changeHandler = e => {
this.setState({ [e.target.name]: e.target.value });
};
The change handler works fine for the input but the Select throws error saying cannot read property name. I went through the API docs and came up with something like this for the Select onChange
onChange={part_id => this.setState({ part_id })}
which sets the part_id as a label, value pair. Is there a way to get just the value? and also how would I implement the same with multiselect?
The return of react-select onChange event and the value props both have the type as below
event / value:
null | {value: string, label: string} | Array<{value: string, label: string}>
So what the error means is that you can't find an attribute of null (not selected), or any attributes naming as name (you need value or label)
For multiple selections, it returns the sub-list of options.
You can find the related info in their document
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
];
Update
For your situation (single selection)
option having type as above
const option = [
{value: '1', label: 'name1'},
{value: '2', label: 'name2'}
]
state save selected value as id
changeHandler = e => {
this.setState({ part_id: e ? e.value : '' });
};
pick selected option item via saved id
<Select
name="part_id"
value={option.find(item => item.value === part_id)}
onChange={this.changeHandler}
options={option}
/>
For multiple selections
state save as id array
changeHandler = e => {
this.setState({ part_id: e ? e.map(x => x.value) : [] });
};
pick via filter
<Select
isMulti // Add this props with value true
name="part_id"
value={option.filter(item => part_id.includes(item.value))}
onChange={this.changeHandler}
options={option}
/>
onChange function is a bit different in react-select
It passes array of selected values, you may get first one like
onChange={([selected]) => {
// React Select return object instead of value for selection
// return { value: selected };
setValue(selected)
}}
I have tried the above solutions but some of these solutions does update the state but it doesn't gets rendered on the Select value instantly.
Herewith a demo example:
this.state = {
part_id: null,
};
handleUpdate = (part_id) => {
this.setState({ part_id: part_id.value }, () =>
console.log(`Option selected:`, this.state.part_id)
);
};
const priceOptions = [
{ value: '999', label: 'Item One' },
{ value: '32.5', label: 'Item Two' },
{ value: '478', label: 'Item Three' }
]
<Select
onChange={this.handleUpdate}
value={priceOptions.find(item => item.value === part_id)}
options={priceOptions}
placeholder={<div>Select option</div>}
/>
The example code in the react-bootstrap site shows the following. I need to drive the options using an array, but I'm having trouble finding examples that will compile.
<Input type="select" label="Multiple Select" multiple>
<option value="select">select (multiple)</option>
<option value="other">...</option>
</Input>
You can start with these two functions. The first will create your select options dynamically based on the props passed to the page. If they are mapped to the state then the select will recreate itself.
createSelectItems() {
let items = [];
for (let i = 0; i <= this.props.maxValue; i++) {
items.push(<option key={i} value={i}>{i}</option>);
//here I will be creating my options dynamically based on
//what props are currently passed to the parent component
}
return items;
}
onDropdownSelected(e) {
console.log("THE VAL", e.target.value);
//here you will see the current selected value of the select input
}
Then you will have this block of code inside render. You will pass a function reference to the onChange prop and everytime onChange is called the selected object will bind with that function automatically. And instead of manually writing your options you will just call the createSelectItems() function which will build and return your options based on some constraints (which can change).
<Input type="select" onChange={this.onDropdownSelected} label="Multiple Select" multiple>
{this.createSelectItems()}
</Input>
My working example
this.countryData = [
{ value: 'USA', name: 'USA' },
{ value: 'CANADA', name: 'CANADA' }
];
<select name="country" value={this.state.data.country}>
{this.countryData.map((e, key) => {
return <option key={key} value={e.value}>{e.name}</option>;
})}
</select>
bind dynamic drop using arrow function.
class BindDropDown extends React.Component {
constructor(props) {
super(props);
this.state = {
values: [
{ name: 'One', id: 1 },
{ name: 'Two', id: 2 },
{ name: 'Three', id: 3 },
{ name: 'four', id: 4 }
]
};
}
render() {
let optionTemplate = this.state.values.map(v => (
<option value={v.id}>{v.name}</option>
));
return (
<label>
Pick your favorite Number:
<select value={this.state.value} onChange={this.handleChange}>
{optionTemplate}
</select>
</label>
);
}
}
ReactDOM.render(
<BindDropDown />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
// on component load, load this list of values
// or we can get this details from api call also
const animalsList = [
{
id: 1,
value: 'Tiger'
}, {
id: 2,
value: 'Lion'
}, {
id: 3,
value: 'Dog'
}, {
id: 4,
value: 'Cat'
}
];
// generage select dropdown option list dynamically
function Options({ options }) {
return (
options.map(option =>
<option key={option.id} value={option.value}>
{option.value}
</option>)
);
}
<select
name="animal"
className="form-control">
<Options options={animalsList} />
</select>
Basically all you need to do, is to map array. This will return a list of <option> elements, which you can place inside form to render.
array.map((element, index) => <option key={index}>{element}</option>)
Complete function component, that renders <option>s from array saved in component's state. Multiple property let's you CTRL-click many elements to select. Remove it, if you want dropdown menu.
import React, { useState } from "react";
const ExampleComponent = () => {
const [options, setOptions] = useState(["option 1", "option 2", "option 3"]);
return (
<form>
<select multiple>
{ options.map((element, index) => <option key={index}>{element}</option>) }
</select>
<button>Add</button>
</form>
);
}
component with multiple select
Working example: https://codesandbox.io/s/blue-moon-rt6k6?file=/src/App.js
A 1 liner would be:
import * as YourTypes from 'Constants/YourTypes';
....
<Input ...>
{Object.keys(YourTypes).map((t,i) => <option key={i} value={t}>{t}</option>)}
</Input>
Assuming you store the list constants in a separate file (and you should, unless they're downloaded from a web service):
# YourTypes.js
export const MY_TYPE_1="My Type 1"
....
You need to add key for mapping otherwise it throws warning because each props should have a unique key. Code revised below:
let optionTemplate = this.state.values.map(
(v, index) => (<option key={index} value={v.id}>{v.name}</option>)
);
You can create dynamic select options by map()
Example code
return (
<select className="form-control"
value={this.state.value}
onChange={event => this.setState({selectedMsgTemplate: event.target.value})}>
{
templates.map(msgTemplate => {
return (
<option key={msgTemplate.id} value={msgTemplate.text}>
Select one...
</option>
)
})
}
</select>
)
</label>
);
I was able to do this using Typeahead. It looks bit lengthy for a simple scenario but I'm posting this as it will be helpful for someone.
First I have created a component so that it is reusable.
interface DynamicSelectProps {
readonly id: string
readonly options: any[]
readonly defaultValue: string | null
readonly disabled: boolean
onSelectItem(item: any): any
children?:React.ReactNode
}
export default function DynamicSelect({id, options, defaultValue, onSelectItem, disabled}: DynamicSelectProps) {
const [selection, setSelection] = useState<any[]>([]);
return <>
<Typeahead
labelKey={option => `${option.key}`}
id={id}
onChange={selected => {
setSelection(selected)
onSelectItem(selected)
}}
options={options}
defaultInputValue={defaultValue || ""}
placeholder="Search"
selected={selection}
disabled={disabled}
/>
</>
}
Callback function
function onSelection(selection: any) {
console.log(selection)
//handle selection
}
Usage
<div className="form-group">
<DynamicSelect
options={array.map(item => <option key={item} value={item}>{item}</option>)}
id="search-typeahead"
defaultValue={<default-value>}
disabled={false}
onSelectItem={onSelection}>
</DynamicSelect>
</div>