react.js -jquery method does not work

1.9k views Asked by At

The app uses node.js and react.js (namely react-async ). So there is a react component that has a click handler inside which I want to get the class names(namely minus_decrement and inline_block) of that component. I used jQuery inside node.js (details here) as well.

var MinusDecrement=React.createClass({

       clickHandler:function(e){

                    $div = $(this);

                    //$div=this.refs.minusDecElem.getDOMNode();

                    var className=$div.attr('class');
                   // var classNameReact=$div.attr('className');
                    if(window.console){

                     console.log("className = "+className);

                           } 

                   e.stopPropagation();

    },      

    render:function(){

        return (

             <span className="minus_decrement inline_block" onClick={this.clickHandler} >&nbsp;-&nbsp;&nbsp;</span>     

        );

    }

});

When I create the component with the following line

<MinusDecrement></MinusDecrement>

, console output shows undefined. I tried with .attr(className) and this.refs.minusDecElem.getDOMNode() after adding href to the span element but in vain. Both alternate codelines are mentioned in comments.

How to get the class name though jQuery then?

2

There are 2 answers

4
Istiaque Ahmed On

Got the solution myself. The following line

var $div = $(this)

should be replaced with

var $div=$(e.target)

1
daniula On

By calling $(this) you are passing React Component object to jQuery. You should retrieve DOM Node first:

clickHandler: function (e) {
    $div = $(this.getDOMNode());
    var className = $div.attr('class');
    if (window.console) {
        console.log("className = "+className);
    } 
    e.stopPropagation();

}

Also you can use this.refs when you pass ref property to one of elements:

render: function () {
    return (
        <span ref="minusDecElem" className="minus_decrement inline_block" onClick={this.clickHandler} >&nbsp;-&nbsp;&nbsp;</span>     
    );
}