Burak Burak - 27 days ago 27
React JSX Question

How to edit an element's text with React.js?

i wanna edit my

p
element's text when i press edit
button
.

When i click edit
button
, i display a
textarea
and get keyed text with alert but can't put that text to my
p
element.

What is the simple way to do it with React.js ?

JSFIDDLE

When i press edit button, editing state changing and textarea shows up.The code below.

renderNormal: function() {
return (
<div>
<p>Edit me</p>
<button onClick={this.edit}>Edit</button>
</div>
)
},
renderForm: function() {
return (
<div>
<textarea ref="newText" defaultValue="Edit me"></textarea>
<button onClick={this.save}>Save</button>
</div>
)
},
render: function() {
if (this.state.editing) {
return this.renderForm()
} else {
return this.renderNormal()
}
}

Answer

You need to store and retrieve the text from a state variable. Modifying the state causes a re-render, which will then display the updated text. Copied from your JSFiddle... note where I've added a "text" property to your state

var MyCom = React.createClass({
  getInitialState: function() {
    return {
      editing: false,
      // ** Initialize "text" property with empty string here
      text: ''
    }
  },
  edit: function() {
    this.setState({
      editing: true
    })
  },
  save: function() {
    var val = this.refs.newText.value;
    alert(val)
    this.setState({
      // ** Update "text" property with new value (this fires render() again)
      text: val,
      editing: false
    })
  },
  renderNormal: function() {
    // ** Render "state.text" inside your <p> whether its empty or not...
    return (
      <div>
        <p>{this.state.text}</p>
        <button onClick={this.edit}>Edit</button>
    </div>
    )
  },
  renderForm: function() {
    return (
      <div>
         <textarea ref="newText" defaultValue="Edit me"></textarea>
        <button onClick={this.save}>Save</button>
    </div>
    )
  },
  render: function() {
    if (this.state.editing) {
      return this.renderForm()
    } else {
      return this.renderNormal()
    }
  }
})

ReactDOM.render(
  <div>
  <MyCom/>
    <MyCom/>
    </div>,
  document.querySelector(".box")
)