0

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
3
  • 1
    Please take the time to write a proper MCVE showing also the parent component. Educated guess: if the function is defined in the CHILD component then how can it be called/available in the PARENT? Commented Jul 13, 2020 at 10:59
  • 1
    Please, provide the code for parent component Commented Jul 13, 2020 at 11:00
  • Fair point, will take the time to provide more code on this issue Commented Jul 13, 2020 at 11:06

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.