Paras Paras -4 years ago 66
React JSX Question

How to call a function which is inside a class in React?

How can i call a function which is inside a class ?
here is the code -

class FriendList extends Component {
demoFunction()
{
console.log('Inside demo function')
}
render(){
<div>Hello</div>
}
}

const button= () => {
return (
<button onClick={() => demoFunction()}>Button</button>//How can i call demo function here?
);
}

Answer Source

I don't understand what are you trying to do by calling a function of a React Component from another component. I strictly feel you are on the wrong track. But still if want to do that, you can do like this:

class FriendList extends Component {
  static demoFunction() {
    console.log('Inside demo function')
  }

  render() {
    <div>Hello</div>
  }
}

const button = () => {
  return (
    <button onClick={() => FriendList.demoFunction()}>Button</button>
  )
}

Just declare demoFunction as static function and call this with the help of class name i.e FriendList.demoFunction()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download