I'm pretty new to React, and I want to make sure my process here is correct:
In this simple example, I've got a MsgBox
component which can maintain its own text state. When I click a button in that MsgBox
, its current value should get sent up to the parent.
var MsgBox = React.createClass({
getInitialState() {
return {msg: ''}
},
handleKeyUp(event) {
this.setState({msg: event.target.value});
},
sendUp() {
var inp = React.findDOMNode(this.refs.txt);
this.props.msgSetter(inp.value);
},
render() {
return (
<div className="msgbox">
<input onKeyUp={this.handleKeyUp} ref="txt" />
<button onClick={this.sendUp}>Send it up!</button>
<div className="echo">{this.state.msg}</div>
</div>
)
}
});
var Hello = React.createClass({
getInitialState() {
return {latestMessage: 'N/A'}
},
setLatestMessage(msg) {
this.setState({latestMessage: msg});
},
render() {
return (
<div>
<p>The latest message is {this.state.latestMessage}.</p>
<div className="msgboxes">
<MsgBox msgSetter={this.setLatestMessage} />
<MsgBox msgSetter={this.setLatestMessage} />
<MsgBox msgSetter={this.setLatestMessage} />
</div>
</div>
)
}
});
React.render(<Hello name="World" />, document.getElementById('container'));
Fiddle: https://jsfiddle.net/70oo7zzy/1/
Is this pretty much how it's done? What happens if you have this structure:
<Home />
<StatusBoard />
<Sector />
<EventsList />
<Event />
...and Event
had to send something way up to StatusBoard
? Do I really have to pass a callback prop from StatusBoard
down to Sector
, then down to EventsList
and finally to each Event
? This seems a bit overkill. Or maybe I'm thinking about it the wrong way.