Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS - Call One Component Method From Another Component

I have two components. I want to call a method of the first component from the second component. How can I do it?

Here is my code.

First Component

class Header extends React.Component{      constructor(){         super();     }      checkClick(e, notyId){        alert(notyId);     } }  export default Header; 

Second Component

class PopupOver extends React.Component{      constructor(){         super();         // here i need to call Header class function check click....         // How to call Header.checkClick() from this class     }      render(){         return (             <div className="displayinline col-md-12 ">                 Hello             </div>         );     } }  export default PopupOver; 
like image 296
Kushal Jain Avatar asked Aug 24 '16 09:08

Kushal Jain


1 Answers

You can do something like this

import React from 'react';  class Header extends React.Component {  constructor() {     super(); }  checkClick(e, notyId) {     alert(notyId); }  render() {     return (         <PopupOver func ={this.checkClick } />     ) } };  class PopupOver extends React.Component {  constructor(props) {     super(props);     this.props.func(this, 1234); }  render() {     return (         <div className="displayinline col-md-12 ">             Hello         </div>     ); } }  export default Header; 

Using statics

var MyComponent = React.createClass({  statics: {  customMethod: function(foo) {   return foo === 'bar';   }  },    render: function() {  } });  MyComponent.customMethod('bar');  // true 
like image 119
Mohit Verma Avatar answered Oct 08 '22 01:10

Mohit Verma