Skip to content

Instantly share code, notes, and snippets.

@gustavoguichard
Created June 10, 2015 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gustavoguichard/e2f88c0adb157f194008 to your computer and use it in GitHub Desktop.
Save gustavoguichard/e2f88c0adb157f194008 to your computer and use it in GitHub Desktop.
Bootstrap Dropdown inside React
////////////////////////////////////////////////////////////////////////////////
// Exercise:
//
// http://getbootstrap.com/javascript/#dropdowns
//
// Wrap Bootstrap Dropdown in a React component and just rely on the declarative
//
// Got extra time?
//
// Allow the parent to manage the state of the dropdown
// - set up an `isShowing` prop
// - when the component mounts, decide to show or hide the dropdown based on the
// `isShowing` prop
// - when the component updates, decide to show or hide the dropdown based on
// the `isShowing` prop
// - synchronize the state back to the parent when the popup closes with an
// `onHide` prop
//
// http://getbootstrap.com/javascript/#dropdowns
////////////////////////////////////////////////////////////////////////////////
import React from 'react';
import $ from 'jquery';
require('bootstrap-webpack');
var Dropdown = React.createClass({
componentDidMount() {
$(this.getDOMNode).on('shown.bs.dropdown', function(event){
this.props.onChange(true);
}.bind(this));
$(this.getDOMNode).on('hidden.bs.dropdown', function(event){
this.props.onChange(false);
}.bind(this));
},
getClasses() {
var classes = ['dropdown'];
if(this.props.isShowing) classes.push('open');
return classes.join(' ');
},
render () {
return (
<div className={this.getClasses()}>
<button ref="dropbutton" className="btn btn-default" data-toggle="dropdown" aria-haspopup="true" aria-expanded={this.props.isShowing}>
{this.props.label}
<span className="caret"></span>
</button>
<ul ref="dropmenu" className="dropdown-menu" role="menu" aria-labelledby="dLabel">
{this.props.children}
</ul>
</div>
);
}
});
var DropdownItem = React.createClass({
render () {
return (
<li>
<a onClick={this.props.onClick}>{this.props.children}</a>
</li>
);
}
});
var App = React.createClass({
getInitialState() {
return {
dropOpen: false
};
},
handleChange(isOpen) {
this.setState({ dropOpen: isOpen });
},
render () {
return (
<div className="container">
<pre>{JSON.stringify(this.state, null, 2)}</pre>
<h1>Dropdown</h1>
<ul className="nav nav-pills">
<li>
<Dropdown onChange={this.handleChange} isShowing={this.state.dropOpen} label="Dropdown Trigger">
<DropdownItem onClick={() => alert('clicked')}>one</DropdownItem>
<DropdownItem>two</DropdownItem>
<DropdownItem>three</DropdownItem>
</Dropdown>
</li>
</ul>
</div>
);
}
});
React.render(<App/>, document.getElementById('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment