I have created select component using Mui but in that whenever i click on any option from select dropdown then it's storing correctly in the state that i have defined but it's not displaying in the select box.
Here is my Json object:
const SampleData = [
{
"type": "button",
"display": "RELEASE",
"key": "key1",
"value": [
{
"type": "text",
"display": "Are you sure to reject this",
"key": "key2",
"value": "val10"
},
{
"type": "select",
"display": "select reason",
"key": "key3",
"value": [
{ "type": "option",
"display":
"Wrong Truck number entered",
"key": "key4",
"value": "val1"
},
{ "type": "option",
"display": "Floors having intrusions",
"key": "key5",
"value": "val1"
}]
}
]
}]
And my component SelectField.js:
const SelectField = ({ SampleData }) => {
const [selectValue, setSelectValue] = useState('');
const [selectfieldres, setSelectFieldRes] = useState([]);
useEffect(() => {
SampleData.map((item, index) => {
if (item.type === 'select') {
if (typeof item.value === "object") {
setSelectFieldRes(item.value)
}
}
})
}, [])
const onChangeHandler = (e, display) => {
const selectedText = e.target.innerText;
console.log(selectedText)
selectfieldres.map((item, index) => {
if(item.display !== selectedText){
localStorage.removeItem('select' item.display)
}
}
)
if (selectedText) {
setSelectValue({selectValue: selectedText})
console.log(localStorage.getItem.name)
localStorage.setItem('select' selectedText, selectedText)
}
}
return (
<Box>
<FormControl sx={{ml: 5, my: 2, minWidth: 180 }}>
<InputLabel id="demo-simple-select-label">select reason</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
value={selectValue}
label="select reason"
onClick={(e)=>{onChangeHandler(e,display)}}
>
{selectfieldres.map((item, index) => (
item.type === 'option' &&
<MenuItem value={item.display} key={index}>
{item.display}
</MenuItem>
))}
</Select>
</FormControl>
</Box>
);
}
export default SelectField;
Output of above component:
Options are showing in the dropdown
When I click on any option then it's showing empty
CodePudding user response:
By the looks, you are not setting the state
for selectValue
properly.
const [selectValue, setSelectValue] = useState('');
This means the selectValue
is of type string
. However, in the state update, you are trying to change an object property.
setSelectValue({selectValue: selectedText});
You need to simply pass a string to the setState
method.
setSelectValue(selectedText);