Pavindu
Pavindu

Reputation: 3123

get value from onInput event for cotentEditable in React

I have a contentEditable header in which I want to get the value on onInput event. So far, I have managed to get event.target but it returns the entire DOM node. I want to get only the actual value of the header. Helpful ideas are highly appreciated.

What I have tried so far:

  1. console.log(e.target.value) --> returns undefined

  2. console.log(e.target) --> returns the node <h5 contenteditable="true" style="margin: 0px;">Lesson 1</h5>

  3. I also thought to convert node to string and extract the value using reg ex, but I had to give up when console.log(e.target.toString()) return [object HTMLHeadingElement]

<h5 contentEditable style={{ margin: 0 }} onInput={e => {
          props.onChangeName(e.target.value)
          console.log(e.target)
      }}>
        {props.name}
</h5>

Upvotes: 1

Views: 1662

Answers (1)

sebastienbarbier
sebastienbarbier

Reputation: 6832

Using .value only works for forms html component. Using contentEditable allows you to edit the innerHtml of your markup. To access the actual content, you can run:

<h5 contentEditable style={{ margin: 0 }} onInput={e => {
      props.onChangeName(e.target.innerHTML);
      //or
      props.onChangeName(e.target.textContent);
  }}>
  {props.name}
</h5>

Upvotes: 2

Related Questions