react-select-multi selection ,select props value - javascript

this is my muti selection component
import React from 'react';
import MultiSelect from "#khanacademy/react-multi-select";
const options = [
{label: "One", value: 1},
{label: "Two", value: 2},
{label: "Three", value: 3},
];
class Consumer extends React.Component {
state = {
selected: [],
}
render() {
const {selected} = this.state;
return <MultiSelect
options={options}
selected={selected}
onSelectedChanged={selected => this.setState({selected})}
/>
}
}
when i click the value, it will be selected in post component, In my view component, I want to show ,how may option I selected using multi selection plugins

<Select
isMulti
/>
this isMulti will handle multi-select
the Select component takes several params. You can make it Creatable and as well as Searchable. you can refer here https://github.com/JedWatson/react-select

Related

Is there any way to trigger a react-select dropdown with jquery from browser?

<select id="selelct-dropdown">
<option value="1">One</option>
<option value="2">Two</option>
</select>
For normal select like this I can change the selected value by using
$('#select-dropdown').val(1)
But when I using react-select there is no select tag nor option tag shown in browser
Is there any way to change the react-select dropdown value by jquery ?
You don't really need to use jquery, instead maintain the state for field and then set state with the value. As per documentation of react-select:
import React, { Component, useState } from 'react'
import Select from 'react-select'
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
const MyComponent = () => {
const [value, setValue] = useState('')
return (
<Select options={options} value={value} onChange={(e) =>
setValue(e.target.value)} />
)
}
export default MyComponent;

How to sync two dropdown lists with different display in React?

I have a list of countries, with key, value, text.
I would like to have two Dropdown (https://react.semantic-ui.com/modules/dropdown/) list, one shows the key, the other the text.
The goal is to allow to choose by key of by text (we can type in the dropdown); if I update one, the other is synchronized immediately.
How can I achieve this ?
<Dropdown
id='form-input-country'
label='Country'
placeholder='Select Country'
fluid
search
selection
options={countryISOOptions} // will show text
/>
<Dropdown
id='form-input-country'
label='Country'
placeholder='Select Country'
fluid
search
selection
options={countryISOOptions} // want to show key + want to sync in both direction
/>
I import countryISOOptions which looks like:
export const countryISOOptions = [
{key: 'AF', value: '4', text: 'Afghanistan'},
{key: 'AL', value: '8', text: 'Albania'},
{key: 'DZ', value: '12', text: 'Algeria'},
...
Maintain 2 option arrays. One for text and other for keys(derived from the first options array). Then maintain just one state and an onChange for both dropdowns and you will be fine.
See working copy of your code.
See code snippet:
import React, { useState } from "react";
import { Dropdown } from "semantic-ui-react";
import "./styles.css";
const countryISOOptions = [
{ key: "AF", value: "4", text: "Afghanistan" },
{ key: "AL", value: "8", text: "Albania" },
{ key: "DZ", value: "12", text: "Algeria" }
];
const countryKeys = countryISOOptions.map(({ key, value }) => ({
value,
text: key
}));
export default function App() {
const [text, setText] = useState("");
const onChangeTextDropdown = (e, d) => {
console.log("onChangeTextDropdown", e.target.value);
console.log("d", d);
setText(d.value);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Dropdown
id="form-input-countryz"
label="Country"
placeholder="Select Country - text"
value={text}
onChange={onChangeTextDropdown}
fluid
search
selection
options={countryISOOptions} // will show text
/>
<Dropdown
id="form-input-country"
label="Country"
placeholder="Select Country - key"
value={text}
onChange={onChangeTextDropdown}
fluid
search
selection
options={countryKeys} // want to show key + want to sync in both direction
/>
</div>
);
}
If you are using controlled version, then each Dropdown is a typical Inputthat supports two props called value and onChange. I'll use hook in the following example,
const [value1, setValue1] = setState('')
const [value2, setValue2] = setState('')
const onValue1Change = e => {
const value = e.target.value
setValue1(value)
if (value === 'key') setValue2('country')
}
return (
<div>
<Dropdown
value={value1}
onChange={onValue1Change}
...
/>
<Dropdown
value={value2}
...
/>
</div>
)

reset value when using react-select

I am using react-select for my select dropdown. The issue I am having is that there is no empty option to reset the dropdown value if the user changes their mind.
Currently I am taking the options and manually adding an empty string, but I feel there must be something already in the library to handle this? I cannot find anything in the docs.
My code looks like the below, and there is a code sandbox here.
import React from "react";
import Select from "react-select";
const App = () => {
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
return <Dropdown options={options} />;
}
const Dropdown = ({ options }) => {
const optionsWithEmptyOption = [{ value: "", label: "" }, ...options];
return <Select options={optionsWithEmptyOption} />;
};
Plase check this out
https://codesandbox.io/s/zow1c?module=/example.js
import React, { Component } from 'react';
import CreatableSelect from 'react-select/creatable';
import { colourOptions } from './docs/data';
export default class CreatableSingle extends Component<*, State> {
handleChange = (newValue: any, actionMeta: any) => {
console.group('Value Changed');
console.log(newValue);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
};
handleInputChange = (inputValue: any, actionMeta: any) => {
console.group('Input Changed');
console.log(inputValue);
console.log(`action: ${actionMeta.action}`);
console.groupEnd();
};
render() {
return (
<CreatableSelect
isClearable
onChange={this.handleChange}
onInputChange={this.handleInputChange}
options={colourOptions}
/>
);
}
}
Empty Unicode
I add line to options, and write between the apostrophes empty unicode like this: ⠀⠀⠀⠀⠀⠀⠀⠀ .. you can mark it but dont see it.
const options = [
{ value: "", label: "⠀" },
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
And I change this:
return <Select options={options} />;
what about const optionsWithEmptyOption = [{ value: null, label: "Select..." }, ...options];
I'm not really good with explanations, but #NicoHaase is right, so here it goes...
as far as I know, you must give a value to value null (if nothing) or string ... same for the label, #1 because of the user UX and second so react-select knows what to display. But if you really need to leave it in black, and you can try to modify in the styles, in order to have the same height as the other options.

Is there any way I can use isMulti without it deleting choices I've already picked? In otherwords, having duplicate/repeated selected options?

Basically, I want to use the react-select library and use the isMulti prop, but the problem with that after selecting an option, the value would be deleted. As you can see below with the provided images, as soon as I click "US: 1" that option would go away. But for the app I'm trying to build, it's certainly possible for a customer to want 2 of the same sizes. Therefore they would pick 2 "US: 1" and it automatically sets the quantity to 2. The problem is that as soon as they pick "US: 1" that option goes away.
This is all I currently have now.
const options = [
{value: 1, label: "US: 1"},
{value: 1.25, label: "US: 1.25"},
{value: 1.5, label: "US: 1.5"},
{value: 1.75, label: "US: 1.75"},
{value: 2, label: "US: 2"},
{value: 2.25, label: "US: 2.25"},
]
class Details extends Component {
state={
selectedOption: []
}
handleChange = (selectedOption) => {
this.setState({ selectedOption: selectedOption });
}
render() {
<Select isMulti={true} isSearchable={true} onClick={value.changeSize(id, selectedOption)} value={selectedOption} onChange={this.handleChange} options={options}></Select>
}
}
Here's an example of what I'm talking about. "US: 1" goes away when it's clicked when I want that option to stay. I'm thinking it alters my "options" array and displaying the new one that doesn't have the clicked option. If I can somehow keep feeding it these original values after every single on onChange that would be awesome. I'm not sure how to dig into the library on how to do it or if it's even possible.
https://www.npmjs.com/package/react-select
Here how I would do it:
class Details extends Component {
state = {
selectedOption: []
};
handleChange = selectedOption => {
const newSelectedOption = selectedOption.map(opt => ({
label: opt.label,
innerValue: opt.value,
// I set a random value because it is needed to be able to delete the value without deleting all of them
value: Math.random()
}));
this.setState({ selectedOption: newSelectedOption });
};
render() {
return (
<Select
isMulti={true}
isSearchable={true}
value={this.state.selectedOption}
onChange={this.handleChange}
options={options}
/>
);
}
}
The idea is not to use value as it's original goal. When a label props is passed to value inside Select it still displays it correctly. So you will base yourself on innerValue and trick react-select.
Here a live example
I guess all you need is to add hideSelectedOptions={false} to <Select />.
Like:
<Select
isMulti={true}
hideSelectedOptions={false}
options={options}
...
/>

send the value as string when selecting the option

I am using react-select for autocomplete and option related field. When i select the option it passes whole that option object as {value: 'abc', label: 'ABC'} but i wanted only to pass the value as a string not the object. Thus, i used getOptionValue but it is not working as expected.
This is what I have done
<Field
name='status'
component={SearchableText}
placeholder="Search..."
options={status}
styles={styles}
getOptionLabel={option => option.label}
getOptionValue={option => option.value}
/>
I have used both getOptionLabel and getOptionValue but is still passing the selected option in object form instead of just the value as string.
Expected one
status: 'active'
Current behavior
status: { value: 'active', label: 'Active'}
I couldn't find getOptionValue in the docs for react-select, but you could always create an adapter around react-select. i.e. create your own Select component that uses react-select's Select component internally. After doing this it becomes possible to create your own getOptionValue. You can use this to make sure the value is a string.
import React from "react";
import Select from "react-select";
class MySelect extends React.Component {
getSelectValue() {
return this.props.options.find(
option => this.props.getOptionValue(option) === this.props.input.value
);
}
render() {
console.log("value", this.props.input.value);
return (
<Select
value={this.getSelectValue()}
onChange={option => {
this.props.input.onChange(this.props.getOptionValue(option));
}}
options={this.props.options}
/>
);
}
}
MySelect.defaultProps = {
getOptionValue: v => v
};
const MyForm = reduxForm({ form: "MyForm" })(
class extends React.PureComponent {
render() {
return (
<Field
name="myCoolSelect"
component={MySelect}
options={[
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
]}
getOptionValue={option => option.value}
/>
);
}
}
);
The above is a basic example of how to get this working. You may want to pass other input or meta props to take advantage of other redux-form features. e.g. onBlur, onFocus, etc. You can see it in action here: https://codesandbox.io/s/6wykjnv32n

Categories

Resources