react using jquery to slideToggle

I'm trying to learn some React by making a menu with collapsable items. I'm using jQuery for its slideToggle function but I cant get it to work right.

the relevant part of the react code is this:

var CollapsableMenuItem = React.createClass({
    toggleDescription: function(el) {
    render: function() {
        return (
                <label className='title' 
                <div className='description'>

althought I'm currently trying to slide toggle "this", that will need to change in the future to


because that's the actual element that needs to slide toggle

Whats the correct way of binding "this [element]" so jQuery can do its slideToggling on it?

I'm currently working out of this fiddle, theres some other stuff in there you can ignore. The relevant code is at the bottom of the javascript section

a second question that comes to mind: is it bad practice to use the jQuery.ready function to bind click events etc... with react?

theoretically I can bundle a jquery file with each component file with its event handlers.



The context of this in React isn't the element, it's the React component. jQuery doesn't understand how to use it as a selector.

You'll need to get a reference to the element you want to control with jQuery.

makeTogglable: function(element) {
  $element = $(element);

  this.toggle = function() {
render: function() {
  return (
      <label onClick={this.toggle}></label>
      <div ref={this.makeTogglable}></div>

The ref prop takes a callback, which will run when the component is mounted. The DOM element will be passed to the callback, so that you can work with it directly.

In this case, we use it to create and expose a new this.toggle method, which calls .slideToggle on the element.

Finally, we pass the new this.toggle method to the onClick handler for the element that we want to trigger the toggle. In this case it's the <div>.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.