0

I'm fairly new to ReactJS and hitting a problem where I have 2 components, I'll just call them comp1 and comp2. Comp1 renders comp2 and comp2 has a method inside it.

If a button is clicked in comp1 it calls a click handler inside comp1 and I want it to call the method inside comp2 but I keep getting the error this.comp1.myFunc is not a function

Below is the code.

In comp1

class Comp1 extends React.Component
{
    testClick()
    {
        this.comp2Comp.myFunc();
    }

render() {
        const postCommentDisabledState = this.state.newComment.length === 0;

        this.comp2Comp = <Comp2 />

        return (
            <div>
                <button onClick={this.testClick}>Test</button>
                {this.comp2Comp}
            </div>
        )
    }
}

In comp2

class Comp2 extends React.Component
{
    myFunc()
    {
        alert("Testing MyFunc");
    }

    render()
    {
         return (
            <div>comp2</div>
         )
    }
}

Is what I am trying to do possible, if not how would I do what I am trying to achieve?

What the end result is, comp2 has stuff within its state that when a button is pressed in comp1 I can grab the data I need from inside comp2 for comp1 to use.

1 Answer 1

2

Since Comp2 is a child component, you should move its state and myFunc to Comp1. Generally in React you want to use one-way data binding, so all state should be "lifted up" to a parent context. See: https://reactjs.org/docs/lifting-state-up.html

Also, just to note, your render function shouldn't have any side effects like setting properties on the component. See: https://reactjs.org/docs/react-component.html#render

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

1 Comment

I thought that might be the answer, I'm trying to make it so the comp2 could be re-used and the func would always be available - maybe I need to rethink my components. Thanks for the help

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.