React Stateless vs Stateful form element components
by Ben Alman
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://fb.me/react-with-addons-0.14.6.js"></script>
<script src="https://fb.me/react-dom-0.14.6.js"></script>
<!-- From https://jsfiddle.net/69z2wepo/ -->
<div id="root"></div>
CSS
select {
display: block;
margin-bottom: 1em;
}
Babel + JSX
// **********************************
// NOT GREAT
// **********************************
// Note that state isn't used, instead the select is allowed to mutate its own
// "state" because the "defaultValue" prop was used instead of "value".
class StatefulSelect1 extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
getOption(value) {
return this.props.options.find(o => o.value === value);
}
handleChange(event) {
const {value} = event.target;
this.props.onChange(this.getOption(value));
}
render() {
const {disabled, options, value} = this.props;
return (
<select disabled={disabled} onChange={this.handleChange} defaultValue={value}>
{options.map(o => <option key={o.value} value={o.value}>{o.title}</option>)}
</select>
);
}
}
// Now state is used, but the component is doing far too much.
class StatefulSelect2 extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {value: this.props.value};
}
getOption(value) {
return this.props.options.find(o => o.value === value);
}
handleChange(event) {
const {value} = event.target;
this.setState({value});
this.props.onChange(this.getOption(value));
}
render() {
const {disabled, options} = this.props;
return (
<select disabled={disabled} onChange={this.handleChange} value={this.state.value}>
{options.map(o => <option key={o.value} value={o.value}>{o.title}</option>)}
</select>
);
}
}
// **********************************
// MUCH BETTER
// **********************************
// Here, the select component is stateless and entirely presentational...
const StatelessSelect = ({value, options, onChange, disabled}) => (
<select disabled={disabled} onChange={event => onChange(event.target.value)} value={value} >
{options.map(o => <option key={o.value}...