Reputation: 149
I was trying to make a select menu with material-ui and React
const SelectLevelButton = forwardRef((props, ref) => {
const [stateLevel, setStateLevel] = useState({
level: "Easy"
});
const [stateMenu, setStateMenu] = useState({
isOpen: false
});
const openMenuHandler = () => {
setStateMenu({
isOpen: true
});
};
const closeMenuHandler = () => {
setStateMenu({
isOpen: false
});
};
const buttonRef = useRef();
console.log(buttonRef.current);
return (
<>
<Menu open={stateMenu.isOpen} anchorEl={buttonRef.current} onClose={closeMenuHandler}>
<MenuItem>Easy</MenuItem>
<MenuItem>Normal</MenuItem>
<MenuItem>Hard</MenuItem>
</Menu>
<div ref={buttonRef}>
<Button onClick={openMenuHandler} color="inherit">{`Level: ${stateLevel.level}`}</Button>
</div>
</>
);
});
export default SelectLevelButton;
but when i click on the button to open the menu in console i get this warning: Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Transition which is inside StrictMode. Instead, add a ref directly to the element you want to reference.
How can i solved that?
Upvotes: 2
Views: 3052
Reputation: 71
anchorEl reference in Menu is undefined, as you get it from buttonRef.current undefined at start. So it uses findDOMNode instead. See Material-UI docs how to get the reference before opening Menu.
You need to change your code like that, (not tested) :
const SelectLevelButton = forwardRef((props, ref) => {
const [anchorEl, setAnchorEl] = React.useState(null);
const [stateLevel, setStateLevel] = useState({
level: "Easy"
});
const [stateMenu, setStateMenu] = useState({
isOpen: false
});
const openMenuHandler = event => {
setAnchorEl(event.currentTarget);
setStateMenu({
isOpen: true
});
};
const closeMenuHandler = () => {
setStateMenu({
isOpen: false
});
};
const buttonRef = useRef(); // No need for that
console.log(buttonRef.current);
return (
<>
<Menu open={stateMenu.isOpen} anchorEl={anchorEl} onClose={closeMenuHandler}>
<MenuItem>Easy</MenuItem>
<MenuItem>Normal</MenuItem>
<MenuItem>Hard</MenuItem>
</Menu>
<div ref={buttonRef}>
<Button onClick={openMenuHandler} color="inherit">{`Level: ${stateLevel.level}`}</Button>
</div>
</>
);
});
export default SelectLevelButton;
Upvotes: 1