Skip to content

Instantly share code, notes, and snippets.

@dantman
Created April 7, 2018 22:07
Show Gist options
  • Save dantman/1ab7c7ffc11c8a47501063e34171adcd to your computer and use it in GitHub Desktop.
Save dantman/1ab7c7ffc11c8a47501063e34171adcd to your computer and use it in GitHub Desktop.
A very simple AnchorRef component that uses a render-prop to provide a local ref (for popover anchors, etc...)
import {PureComponent} from 'react';
export default class AnchorRef extends PureComponent {
state = {
ref: undefined,
};
_setRef = ref => {
this.setState({ref});
};
render() {
return this.props.render(this.state.ref, this._setRef);
}
}
/**
* This is the Simple Menu example from the Material UI Menu examples
* https://material-ui-next.com/demos/menus/
* Except it has been modified to use a local ref instead of a ref within the component itself.
* This makes it much easier to use in the middle of a larger component
* Though I'd imagine the common case of using `event.currentTarget` to get an anchor could be
* abstracted further into a helper that exposes onOpen and onClose handlers that do not change
* each render like the inline handleClick/handleClose.
* Or a WeakMap based helper that memoizes handleClick/handleClosed based on setAnchorEl.
*/
import React from 'react';
import Button from 'material-ui/Button';
import Menu, { MenuItem } from 'material-ui/Menu';
import AnchorRef from './AnchorRef';
class SimpleMenu extends React.Component {
render() {
return (
<div>
<AnchorRef render={(anchorEl, setAnchorEl) => {
const handleClick = event => setAnchorEl(event.currentTarget);
const handleClose = () => setAnchorEl(null);
return (
<>
<Button
aria-owns={anchorEl ? 'simple-menu' : null}
aria-haspopup="true"
onClick={handleClick}
>
Open Menu
</Button>
<Menu
id="simple-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={handleClose}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
</>
);
}} />
</div>
);
}
}
export default SimpleMenu;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment