How to fix React forwardRef(Menu) Material UI?

Viewed 10167

I created very simple custom components MuiMenu and MuiMenuItem. But when I try displaying these components I see an error as shown below:

Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

Check the render method of `ForwardRef(Menu)`.

But if I import directly from @material-ui/core - all is well. How do I fix this?

Working example: https://codesandbox.io/s/sharp-shadow-bt404?file=/src/App.js

1 Answers

As the error says, Material-UI is using ForwardRef and you need to include that in your code. Below is a fix to your MuiMenu and MuiMenuItem Components;

MuiMenu

import React from "react";
import Menu from "@material-ui/core/Menu";


const MuiMenu = React.forwardRef((props, ref) => {
  return <Menu  ref={ref} {...props} />;
});

export default MuiMenu;

MuiMenuItem

import React from "react";
import MenuItem from "@material-ui/core/MenuItem";

const MuiMenuItem = React.forwardRef((props, ref) => {
  return <MenuItem  ref={ref} {...props} />;
});

export default MuiMenuItem;

Also there was an error with the strictmode you used at index so I removed it.

Index.JS

import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

const rootElement = document.getElementById("root");
ReactDOM.render(
    <App />,
  rootElement
);

here is a link to the fixed sandbox: https://codesandbox.io/s/hopeful-thunder-u6m2k

And here are other links to help you understand a bit more: https://material-ui.com/getting-started/faq/#how-do-i-use-react-router | https://reactjs.org/docs/react-api.html#reactforwardref

Related