2

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

1 Answer 1

1

You shouldn't store JSX in the state of the component so saving the span with the text to state is not the best approach. It think this is what you are trying to do:

import { useState } from "react"; import "./styles.css"; export default function App() { const [selected, setSelected] = useState(false); const text = "Some text that will be wrapped in a span and the color will be yellow"; const handleClick= (e)=> { setSelected(!selected); } return ( <div className="App"> <div className='textContent' onClick={handleClick}> {selected ? <span style={{ color: "yellow" }}> text </span> : text } </div> </div> ); } 
Sign up to request clarification or add additional context in comments.

2 Comments

I need ability to highlight text after it has been selected, so I should replace old text with new where selected - highlighted
Are you saying that you want the text updated as well as the color?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.