Building the Context Menu System
We'll cover the following...
Looking back at our description of what a “context menu” is, we said that it needs to be absolutely positioned on the screen. We can put together a generic component to help render something at an absolute position.
common/components/AbsolutePosition.jsx
import React from "react";
import PropTypes from "prop-types";
const AbsolutePosition = (props) => {
const {children, nodeRef} = props;
const style = {
position: 'absolute',
top: props.top,
bottom : props.bottom,
left: props.left,
right : props.right,
width: props.width,
};
return (
<div style={style} className={props.className} ref={nodeRef}>
{children}
</div>
);
}
AbsolutePosition.propTypes = {
top: PropTypes.number,
bottom : PropTypes.number,
left: PropTypes.number,
width: PropTypes.number,
nodeRef : PropTypes.func,
};
export default AbsolutePosition;
All we really do here is set a div
's style to position : "absolute"
, apply the provided positions, and insert the children inside the div. The only slightly unusual thing here is that we’re taking a prop called nodeRef
, and passing it down as a callback ref to the div
. We’ll see why that matters in a minute.
Now for the actual context menu behavior. First, we’ll add the react-portal
library to our app:
...