React Grommet Select - passing in object data as options - reactjs

I am using Grommet v2 components and trying to mirror the display used in the Select 'Seasons' example in Grommet's storybook.
The field appears like this:
The difference is my data needs to separate label and value:
const Options = [
{
label: "S01",
value: "283736"
},
{
label: "S02",
value: "293774"
},
instead of using the default:
const Options = [
"S01",
"S02",
Here is an example on Codesandbox
The object format was used in Grommet's example of ObjectMultiSelect in their storybook. I found the Select component needs
labelKey="label" and valueKey="value" to load the objects as options, but adding these two props seems to break the component options.
I would like for the data passed in to resemble
const Options = [
{
label: "S01",
value: "283736"
},
{
label: "S02",
value: "293774"
},
and still have the options displayed as above.

<Select
options={[
{
lab: "S01",
val: "283736"
},
{
lab: "S02",
value: "293774"
}
]}
labelKey="lab"
dropHeight="large"
name="primaryServer"
value={this.props.values.primaryServer}
placeholder="Select Primary Server"
emptySearchMessage={"No Servers Available"}
onChange={({ option }) => {
console.log(option.lab)
console.log(option.val)
}}
/>
// Output // S01 // 283736
// This worked for me. labelKey="lab" is required.

Related

Use Antd select with mode tags but allow only one selection

I'm using Antd Select for a project. My requirement is to use Select with mode='tags' as it allows user to create a new option, but I also want user to select only one option at a time (i.e either have a new option created or have an existing option selected shown in the select box). I tried using autoClearSearchValue but is of no use.
Appreciate the help.
Make the <Select /> to be controlled component.
I write an example, the key logic is to control the selected value in onChange function;
export default function MyTest() {
const [data, setData] = React.useState<string[]>([]);
return (
<div>
<Select
mode="tags"
onChange={(value, options) => {
// update data only when select one item or clear action
if (options?.length === 0 || options?.length === 1) {
setData(value);
}
}}
value={data}
options={[
{
label: "0",
value: "0",
},
{
label: "1",
value: "1",
},
{
label: "2",
value: "2",
},
]}
/>
</div>
);
}

How to make MUI's Autocomplete display the label from the matching value in props.options?

I have a multilingual website where there are certain Autocompletes whose options array need to have its items labels translated, which is done very easily.
However, it would be harder to update the current chosen value, stored elsewhere. Since Autocomplete uses the label from the value prop instead of using the item of same ID within options, it ends up like this:
const vehicles = [
{ id: 1, label: "Car" },
{ id: 2, label: "Bus" }
];
const currentVehicleValue = {
id: 2,
label: "Ônibus"
};
export default function ComboBox() {
return (
<Autocomplete
disablePortal
id="combo-box-demo"
options={vehicles}
value={currentVehicleValue}
renderInput={(params) => <TextField {...params} label="Vehicle" />}
/>
);
}
Is there a way to just tell Autocomplete to use the label inside the options prop instead of the one within the value
demo
EDIT: I mean to have the label within options being shown while I don't type anything. As in, the language changed, the options were translated, but the currentValue was not, so it would be nice to have the Autocomplete use the label from the matching item within options as long as I don't type anything.
Edit after clarification
You can change how the <TextField/> is rendered by tweaking the props it receives.
In the example below, I find the currentVehicle by its id and change the inputProps.value to be the vehicle label.
Also, to ensure MUI finds the currentValue correctly within the options, you will need to use the isOptionEqualToValue to compare the options ids instead of strict equality
const vehicles = [
{ id: 1, label: "Car" },
{ id: 2, label: "Bus" }
];
const currentVehicleValue = {
id: 2,
label: "Ônibus"
};
function compareValueToOption(option, value) {
return option.id === value.id;
}
function ComboBox() {
return (
<Autocomplete
disablePortal
id="combo-box-demo"
options={vehicles}
value={currentVehicleValue}
renderInput={ComboBoxInput}
isOptionEqualToValue={compareValueToOption}
/>
);
}
function ComboBoxInput(props) {
const currentVehicle = vehicles.find(
(vehicle) => vehicle.id === currentVehicleValue.id
);
props.inputProps.value = currentVehicle.label;
return <TextField {...props} label="Vehicle" />;
}
Here's a working demo

Unable to maintain formik state values within react-select component

I am using react-select (multi-values) with Formik together with Material-UI Stepper (wizard) and have the values stored successfully within Formik's initialStates values but when I advance to the next screen, using conditional component rendering within my Stepper and then return back one screen where my react-select component resides, it no longer holds/shows the values that have already been selected within my react-select component even though the values are still in Formik's initialStates values.
My state is as follows which is storing my selectedOptions correctly:
import Select from 'react-select';
const myOptions= [
{ value: 'Food', label: 'Food' },
{ value: 'Being Fabulous', label: 'Being Fabulous' },
{ value: 'Unicorns', label: 'Unicorns' },
{ value: 'Kittens', label: 'Kittens' },
];
"props": {
"myGroups": [
{
"myGroupName": "",
"selectedOptions": [
{
"value": "Unicorns",
"label": "Unicorns"
},
{
"value": "Kittens",
"label": "Kittens"
}
]
}
]
}
Here is the code for the react-select component:
<Formik initialValues={initialFormValues} validationSchema={formSchema} onSubmit={this.handleFormSubmit} enableReinitialize>
{({ handleSubmit, handleChange }) => (
<Form noValidate onSubmit={handleSubmit} autoComplete='off'>
<Select
options={myOptions}
isMulti={true}
name={`myGroups.${index}.selectedOptions`}
onChange={(selectedOption) => {
let e = { target: { name: `myGroups.${index}.selectedOptions`, value: selectedOption } };
handleChange(e);
}}
/>
</Form>
)}
</Formik>
When returning, I expected to see both "Unicorns" and "Kittens" within the select but it's empty.
Any ideas how I can maintain state within this component? Can I perhaps somehow use `defaultValue' ?
The only solution I found is to install this library : formik-material-ui
You can after easy import:
import { Select } from 'formik-material-ui';
And use it in the Field component props.

react-select: Automatically suggest "other" option when you have no options for the search

I have a searchable dropdown field on my form, where the user does the research and selects normally.
What I need is if he types an option that does not exist, suggest the option "other" for him to select.
The "other" option already exists, I just don't know how to automatically suggest it.
I've seen about noOptionsMessage, but it's not useful for me, I need you to suggest the option automatically.
Can you help me? Thanks.
There is a props called filterOption to customize how you want your option filtered when the user types in the input, but it can only filter a single option and lacks the context of other options.
Because of that, to show the "other" option when no option available, you have to:
Disable the default option filter so it doesn't mess with your custom filter.
Control the options state.
Filter out the options as the user type and update the options state.
Below is an example to demonstrate what I meant:
import Select, { createFilter } from "react-select";
const filterOption = createFilter({});
const allOptions = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" }
];
const otherOption = { value: "other", label: "Other" };
export default function App() {
const [options, setOptions] = useState(allOptions);
const filterAllOptions = (rawInput: string) => {
const filteredOptions = allOptions.filter((o) => filterOption(o, rawInput));
if (filteredOptions.length === 0) {
filteredOptions.push(otherOption);
}
setOptions(filteredOptions);
};
return (
<Select
options={options}
filterOption={() => true} // disable the default option filter
onInputChange={(e) => filterAllOptions(e)}
/>
);
}
Live Demo

How to format value of the React Select

I use "react final forms" and "react select".
I've organized an interface and functionality works, but I have one thing which I don't like.
React select requires options in next format:
const options = [
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' }
]
and the value also should be set as { value: 'chocolate', label: 'Chocolate' }.
But for me is strange to have in my model of data (and send to the server also) the value like this - { value: 'chocolate', label: 'Chocolate' }, because I need only 'chocolate'.
Easy way is format the object into a single value after the form will be saved and format back from single value to the object before the rendering of the element. I know how to do it outside of form, but in this case I should solve this problem again and again for each select element separately.
What I would like to do:
Find a way how to set value of the react select as single value, like 'chocolate' instead of object.
OR
Create a wrapper for react select component and format value there when it sets (it's easy) and when the form get the value from this field (this I don't know how to do).
I will appreciate any help.
Method 1
With strings:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import Select from "react-select";
const data = ["1", "2"];
function SingleStringReactSelect() {
const [option, setOption] = useState();
return (
<section>
<Select
onChange={option => setOption(option)}
value={[option]}
getOptionLabel={label => label}
getOptionValue={value => value}
closeMenuOSelect={false}
options={data}
/>
</section>
);
}
Method 2:
Created example:
https://codesandbox.io/s/react-codesandboxer-example-z57ke
You can use map in options and with Wrapper like SingleValueReactSelect
import React, { Fragment, useState } from "react";
import Select from "react-select";
const data = ["chocolate", "strawberry", "vanilla"];
export function SingleValueReactSelect(props) {
const [selectedItem, setSelectedItem] = useState();
return (
<Select
{...props}
value={selectedItem}
onChange={item => {
setSelectedItem(item);
props.onChange(item.value);
}}
options={props.options.map(item => ({ label: item, value: item }))}
/>
);
}
export default function AppDemo() {
return (
<Fragment>
<p>SingleValueReactSelect Demo</p>
<SingleValueReactSelect
isClearable
isSearchable
options={data}
onChange={item => {
alert(item);
}}
/>
</Fragment>
);
}
You can transform/filter the object data once you are sending the form data to server or another component.
Setting the value of the react-select as a single value will not show it as selected in the React-Select.

Resources