Hi I am using Material UI multi select in react typescript.
I am passing an event to child component to change the multi select value.
Parent component code is -
import {myData} from '../constant';
export const Parent = () => {
const [personName, setPersonName] = React.useState<string[]>([]);
const handleChangeMultiple = (event: React.ChangeEvent<{ value: unknown }>) => {
const { options } = event.target as HTMLSelectElement;
const value: string[] = [];
for (let i = 0, l = options.length; i < l; i += 1) {
if (options[i].selected) {
value.push(options[i].value);
}
}
setPersonName(value);
};
return (
<div>
<Child
onChange={handleChangeMultiple}
myData={myData}
/>
</div>
);
}
Child Component code is -
import React from 'react'
export interface ChildProps {
onChange: (event: React.ChangeEvent<{ value: unknown }>) => void;
myData?: Array<Test<string, string>> | null;
}
export const Child = ({onChange , myData}: ChildProps) => {
return (
<div>
<MultiSelect
multiple
native
value={myData.val}
onChange={(event: React.ChangeEvent<{ value: unknown }>): void =>
onChange(event: React.ChangeEvent<{ value: unknown }>)
}>
{myData &&
myData.multiSelectData &&
myData.multiSelectData.map(
(item: Test<string, string>) => (
<option key={item.key} value={item.value}>
{item.key.replace('_',' ')}
</option>
)
)}
</MultiSelect>
</div>
);
}
I am passing the Change Event to get multi select value onChange in parent component. I don't want to pass any event I want to pass only string value & want to get this string value onchange multi select.
like in child component interface it should be - onChange: (value:string) => void;
and in child component it should be -
<MultiSelect
multiple
native
value={myData.val}
onChange={(event: React.FormEvent<EventTarget>): void =>
onChange(someValue)
}>
{myData &&
myData.multiSelectData &&
myData.multiSelectData.map(
(item: Test<string, string>) => (
<option key={item.key} value={item.value}>
{item.key.replace('_',' ')}
</option>
)
)}
</MultiSelect>
SO is there any way to pass string value to the event rather passing whole html event but yes multi select should work properly.
question from:
https://stackoverflow.com/questions/65517617/how-to-pass-string-value-rather-pass-event-in-multiselect-material-ui 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…