I have react component that render some text inside, but how I can dynamically select a piece of text and wrap it in a span.
Code example
import { useState } from "react"; import "./styles.css"; export default function App() { const [text, setText] = useState('Some text will be here but this one will be yellow') const transformTextCallback = (text,start, end) => { let selectedString = text.substring(start, end) //how wrapp selectedText into span and return all text where //selected text will be wrapped with span //exprected result => Some text will <span className='red'>be here but</span> this one will be yellow } const onMouseUp = ()=> { let data = window.getSelection().getRangeAt(0) let start = data.startOffset; //index start select text let end = data.endOffset //index end select text let transformText = transformTextCallback(text, start, end) console.log(transformText) } return ( <div className="App"> <div className='textContent' onMouseUp={onMouseUp}> {text} </div> </div> ); } When I select the text, a function is triggered that receives the coordinates of the selected text and processes it, so this is how I wrap the selected text in a span and set the new text in setState, which will be the old text with the text wrapped in the span