Component integration

We now understand the component life cycle methods. So now let's integrate our component in React using these methods. Observe the following code:

componentDidMount: function() { 
    // When the component is mount into the DOM 
    $(this.refs.alertMsg).hide(); 
          // Bootstrap's alert events 
// functionality. Lets hook into one of them: 
    $(this.refs.alertMsg).on('closed.bs.alert', this.handleClose); 
  }, 
  componentWillUnmount: function() {  
      $(this.refs.alertMsg).off('closed.bs.alert', this.handleClose); 
  }, 
  show: function() { 
      $(this.refs.alertMsg).show(); 
  }, 
  close: function() { 
      $(this.refs.alertMsg).alert('close'); 
  }, 
  hide: function() { 
      $(this.refs.alertMsg).hide(); 
  }, 
  render: function() { 
      return ( 
      <div className={(this.props.className) + ' alert'} role="alert"
      ref="alertMsg"> 
          <button type="button" className="close" data-dismiss="alert"
          aria-label="Close" onClick={this.handleClose}> 
          <span aria-hidden="true">x</span></button> 
          <strong>Oh snap!</strong> You reached the max limit  
      </div>      
    ); 
  }, 
}); 

Let's see an explanation of the preceding code:

  • The componentDidMount(), by default, is hiding the alert component using the refs keyword when the component mounts in DOM
  • The alert component provides us with some events that are invoked when the close method is called
  • The close.bs.alert is invoked when the close method is called

When we use the component componentWillUnmount, we are also removing the event handler using the jQuery .off. When we click on the close (x) button, it invokes the Closehandler and calls the close

We have also created some custom events that control our component:

  • .hide(): This is for hiding the component
  • .show(): This is for showing the component
  • .close(): This is for closing the alert

Observe the following code:

var Teaxtarea = React.createClass({ 
    getInitialState: function() { 
        return {value: 'Controlled!!!', char_Left: max_Char}; 
    }, 
    handleChange: function(event) { 
        var input = event.target.value; 
        this.setState({value: input.substr(0, max_Char),char_Left:   
        max_Char - input.length}); 
        if (input.length == max_Char){ 
            this.refs.alertBox.show(); 
        } 
        else{ 
        this.refs.alertBox.hide(); 
        } 
    }, 
    handleClose: function() { 
        this.refs.alertBox.close(); 
    }, 
 
    render: function() { 
        var alertBox = null; 
        alertBox = ( 
            <BootstrapAlert className="alert-warning fade in" 
            ref="alertBox" onClose={this.handleClose}/> 
        ); 
        return ( 
            <div className="example"> 
            {alertBox} 
                <div className="form-group"> 
                    <label htmlFor="comments">Comments <span style=
                    {style}>*</span></label(<span{this.state.char_Left}
                    </span> characters left) 
                    <textarea className="form-control" value=
                    {this.state.value} maxLength={max_Char} onChange=
                    {this.handleChange} /> 
                </div> 
            </div> 
        ); 
    } 
}); 
ReactDOM.render( 
    <Teaxtarea />, 
    document.getElementById('alert') 
); 

Using the if condition, we are hiding and showing the alert as per the character length. The handleClose() method will call the close method which we created earlier to close the alert.

Inside the render method, we are rendering our component with the className props, ref key, and onClose props to handle the close method.

The .fade in the class gives us the fading effect when we close the alert.

Now let's combine our code and take a quick look in the browser:

'use strict'; 
var max_Char='140'; 
var style = {color: "#ffaaaa"}; 
 
var BootstrapAlert = React.createClass({  
    componentDidMount: function() { 
        // When the component is added 
        $(this.refs.alertMsg).hide();  
        // Bootstrap's alert class exposes a few events for hooking 
        into modal 
        // functionality. Lets hook into one of them: 
        $(this.refs.alertMsg).on('closed.bs.alert', this.handleClose); 
    }, 
    componentWillUnmount: function() { 
        $(this.refs.alertMsg).off('closed.bs.alert', this.
        handleClose); 
    }, 
    show: function() { 
        $(this.refs.alertMsg).show(); 
    }, 
    close: function() { 
        $(this.refs.alertMsg).alert('close'); 
    }, 
    hide: function() { 
        $(this.refs.alertMsg).hide(); 
    },  
    render: function() { 
        return ( 
            <div className={(this.props.className) + ' alert'}
            role="alert" ref="alertMsg"> 
                <button type="button" className="close" 
                data-dismiss="alert" aria-label="Close" onClick=
                {this.handleClose}> 
                <span aria-hidden="true">×</span></button> 
                <strong>oops!</strong> You reached the max limit  
            </div> 
     
        ); 
    } 
}); 
 
var Teaxtarea = React.createClass({ 
    getInitialState: function() { 
        return {value: '', char_Left: max_Char}; 
    }, 
    handleChange: function(event) { 
        var input = event.target.value; 
        this.setState({value: input.substr(0, max_Char),char_Left: 
        max_Char - input.length}); 
        if (input.length == max_Char){ 
            this.refs.alertBox.show(); 
        } 
        else{ 
            this.refs.alertBox.hide(); 
        } 
    }, 
    handleClose: function() { 
        this.refs.alertBox.close(); 
    }, 
 
    render: function() { 
        var alertBox = null; 
        alertBox = ( 
            <BootstrapAlert className="alert-warning fade in"
            ref="alertBox"/> 
        ); 
        return ( 
            <div className="example"> 
            {alertBox} 
                <div className="form-group"> 
                    <label htmlFor="comments">Comments <span style=
                    {style}>*</span></label>(<span
                    {this.state.char_Left}</span> characters left) 
                    <textarea className="form-control" value=
                    {this.state.value} maxLength={max_Char} onChange=
                    {this.handleChange} /> 
                </div> 
            </div> 
        ); 
    } 
}); 
ReactDOM.render( 
    <Teaxtarea />, 
    document.getElementById('alert') 
);

Observe the following screenshot:

Component integration

When we click on the close (x) button, it invokes the Closehandler and calls the close event to close the alert message. Once closed, to get it back you will have to refresh the page. Please observe the following screenshot:

Component integration

Note

Using console.log(), we can verify if our component is mounted or unmounted.

Now let's take a look at another example of the Bootstrap component.

Bootstrap modal

The Bootstrap modal component displays a small amount of information to the user without taking you to a new page.

The following table from the Bootstrap website (http://getbootstrap.com/javascript) shows the full list of options available for the modal:

Name

Type

Default

Description

backdrop

Boolean

true

backdrop allows us to close the modal when the user clicks outside. It gives a static value for a backdrop which doesn't close the modal on click.

keyboard

Boolean

true

Presses the Esc key to close the modal.

show

Boolean

true

Initializes the modal.

remote

PATH

false

This option has been deprecated since version 3.3.0 and has been removed in version 4. For client-side templating it is recommended to use the data binding framework, or call jQuery.load yourself.

The following table from the Bootstrap website (http://getbootstrap.com/javascript) shows the full list of events available for the Bootstrap modal component:

Event type

Description

show.bs.modal

This event fires immediately when the show ($('.modal').show();) instance method is called.

shown.bs.modal

This event is fired when the modal has been made visible to the user (we need to wait for CSS transitions to complete).

hide.bs.modal

This event is fired immediately when the hide ($('.modal').hide();) instance method has been called.

hidden.bs.modal

This event is fired when the modal has finished being hidden from the user (we need to wait for CSS transitions to complete).

loaded.bs.modal

This event is fired when the modal has loaded content using the remote option.

Whenever we are integrating any other component, we must be aware of the component options and events provided by the library or plugin.

First, we need to create a button component to open a modal popup:

// Bootstrap's button to open the modal 
var BootstrapButton = React.createClass({ 
    render: function() { 
        return ( 
            <button {...this.props} 
            role="button" 
            type="button" 
            className={(this.props.className || '') + ' btn'} /> 
        ); 
    } 
}); 

Now, we need to create a component of modal-dialog and mount the button and dialog component to the DOM.

We will also create some events that handle the show and hide modal events:

var BootstrapModal = React.createClass({ 
    componentDidMount: function() { 
        // When the component is mount into the DOM 
        $(this.refs.root).modal({keyboard: true, show: false}); 
 
        // capture the Bootstrap's modal events 
        $(this.refs.root).on('hidden.bs.modal', this.handleHidden); 
    }, 
    componentWillUnmount: function() { 
        $(this.refs.root).off('hidden.bs.modal', this.handleHidden); 
    }, 
    close: function() { 
        $(this.refs.root).modal('hide'); 
    }, 
    open: function() { 
        $(this.refs.root).modal('show'); 
    }, 
    render: function() { 
        var confirmButton = null; 
        var cancelButton = null; 
 
    if (this.props.confirm) { 
        confirmButton = ( 
            <BootstrapButton 
                onClick={this.handleConfirm} 
                className="btn-primary"> 
                {this.props.confirm} 
            </BootstrapButton> 
        ); 
    } 
    if (this.props.cancel) { 
        cancelButton = ( 
            <BootstrapButton onClick={this.handleCancel} className=
            "btn-default"> 
            {this.props.cancel} 
            </BootstrapButton> 
        ); 
    } 
 
    return ( 
        <div className="modal fade" ref="root"> 
        <div className="modal-dialog"> 
        <div className="modal-content"> 
        <div className="modal-header"> 
        <button 
            type="button" 
            className="close" 
            onClick={this.handleCancel}> 
            &times; 
        </button> 
        <h3>{this.props.title}</h3> 
        </div> 
        <div className="modal-body"> 
            {this.props.children} 
        </div> 
        <div className="modal-footer"> 
            {cancelButton} 
            {confirmButton} 
</div> 
</div> 
</div> 
</div> 
    ); 
  }, 
  handleCancel: function() { 
      if (this.props.onCancel) { 
          this.props.onCancel(); 
      } 
  }, 
  handleConfirm: function() { 
      if (this.props.onConfirm) { 
          this.props.onConfirm(); 
      } 
  }, 
  handleHidden: function() { 
      if (this.props.onHidden) { 
          this.props.onHidden(); 
      } 
  } 
}); 

In componentDidMount(), we are initializing the modal component with some options and injecting the hidden.bs.modal event into modal.

The close() and show() functions trigger the model hide/show event.

Inside the render() method, we include the modal HTML template with the props and ref key to manipulate the template.

handleCancel(),handleConfirm(), and handleHidden() handle every state of our component.

.modal-* classes give us Bootstrap's style to make our app more user-friendly.

Now we need to render our components using the render function:

var ReactBootstrapModalDialog = React.createClass({ 
    handleCancel: function() { 
        if (confirm('Are you sure you want to cancel the dialog 
        info?')) { 
            this.refs.modal.close(); 
        } 
    }, 
    render: function() { 
        var modal = null; 
        modal = ( 
            <BootstrapModal 
                ref="modal" 
                confirm="OK" 
                cancel="Cancel" 
                onCancel={this.handleCancel} 
                onConfirm={this.closeModal} 
                onHidden={this.handleModalDidClose} 
                > 
                This is a React component powered by jQuery and                      Bootstrap! 
            </BootstrapModal> 
        ); 
        return ( 
            {modal} 
            <BootstrapButton onClick={this.openModal} className="btn-
            default"> 
            Open modal 
            </BootstrapButton> 
        ); 
    }, 
    openModal: function() { 
        this.refs.modal.open(); 
    }, 
    closeModal: function() { 
        this.refs.modal.close(); 
    }, 
    handleModalDidClose: function() { 
        alert("The modal has been dismissed!"); 
    } 
}); 

We are passing props in <BootstrapModal> and rendering <BootstrapButton>.

With the this keyword, we call a function to invoke the modal events and display an alert on every event fire:

ReactDOM.render(<ReactBootstrapModalDialog />, 
document.getElementById('modal')); 

Let's take a quick look at our component in the browser:

Bootstrap modal

Oops! We are getting an error. I think that might have happened because we have not wrapped our component inside the render method. It should always wrap with one parent element:

return ( 
    <div className="modalbtn"> 
        {modal} 
    <BootstrapButton onClick={this.openModal} className="btn-default"> 
        Open modal 
    </BootstrapButton> 
    </div> 
); 

Here's what our ReactBootstrapModalDialog component looks like after we've made a small change:

var ReactBootstrapModalDialog = React.createClass({ 
    handleCancel: function() { 
        if (confirm('Are you sure you want to cancel?')) { 
            this.refs.modal.close(); 
        } 
    }, 
    render: function() { 
        var modal = null; 
        modal = ( 
            <BootstrapModal 
                ref="modal" 
                confirm="OK" 
                cancel="Cancel" 
                onCancel={this.handleCancel} 
                onConfirm={this.closeModal} 
                onHidden={this.handleModalDidClose} 
                > 
                This is a React component powered by jQuery and
                Bootstrap! 
            </BootstrapModal> 
        ); 
        return ( 
            <div className="modalbtn"> 
                {modal} 
                <BootstrapButton onClick={this.openModal} 
                className="btn-default"> 
                    Open modal 
                </BootstrapButton> 
            </div> 
        ); 
    }, 
    openModal: function() { 
        this.refs.modal.open(); 
    }, 
    closeModal: function() { 
        this.refs.modal.close(); 
    }, 
    handleModalDidClose: function() { 
        alert("The modal has been dismissed!"); 
    } 
}); 
 
ReactDOM.render(<ReactBootstrapModalDialog />, document.getElementById('modal')); 

Let's take a quick look at our component again in the browser:

Bootstrap modal

Now click the Open modal button to see the modal dialog box:

Bootstrap modal

If we click on the Cancel or the OK button, it will display the alert box as shown in the following screenshot:

Bootstrap modal

If we click on the X icon, it will display the alert box as shown in the following screenshot:

Bootstrap modal

So, now we know that we can close the modal dialog by clicking on the (X) icon.

When the modal dialog is closed, it shows the alert, The modal has been dismissed! See the following screenshot:

Bootstrap modal

Here is what our HTML file looks like:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>J-Query Bootstrap Component with React</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-sm-6">
                    <h2>jQuery Bootstrap Modal with React</h2>
                    <hr/>
                    <div id="modal">
                    </div>
                </div>
            </div>
        </div>
        <script type="text/javascript" src="js/jquery-1.10.2.min.js">
        </script>
        <script type="text/javascript" src="js/bootstrap.min.js">
        </script>
        <script type="text/javascript" src="js/react.min.js"></script>
        <script type="text/javascript" src="js/react-dom.min.js">
        </script>
        <script src="js/browser.min.js"></script>
        <script src="component/modal.js" type="text/babel"></script>
    </body>
</html>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset