javascript - React, how to programmatically select text on component click - Stack Overflow

admin2025-04-19  1

I would like to select the contents of a simple span element, when clicked on

<span 
  onClick={() => // How do I programmatically highlight the `Click Me!` text?}
>Click Me!</span>

Is there any way to do this?

Edit: I'm sorry it seems the question was not clear enough, I do not only want to highlight the span, but I actually want to trigger a dom selection of the element, so afterwards it can be copied and/or written upon (if for example it is within a div with editable content turned on).

I would like to select the contents of a simple span element, when clicked on

<span 
  onClick={() => // How do I programmatically highlight the `Click Me!` text?}
>Click Me!</span>

Is there any way to do this?

Edit: I'm sorry it seems the question was not clear enough, I do not only want to highlight the span, but I actually want to trigger a dom selection of the element, so afterwards it can be copied and/or written upon (if for example it is within a div with editable content turned on).

Share edited Sep 17, 2019 at 5:08 Oscar Franco asked Sep 16, 2019 at 19:05 Oscar FrancoOscar Franco 6,2606 gold badges37 silver badges70 bronze badges 3
  • you mean highlight the text or select the text inside of the span? – Ivan-San Commented Sep 16, 2019 at 19:09
  • do you want the highlight to be permanent or you want a blink? – Dhaval Jardosh Commented Sep 16, 2019 at 19:10
  • Select the text inside of the span – Oscar Franco Commented Sep 17, 2019 at 5:07
Add a ment  | 

3 Answers 3

Reset to default 3

Thanks a lot for the answers, but it seems the question was not pletely clear, I apologize for that.

In any case, I found an answer here:

Programmatically select text in a contenteditable HTML element?

I really wanted to select the content programmatically, so the final snippet of code I used is the following:

function selectContents(el: any) {
  let range = document.createRange();
  range.selectNodeContents(el);
  let sel = window.getSelection()!;
  sel.removeAllRanges();
  sel.addRange(range);
}

<span onClick={(e) => selectContents(e.target)}>
  {node.name}
</span>

It is working fine in electro, but there might be some patibility issues with older browsers.

Cheers.

You can use react state to highlight the span programmatically.

class App extends React.Component {
  state = {
    highlightOn: false,
    smallPortionHighlight: false
  };

  render() {
    return (
      <div>
        <span
          style={{ backgroundColor: this.state.highlightOn ? "red" : "white" }}
          onClick={() => this.setState({ highlightOn: true })}
        >
          Click Me!
        </span>

        <br />
        <br />
        <span onClick={() => this.setState({ smallPortionHighlight: true })}>
          Here is a long text but just highlight this{" "}
          <span
            style={{
              backgroundColor: this.state.smallPortionHighlight
                ? "red"
                : "white"
            }}
          >
            Click Me!
          </span>
        </span>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activate: false };
        
  }
  toggleClass() {
        const currentState = this.state.active;
        this.setState({ active: !currentState });
    };

  render() {
    return (
      <div>
        <span className={this.state.active ? 'highlight': null} 
                onClick={ () => this.setState({active: !this.state.active}) } >
          Click Me!</span>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
.highlight{
  background-color: #FFFF00; 
}
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745013524a279949.html

最新回复(0)