Adding React Components After Text Selection

- 1 answer

I have a set of React components that represent a text document. When someone selects text, I want to display a toolbar. Buttons on the toolbar will eventually change styling on the selected text of the React components.

Each phrase in the document gets it's own component that looks like (simplified):

render: function() {
    return (
        <span handleSelection={this.handleSelection}>
            <span className="pre"></span>
            <span className="phrase">text</span>
            <span className="post"></span>
renderSelectionToolbar: function() 
    return this.state.selected ? <ToolbarHTML> : '';
handleSelection: function() {
    this.setState({selected: true});

I've tried getting the selection with var selection = window.getSelection(). I can get the wrapping span (start of the selection) with selection.anchorNode. I tried calling selection.anchorNode.handleSelection(), but that function doesn't exist on the html element.

How can I call a method of my React component upon text selection? Is there a better way to display a toolbar after selected text? Thanks!



Thanks to Felipe T.'s comment, I've had an idea that solves the problem.

I was already using the onMouseUp event of a parent element to pull the list of phrases that have been changed. I've been rendering a phraseId attribute to each phrase so that I can update its entry in mongodb. Now, I'm updating the mongodb entry of the first phrase in the selection with an attribute {contextToolbar: true}. Then, in my render code I build a display off of the same attribute. If the user dismisses the toolbar or un-selects the text then the attribute gets set back to false. Though, I have to remember to remove the flag if the user goes straight into selecting a new set of text.

This is working for now, but I'd love to hear a more elegant solution if you have one. Especially one that doesn't force me to save temporary state information in my document database.