Boardy
Boardy

Reputation: 36205

Calling a method inside a react component from another react component

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.

Upvotes: 0

Views: 50

Answers (1)

Ethan Lipkind
Ethan Lipkind

Reputation: 1156

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

Upvotes: 2

Related Questions