I have a problem regarding MUI's MenuItem when combined with Select and rendering it in a separate component.
Here's the codesandbox
Basically, I have something like this:
import { Select } from "@material-ui/core";
import CustomMenuItem from "./CustomMenuItem";
import React from "react";
export default function App() {
const userIds = [1, 2, 3];
return (
<Select
id="user"
name="User"
onChange={(event: React.ChangeEvent<{ value: unknown }>) => {
alert(event.target.value as number);
}}
>
{userIds.map((userId) => (
<CustomMenuItem key={userId} userId={userId} />
))}
</Select>
);
}
And this is the custom item:
import { MenuItem, Typography } from "@material-ui/core";
import React from "react";
interface CustomMenuItemProps {
userId: number;
}
const CustomMenuItem = React.forwardRef<HTMLLIElement, CustomMenuItemProps>(
(props: CustomMenuItemProps, ref) => {
const { userId, ...rest } = props;
return (
<MenuItem value={userId} {...rest} ref={ref}>
<Typography>{userId}</Typography>
</MenuItem>
);
}
);
export default CustomMenuItem;
At first, I've done this without any refs, but this gave me an error in the console (Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?), so after googling a while, I found out that I have to pass this ref. I also pass the ...rest of the props, as I understand that the MenuItem needs them.
Expected behavior: when I click on the MenuItem, it gets selected in the Select component.
Actual behavior: nothing happens.
The thing is, I made the CustomMenuItem to make it reusable. But before that, I had a simple function like: renderItem which I used both in Select.renderValue and in userIds.map and it had the same code as CustomMenuItem - it returned the same JSX tree. And it worked then, but it doesn't work now, for some reason. So if I would do:
<Select
id="user"
name="User"
onChange={(event: React.ChangeEvent<{ value: unknown }>) => {
alert(event.target.value as number);
}}
>
{userIds.map((userId) => (
<MenuItem key={userId} value={userId}>
<Typography>{userId}</Typography>
</MenuItem>
))}
</Select>
it simply works :(
Am I missing something here?