Jay
Jay

Reputation: 75

How to get value from contentEditable in reactjs

I'm fairly new to ReactJS. I am looking to get the value inside a <div> when contentEditable is set to true.

const listResults = this.state.results['1'].map((result) =>
  <div key={result.toString()} contentEditable="true">
    {result}
  </div>
);

return (
  <h1> listResults </h1>
  <div> {listResults} </div>
)

I am currently outputting a list into pre-filled text-boxes which allows the user to edit them. I am looking to add in a button which once clicked captures the data inside all of the text-boxes. Can anyone point me in a direction on how to capture the changed data.

It may also be worth noting I am using ReactJS on the client side through a CDN.

Upvotes: 5

Views: 6243

Answers (2)

Gary Felicite-Prudent
Gary Felicite-Prudent

Reputation: 31

To get the value of an element whose contentEditable attribute is set to true in React, here is a way to do it:

import React, { useRef } from "react";

export default () => {
  const editable = useRef(null);
  return (
    <>
      <p contentEditable={true} ref={editable} />
      <button
        onClick={() => {
          console.log(editable.current.innerHTML);
        }}
      >
        Click
      </button>
    </>
  );
};

Upvotes: 0

Andrii Starusiev
Andrii Starusiev

Reputation: 7774

To get value of editable div:

class App extends React.Component {
    constructor(){
        super();
      this.state = {
            arr: [1,2,3,4,5]
      }
      this.change = this.change.bind(this);
  }
  change(e, index){
    let tmpArr = this.state.arr;
    tmpArr[index] = e.target.textContent;
    this.setState({arr: tmpArr})
  }
  render(){
    console.log(this.state);
    return (
      <tr>
          {this.state.arr.map((el, index) => <td key={index} id="test" onBlur={(e) => this.change(e, index)} contentEditable="true">{el}</td>)}
      </tr>
    );
  }
}

https://jsfiddle.net/69z2wepo/84647/

One note, you can't return two elements on the same level:

return (
  <h1> listResults </h1>
  <div> {listResults} </div>
)

It should be wrapped like this:

return (
    <div>
      <h1> listResults </h1>
      <div> {listResults} </div>
    </div>
)

Upvotes: 2

Related Questions