Description:
A React component that displays a custom popup menu on the selected text. Perfect for inline editing, social sharing, etc.
How to use it:
1. Install and import the component.
import React, { useRef } from ‘react’;
import ReactSelectionPopup, { PopupHandle } from ‘react-selection-popup’;
2. Create a text selection popup component.
const App = () => {
const ref = useRef<PopupHandle>(null)
return (
<div>
<ReactSelectionPopup
ref={ref}
selectionClassName="selection"
metaAttrName="data-meta"
onSelect={(text, meta) => console.debug(text, meta)}
>
<div>
<p>Popup Content</p>
<button onClick={() => { ref.current?.close() }}>Close</button>
</div>
</ReactSelectionPopup>
<p className="selection" data-meta={JSON.stringify({ explain: "Test metadata" })}>
Select me to see the popup.
</p>
</div>
);
};3. Available props.
/**
* This function is called when a user selects texts in html.
* @param text - The text of the selection
* @param meta - Additional metadata associated with the selected text (optional)
*/
onSelect?: (text: string, meta?: any) => void
/**
* This function is called when a popup is closed due to focus lost.
*/
onClose?: () => void
/**
* This function returns a function to close a popup.
*/
children: React.ReactNode
/**
* The className to be used to identify selectable element(s).
*/
selectionClassName: string
/**
* Whether multiple elements can be selected at once (default is false).
*/
multipleSelection?: boolean
/**
* The name of the metadata attribute associated with the selected text (optional).
* The metadata value should be JSON stringfied.
* @example <div ... className="selection" metaAttrName="data-meta">...</div>
* ...
* <ReactSelectionPopup ... data-meta={JSON.stringfy(data)}>...</ReactSelectionPopup>
*/
metaAttrName?: string
/**
* The offset (in pixels) to the left direction of the screen to reposition the popup. The default pivot x is right of the pop.
*/
offsetToLeft?: number
/**
* The offset (in pixels) to the top direction of the screen to reposition the popup. The default pivot y is bottom of the pop.
*/
offsetToTop?: number
id?: string
className?: string
style?: React.CSSProperties