Search code examples
javascriptreactjscomponents

React not calling function from another component?


I believe I am trying to accomplish something simple but failing to do so.

React is not calling the 'alertFunc()' from the ChildComponent from another component like I hoped it would.

Here is the ChildComp:

class ChildComp extends React.Component {
    constructor(props) {
        super(props);
        this.state = { };
        this.input = React.createRef();
    }

    alertFunc = () => {
        alert('This function is called from the Child Component');
    };

    handleChange = () => {
        this.alertFunc();
    };

    render() {
        return (
            <ChildComp onChange={this.handleChange} />
        );
    }
}

Then I'm trying to call it from a parent compolike:

render(props){

    return(
        <button onClick={props.alertFunc()}>Next</button>
    );

}

And the error I get is:

props.alertFunc is not a function

Solution

  • You can't call an instance function of a child component from a parent component like that, you don't have access to that function from the parent. If you wish both components to have access to it (parent and child) you should share it somehow between them, using context at a more upper-level if the hierarchy is deeply nested, or define it in the parent and pass it to the child via props or use redux. Or if doesn't depend on component state move it out of the component.