Now we will integrate the Bootstrap alert
component with the React controlled component (textarea
) that we developed earlier in Chapter 4, DOM Interaction with ReactJS, where we developed a form with a controlled component. We went through an example of preventing the user writing text into the textarea
above 140
characters.
In the following example, we will see how we can bind alert/warning messages with the same component. Here, we are just extending the developed controlled component.
You might have also have seen the following screenshot in Chapter 4, DOM Interaction with ReactJS, which shows the controlled component with comments in the textarea
. In brackets, you can see the defined character limit:
After adding the alert
component, it will show in the UI when a user reaches the maximum character limit.
For this, first of all, we'll need to enfold the Bootstrap component into the React structure. Let's go through the practical example:
var BootstrapAlert = React.createClass({ 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>Ooops!</strong> You reached the max limit </div> ); } });
We have created a component with the name of BootstrapAlert
and wrapped the HTML inside the render
method.
onClick
is calling the handleClose
function which will handle the close
event. It is the default function of React, as we have the .show()
and .hide()
default functions in JavaScript.
Before we integrate the jQuery Bootstrap component, we must understand the React life cycle methods in the component.