Component states - Dynamic user-interface

suggest change

Suppose we want the following behaviour. We have a heading (an h3 element) and, on clicking it, we want it to become an input box so that we can modify the heading text. React makes this simple using component state and if/else. (Code explanation below.) This example uses the React 15 createClass API and React Bootstrap.

// I have used ReactBootstrap elements. But the code works with regular html elements also
var Button = ReactBootstrap.Button;
var Form = ReactBootstrap.Form;
var FormGroup = ReactBootstrap.FormGroup;
var FormControl = ReactBootstrap.FormControl;

var Comment = React.createClass({
  getInitialState: function() {
    return {show: false, newTitle: ''};
  },

  handleTitleSubmit: function(e) {
     e.preventDefault();
     //code to handle input box submit - for example, issue an ajax request to change name in database
  },

  handleTitleChange: function(e) {
    //code to change the name in form input box. newTitle is initialized as empty string. We need to update it with the string currently entered by user in the form
    this.setState({newTitle: e.target.value});
  },

  changeComponent: function() {
    // this toggles the show variable which is used  for dynamic UI
    this.setState({show: !this.state.show});
  },

  render: function() {

    var clickableTitle;

    if(this.state.show) {
        clickableTitle = <Form inline onSubmit={this.handleTitleSubmit}>
                             <FormGroup controlId="formInlineTitle">
                                 <FormControl type="text" onChange={this.handleTitleChange} />
                             </FormGroup>
                         </Form>;
    } else {
        clickableTitle = <div>
                            <Button bsStyle="link" onClick={this.changeComponent}>
                                <h3> Default Text </h3>
                            </Button>
                         </div>;
    }

    return (
        <div className="comment">
            {clickableTitle}
        </div>
    );
  }
});

ReactDOM.render(
    <Comment />, document.getElementById('content')
);

The main part of the code is the clickableTitle variable. Based on the state variable show, it can be either a Form element or a Button element. React allows nesting of components.

So we can place {clickableTitle} in the render function. Based on the value of this.state.show, it displays the corresponding element.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents