The map function in TextField does not work if it is located in the component material-ui
I have two TextFields in the first one the radio button works, in the second one the radio button does not work. How to do if the map function is located in a separate component to use the radio button?
if you try to replace the value in the first example, it will change correctly, in the second example it does not work. The only difference is that in the second example map is a separate file
https://codesandbox.io/s/green-snow-bmbcn2?file=/src/Test.js
import * as React from "react";
import Box from "@mui/material/Box";
import TextField from "@mui/material/TextField";
import MenuItem from "@mui/material/MenuItem";
import MapCastom from "./MapCastom";
const currencies = [
{
value: "USD",
label: "$"
},
{
value: "EUR",
label: "€"
},
{
value: "BTC",
label: "฿"
},
{
value: "JPY",
label: "¥"
}
];
export default function SelectTextFields() {
return (
<Box
component="form"
sx={{
"& .MuiTextField-root": { m: 1, width: "25ch" }
}}
noValidate
autoComplete="off"
>
<div>
<TextField
id="outlined-select-currency"
select
label="Select"
defaultValue="EUR"
helperText="Please select your currency"
>
{currencies.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</TextField>
</div>
<div>
<TextField
id="outlined-select-currency"
select
label="Select"
defaultValue="EUR"
helperText="Please select your currency"
>
<MapCastom data={currencies} />
</TextField>
</div>
</Box>
);
}
import React from "react";
import MenuItem from "@mui/material/MenuItem";
const MapCastom = ({ data }) => {
return (
<>
{data.map((option) => (
<MenuItem key={option.value} value={option.value}>
{option.label}
</MenuItem>
))}
</>
);
};
export default MapCastom;
2
Answers
Here most likely you are encountering the warning
which means that during first rendering select value doesn’t see possible options.
One way to fix it is to not use a component for this, already what you need is an array so you can replace
MapCastom
with this function :and call it this way :
It seems that for the MenuItem to work, it has to be a direct descendent of Select. One workaround is to use a function to return MenuItems instead of a component. Github issue