Recipes for making your React.js Components Awesome, or at least a little cleaner
- Basics
- Intermediate
- Use ternary operator for if/else
- Use 'map' to cleanly iterate over arrays
- Use 'classSet' to toggle classes
- ReactLink can be used for two-way data bindings
- Reduce can be used for simple list filtering
- Use bind to map specifiic parameters for event handlers
- Handler callback functions can be used a props to get events for subcomponents
render: function() {
return (
<button className="Btn Primary">Button</button>
);
}
NOTE: React uses camelCased for attribute names 'backgroundColor for 'background-color'
render: function() {
return (
<div style={{color: 'white', backgroundColor: 'lightblue'}}>Test</div>
);
}
render: function() {
var coinflip = Math.random() < .5;
return (
<div>
{(coinflip) ?
<div>Heads</div> :
<div>Tails</div>
}
</div>
);
}
render: function() {
var list = ['one', 'two', 'three'];
return (
<ul>
{list.map(function(item, idx) {
return <li key={idx}>{item}</li>
})}
</ul>
);
}
var cx = React.addons.classSet;
...
render: function() {
return <div className={cx({
'message': true,
'message-important': this.props.isImportant,
'message-read': this.props.isRead
})}>Great, I'll be there.</div>;
}
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {value: 'Hello!'};
},
render: function() {
return (
<div>
<input type="text" valueLink={this.linkState('value')} />
<div>You typed: {this.state.value}</div>
</div>
);
}
return (
<ul>
{messages.reduce(function(messages, item) {
if (match(item, filter)) {
messages.push(<li>{item.title}</li>)
}
return messages;
}, [])}
</ul>
);
onClick: function(value, e) {
e.preventDefault();
this.props.onChange({
choice: value
}, true);
this.setState({
choice: value
});
},
render: function() {
var self = this,
cx = React.addons.classSet,
choices = this.props.choices,
selected = this.state.choice;
return (
<ul className="Choices">
{choices.map(function(choice) {
return <li key={choice.value} className={cx({'Selected': (choice.value === selected)})}><a href='#' onClick={self.onClick.bind(null, choice.value)}>{choice.label}</a></li>;
})}
</ul>
);
}
Note: bind should have "null" as its first parameter, React will automatically re-bind with "this"
onClick: function(value, e) {
e.preventDefault();
this.props.onChange({
choice: value
}, true);
this.setState({
choice: value
});
},
...
<div>
<div>{'Selected: ' + this.state.selected}</div>
<Chooser choices={choices} onChange={this.choiceChange} />
</div>