Paras
Paras

Reputation: 63

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?
      );
    }

Upvotes: 0

Views: 5644

Answers (1)

Ritesh Bansal
Ritesh Bansal

Reputation: 3238

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()

Upvotes: 1

Related Questions