-3

I have a react component like below:

var Dog = React.createClass({
  bark: function() {
    alert('bow');
  },

  render: function() {
    return (<div>Dog</div>);
  }
});

But when I am trying to call the bark method by creating an element of Dog like below:

var doge = React.createElement(Dog, null);
console.log(doge);
doge.bark();

I am getting Uncaught TypeError: doge.bark is not a function. But in chrome's console I can see the bark method in doge object

enter image description here

I am a beginner in react. Can anyone explain what is actually going on behind the scenes?

EDIT:

Actually I want to know why we can not access a component's method from its element created by React.createElement method? Please someone explain this.

Sattyaki
  • 376
  • 2
  • 9
  • 1) You need to spell Dog, dog and doge consistently throughout the program. – SteveB Nov 19 '17 at 16:37
  • Does this answer your question? [How to access component methods from “outside” in ReactJS?](https://stackoverflow.com/questions/24841855/how-to-access-component-methods-from-outside-in-reactjs) – Martin Apr 27 '21 at 14:45

1 Answers1

0

You need to spell and capitalize dog the same way everywhere so Dog, not dog or doge. Then change your render function to call the bark function as follows:

 render: function() {
    return (<div>{this.bark()}</div>);
 }

Although I would change the function from sending an Alert to a console.log.

For your last three lines of code, you are trying to treat a react component as an object. Just call bark before the render as such:

 render: function() {
    this.bark() /*called function on render*/
    return (<div></div>);
 }
SteveB
  • 894
  • 7
  • 15
  • You didn't get my question. My question is that when I am creating an **element** of a **component** by the `React.createElement` method and calling a method of that element it is throwing that error. Why it can not access the method? – Sattyaki Nov 19 '17 at 17:35
  • See: https://stackoverflow.com/questions/24841855/react-js-access-to-component-methods – SteveB Nov 19 '17 at 17:48