1

I'm trying to apply styling through jquery in react component however i'm getting error Uncaught TypeError: this.getDOMNode is not a function

topicsVisited(arr){
         $(function() {
          $.each(arr, function(key, eachVisitedTopic) {
            console.log(eachVisitedTopic);
            $(this.getDOMNode()).find('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
              'background-color': 'red'
            });
          });
        });
      };
Rahul Dagli
  • 4,301
  • 15
  • 47
  • 85

2 Answers2

1

You need to bind your functions in order to use this properly.

topicsVisited(arr) {
    $(function() {
        $.each(arr, function(key, eachVisitedTopic) {
            console.log(eachVisitedTopic);
            $(this.getDOMNode()).find('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({'background-color': 'red'});
        }.bind(this));
    }.bind(this);
}

or create a variable that references the correct this.

topicsVisited(arr) {
    var self = this;
    $(function() {
        $.each(arr, function(key, eachVisitedTopic) {
            console.log(eachVisitedTopic);
            $(self.getDOMNode()).find('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({'background-color': 'red'});
        });
    };
}
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
  • Now i'm getting 2 errors `Warning: getDOMNode(...) is deprecated in plain JavaScript React classes. Use ReactDOM.findDOMNode(component) instead.` and `Uncaught TypeError: self.getDOMNode is not a function` – Rahul Dagli Feb 16 '16 at 12:57
  • 1
    Yes, `getDOMNode` is deprecated in favour of `findDOMNode` from the `react-dom` package. `npm install react-dom --save` and change from `this.getDOMNode()` to `ReactDOM.findDOMNode(self)` will do the trick! – Henrik Andersson Feb 16 '16 at 14:17
1

Try this

topicsVisited(arr){
         var ReactDom = require('react-dom');
         var self = this;
         $(function() {
          $.each(arr, function(key, eachVisitedTopic) {
            console.log(eachVisitedTopic);
            $(ReactDOM.findDOMNode(self)).find('.single-topic[data-topic-id="' + eachVisitedTopic + '"]').css({
              'background-color': 'red'
            });
          });
        });
      };
John_West
  • 2,239
  • 4
  • 24
  • 44
  • Still not working although it not showing any error in console. console.log output `[prevObject: jQuery.fn.init[1], context: div.row, selector: ".single-topic[data-topic-id="4"]"]` – Rahul Dagli Feb 16 '16 at 13:23
  • I think the styling is getting overridden while mount and unmounting of components. – Rahul Dagli Feb 16 '16 at 13:29