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
const Input = forwardRef((props, ref) => { // Here goes the content of our component }); In the returned JSX code, we now need to pass the ref we receive in the function to the correct HTML component, which in our case is the input element. const Input = forwardRef((props, ref) => { return ( <input ref={ref} {...
The forwardRef hooks allows React users to pass refs to child components. The ref can be created and referenced with useRef or createRef and then passed in a parent component. Using forwardRef instead of useRef is useful when a ref needs to be accessed in a parent component.
The forwardRef method in React allows parent components to move down (or “forward”) refs to their children. ForwardRef gives a child component a reference to a DOM entity created by its parent component in React. This helps the child to read and modify the element from any location where it is used.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With