Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js and bootstrap modal from examples on github

I'm trying to set up an app with react and everything is going well except for my modal. I've used this code from the following link, untouched and I get errors. https://github.com/facebook/react/blob/master/examples/jquery-bootstrap/js/app.js

Try this fiddle http://jsbin.com/eGocaZa/1/edit?html,css,output

The callback functions don't seem to have access to "this". If you log "this" in the console, it logs the window object.

openModal: function() {
  this.refs.modal.open();
},

I did pass in this and return a new function which seemed to work but that didn't seem right and not playing nice with jsfiddle. I got the modal firing locally but then I run into the same issue with the close function. Any help would be appreciated. Thanks!

var Example = 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}
        title="Hello, Bootstrap!">
        This is a React component powered by jQuery and Bootstrap!
      </BootstrapModal>
    );
    return (
      <div className="example">
          {modal}
        <BootstrapButton onClick={this.openModal(this)}>Open modal</BootstrapButton>
      </div>
    );
  },

  openModal: function(obj) {
    return function(){obj.refs.modal.open();}
  },

  closeModal: function() {
    this.refs.modal.close();
  }
});
like image 890
BrettAHale Avatar asked Aug 16 '26 04:08

BrettAHale


1 Answers

I found a few problems with your code:

  1. You were loading the Bootstrap JS before jQuery but it needs to be loaded after.
  2. You were using React 0.3.0, which had different scoping rules for component methods -- since React 0.4, methods are bound to the component automatically. You could have written openModal: React.autoBind(function() { this.refs.modal.open(); }) or onClick={this.openModal.bind(this)} in React 0.3 but upgrading to 0.4 removes the necessity to bind manually.
  3. Your modal had the hide class which seemed to make it invisible; I removed it and now the modal seems to appear. I'm not sure at the moment why this behaves differently between your code and the example.

Here's my working example jsbin . The modal appears to have some strange CSS applied to it but I don't think it's React-related so I'll leave you here. Let me know if anything's unclear.

like image 194
Sophie Alpert Avatar answered Aug 17 '26 18:08

Sophie Alpert