0

I am looking for some good practice example to change color of text in a textarea in react js

i saw some example with adding div on top of textarea but how to do that in a react way

precious
  • 117
  • 2
  • 12

1 Answers1

0

To change the color of the text, we need to add html and css. We can't add that in textarea as textarea only contains text, but not html elements.

So, for your usecase, what you gonna do is use a div with contenteditable instead of textarea to enter the text. Like this

<div contentEditable></div>

Now to do in react way. We need to store the state which will be rendered in div. And upon some action like selection of the text, you can insert the text wrapped around a p tag with style of text color.

For suppose, lets assume this line, This is a sentence for demo. When user selects on sentence, we can wrap the text with p and update the state like this - This is a <p style={{ color: 'red' }}>sentence</p> for demo.

const [state, setState] = useState('');

render (
  <div contentEditable>{state}</div>
);
  • How to add p tag on some action? i want to change text color of say n words for eg 10 words – precious Sep 25 '20 at 21:16
  • with contenteditable there is too much of a handling required. For eg, on paste from excel you have position cursor at the of the string etc. Cant we do this over text area so that extra handling can be avoided? – precious Sep 28 '20 at 09:39
  • If you check my answer again, I already specified that we can't color the text in textarea. The only way you have is to do in html contenteditable. Check this similar answer - https://stackoverflow.com/a/37160584/10616955, he said the same. – Saka Sai Trinath Sep 29 '20 at 12:40
  • For reference, you can check this - https://codesandbox.io/s/godzilla-editor-up2se. I was playing around with text editor in some way. I will try with contenteditable and comment here. – Saka Sai Trinath Sep 29 '20 at 12:55