asif.ibtihaj
asif.ibtihaj

Reputation: 391

Call method of parent class component from child class component

I've got a method addNotification() at App.js which I want to reuse in some of my other components. Here I used AgencyProfile component for example. It doesn't work if I export the addNotification() method from App.js. How can I call the method addNotification() from other child components, here for example AgencyProfile? here is my App.js code

export class App extends React.Component{

.....

        addNotification(title, message, level, time) {
        let dismiss = (time === undefined) ? 0 : time;
        this.notification.addNotification({
            title: title,
            message: message,
            level: level,
            autoDismiss: dismiss
        });
    }
.......

render() {

        return (
            <div>
                <NotificationSystem ref={ref => this.notification = ref}/>
                <AgencyProfile />

            </div>
        );
    }

}

Upvotes: 1

Views: 82

Answers (2)

Alberto Perez
Alberto Perez

Reputation: 2922

Yeah, this is possible if you pass the function addNotification as a prop (callback) for the component in which you want to reuse the function as:

App.js:

export class App extends React.Component{

.....

addNotification = (title, message, level, time) => {
        let dismiss = (time === undefined) ? 0 : time;
        this.notification.addNotification({
            title: title,
            message: message,
            level: level,
            autoDismiss: dismiss
        });
    };

.......

render() {
        return (
            <div>
                <NotificationSystem ref={ref => this.notification = ref}/>
                <AgencyProfile onAddNotification={this.addNotification} />
                .....

            </div>
        );
    }
}

And in the child component we can just make a method like this to call addNotification() method in the App.js

AgencyProfile.js

showNotification(title, message, level, time){
    this.props.onAddNotification(title, message, level, time);
}

use this method to call addNotification() from anywhere inside AgencyProfile component.

Another approach is to make addNotification() a exportable function in another js file and them import it in the component where you want to use it (But with this approach you'll have to bind this depending on where you are going to use it):

import addNotification from 'helpers/addNotification';

Upvotes: 2

Brian Thompson
Brian Thompson

Reputation: 14365

You can't really export/import a function like that. If you don't want to pass it down the tree as a prop, your best bet will be to use react's context https://reactjs.org/docs/context.html. Then instead of importing a function, you will just get it from context.

Upvotes: 0

Related Questions