this fiddle demonstrates a react.js component that takes an object as an argument and creates a set of content editable spans for the values, and labels them with the keys.
a bit of quick annotation below. Essentially i use 2 props, name and value for each key/value pair. Only the value is editable.
// this is our object, please excuese the vulgarity. I was tired when I wrote this.
var node1 ={
owner: "i am the owner",
where: "right here bitch",
name: "Joe Super Fucking AWESOME"}
// this is our main component which manages the changes to the content in our contentEditable spans
var ContentEditable = React.createClass({
render(){
return( <span id="contenteditable"
onInput={this.emitChange}
onBlur={this.emitChange}
contentEditable >
{this.props.item}
</span> )
},
emitChange(){
var html = this.getDOMNode().innerHTML;
// only fire if the html changes
if (this.props.onChange && html !== this.lastHtml) {
this.props.onChange({
// emit both the value of the change, and the key, as name here
target: {
value: html,
name: this.props.name
}
});
}
this.lastHtml = html;
}
});
var Item = React.createClass({
getInitialState(){
return {result: ""}
},
// this is where we'd do something with the update
handleClick(event){
console.log("click",this.state)
},
// mostly debuggin output to see how thing react to changes
handleChange(event){
console.log("change",this.state);
var x = this.state[event.target.name];
console.log("x",x,event.target.name);
var o = {}
o[event.target.name] = event.target.value;
this.setState(o);
},
render(){
var keys = Object.keys(this.props.i)
return(<div>
{keys.map(function(key){
var item = this.props.i[key]
return(
<li>
<label>{key}:</label>
<ContentEditable name={key} item={item} onChange={this.handleChange} />
</li>
);},this)}
<button onClick={this.handleClick} >
Pretend to send to a server or something
</button>
<div>result<pre>{JSON.stringify(this.state,null, 2)}</pre></div>
</div>)
}
});
var MyDiv = React.createClass({
//mixins: [Reflux.connect(TheStore)],
render(){
return (
<div> This holds our item! <br />
<div>
<ul>
<Item i={node1} />
</ul>
</div>
</div>
)
}
})
React.render(<MyDiv />, document.getElementById('container'));
About this blog: This blog will discuss technology associated with my idgon.com project. I am using Elixir and Phoenix for my backend, and React.js and Reflux for my front end. I have a library called Trabant to experiment with graph database persistence for Elixir. The views expressed on this blog are my own, and are not that of my current employer.
About Me: I am a hobbyist programmer interested in distributed computing. I dabble in Elixir, Ruby, and Javascript. I can't spell very well, and I enjoy golf.