Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ho to fix React forwardRef(Menu) Material UI?

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

like image 725
itwaze Avatar asked Jul 16 '20 13:07

itwaze


People also ask

How do you use react forwardRef in functional components?

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} {...

Is forwardRef a hook?

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.

What does react forwardRef do?

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.


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

like image 133
mw509 Avatar answered Oct 25 '22 03:10

mw509