React- component with behavior

Hello React - composite components - composing components with behavior - working solution. author(s): Ryan Vice

by Rich Costello

HTML

<script src="https://fb.me/react-with-addons-0.14.0.js"></script>
<script src="https://fb.me/react-dom-0.14.0.js"></script>
 
<div id="view"/>

Babel + JSX

var HelloMessage = React.createClass({
    render: function() {
        return <h2>{this.props.message}</h2>;
    }
});

var TextBox = React.createClass({
    getInitialState: function() {
        return { isEditing: false }
    },
    update: function() {
        this.props.update(this.refs.messageTextBox.value);
        this.setState(
            {
                isEditing: false
            });
    },
    edit: function() {
        this.setState({ isEditing: true});
    },
    render: function() {
        return (
            <div>
              {this.props.label}<br/>
                <input type='text' ref='messageTextBox' disabled={!this.state.isEditing}/>
                {
                    this.state.isEditing ?
                        <button onClick={this.update}>Update</button>
                        :
                        <button onClick={this.edit}>Edit</button>
                    }
            </div>
        );
    }
});

var HelloReact = React.createClass({
    getInitialState: function () {
        return { firstName: 'Geordi', lastName: 'La Forge'}
    },
    update: function(key, value) {
        var newState = {};
        newState[key] = value;
        this.setState(newState);
    },
    render: function() {
        return (
            <div>
                <HelloMessage
                    message={'Hello ' + this.state.firstName + ' ' + this.state.lastName}>
                </HelloMessage>
                <TextBox label='First Name' update={this.update.bind(null, 'firstName')}>
                </TextBox>
                <TextBox label='Last Name'
                    update={this.update.bind(null, 'lastName')}>
                </TextBox>
            </div>
        );
    }
});

ReactDOM.render(
    <HelloReact/>,
    document.getElementById('view'));