Reputation: 1132
I am creating a dropdown edit form where on edit user will able to see the option value as selected from props
on edit. I tried with defaultValue
and using selected
but it seems my conditions are wrong.
Any suggestions which I can utilized to check the props value in option and display as selected on dropdown when user click edit.
Here selectedPropsName
is what we are getting from props
and I want to map
and display this as selected.
Thanks...
Code
const results = [
{
'Name': 'apple',
'description': 'apple is good for health'
},
{
'Name': 'mango',
'description': 'mango is very juicy'
}
]
const props = {
'Name': 'apple'
}
const CreateForm=()=> {
const [spaceName, setSpaceName] = React.useState('');
const [, setSpaceDescriptionName] = React.useState('');
const handleChangeSpaceName = (event: React.ChangeEvent<HTMLInputElement>) => {
setSpaceName(event.target.value);
setSpaceDescriptionName(event.target.value)
};
const selectedPropsName = props.Name
return (
<>
<div className='create-dropdown'>
<TextField
className='create-textfield'
id='create-textfield'
select={true}
label='create Name'
value={spaceName}
onChange={handleChangeSpaceName}
SelectProps={{
native: true,
}}
variant='standard'
>
{results && results.length > 0 && results.map((optionNames:any) => (
<option key={optionNames.Name}
className='textfield-option'
value={`${optionNames.Name}, ${optionNames.description}`}>
{optionNames.Name}
</option>
))}
</TextField>
</div>
</>
)
}
Upvotes: 0
Views: 680
Reputation: 502
If I understand you correctly, you should be able to check if optionNames.Name equals selectedPropsName and then set the option's selected attribute to true, conditionally.
So,
{results && results.length > 0 && results.map((optionNames:any) => (
<option key={optionNames.Name}
className='textfield-option'
value={`${optionNames.Name}, ${optionNames.description}`}>
{optionNames.Name}
</option>
))}
becomes
{results && results.length > 0 && results.map((optionNames:any) => (
<option key={optionNames.Name}
selected={optionNames.Name === selectedPropsName ? true : false}
className='textfield-option'
value={`${optionNames.Name}, ${optionNames.description}`}>
{optionNames.Name}
</option>
))}
EDIT:
My mistake. I've taken another look. It looks like you are using Material-UI and so, the select component is controlled. You would have to set the initial value through the spaceName hook. And you would have to change the props.Name variable to include a "name, description" since that is what your option value={} field is expecting. So, these changes should make it work:
const props = {
Name: "mango, mango is very juicy",
};
const [spaceName, setSpaceName] = React.useState(props.Name);
Upvotes: 1