Jenkins
Jenkins

Reputation: 83

Call a function in a sibling component Reactjs

There are 3 components. First one is the parent component called A. The others are X and Y.

X is a toolbar component that has a Save button. And Y is a Form component that has some inputs (obviously). And both of them are imported and rendered in A.

So what I am trying to do is when the Save button in X clicked, I want the Form in the B to be submitted.

Thanks in advance.

Upvotes: 4

Views: 4520

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281686

You can communicate with the parent from child and vice versa.

What you need to do is pass a handler to Component X from Component A and then in this handler using refs you can access the Child component form and trigger a submit like

A:

class A extends React.Component {
    constructor(props) {
        super(props);
    }
    buttonSubmit = () => {
           this.Yform.childForm.submit()

    }
    render() {
          return <div>
                <X triggerSubmit={this.buttonSubmit}/>
                <Y ref={(form) => this.Yform = form}/>
           </div>
    }
}

X

class X extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
          return <div>
                <button onClick={() => this.props.triggerSubmit()}>Submit</button>
           </div>
    }
}

Y:

class Y extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
          return <div>
                <form ref={(childForm) => {this.childForm = childForm}}>
                    ...
                </form>
           </div>
    }
}

In case you are using Redux, then you need to do call an onSubmit like

  this.YForm.getWrappedInstance().submit()

Upvotes: 5

Related Questions