Home > other >  React - Set TextArea value as HTML
React - Set TextArea value as HTML

Time:10-22

I have one inside react functional component, and would like to set the value of textarea as html.I try to set the value using useState hook.

Exactly asking, what is the equivalent for document.getElementById("foo").innerHTML in React using useState hook?

CodePudding user response:

If the textarea is inside your react component, you can render it with useState.

const MyComponent = () => {
  const [value, setValue] = useState('');
  
  // render textarea with new props when value changes
  return <textarea id='foo'>{value}<textarea>
}

If the textarea is outside your react component, you could use useState and useEffect.

const MyComponent = () => {
  const [value, setValue] = useState('');

  useEffect(() => {
    // run this command when value changes
    document.getElementById("foo").innerHTML = value
  }, [value])
  
  return <div /> // or anything you want
}

CodePudding user response:

in React, state changes automatically re-renders the DOM so you dont need document.getElementById("foo").innerHTML.

What you can do is, write your state inside JSX tags like this:

<p>{this.state.text}</p>

When your state changes, the DOM will automatically re-render and your text will be updated.

  • Related