1

I have a child component which is a Redux form and from it's handleSubmit method, I need to call a method on the Parent Component. I try to do this by passing a callback as props from the Parent and nothing happens.

I've seen that this method works only when a function is called directly with an event handler on the child component.

import Parent from './parent.js';
class Child extends React.Component {
    constructor(props) {
        super(props);
        };

    callCloseModal = () => {
        this.props.closeModal();
    }

    handleFormSubmit (values) {
        this.callCloseModal()    
    }

    render() {
         <form onSubmit= 
            {handleSubmit(this.handleFormSubmit.bind(this))}>
            .....
         </form>
    }
}

class Parent extends React.Component {
      constructor (props) {
        super(props)
        this.state = {
          modalOpen: false,
        }
      }
     .....

    handleModalClose() {
        this.setState({ modalOpen: false })
    }

    render() {
          <Child closeModal={this.handleModalClose}> {this.props.children}</Child>
    }
}

How can I call a method on the parent component from a method on a child component?

Edit: The method was correct but it was one level higher (Grandparent component)

Glen Padua
  • 487
  • 1
  • 7
  • 14

3 Answers3

1

In your onSubmit handler:

render() {
     <form onSubmit= 
        {handleSubmit(this.handleFormSubmit.bind(this))}>
        .....
     </form>
}

You call handleFormSubmit, but in its definition:

handleFormSubmit (values) {
    this.callCloseModal    
}

You only reference the callCloseModal. Notice callCloseModal is defined as an arrow function:

callCloseModal = () => {
    this.props.closeModal();
}

So you need to call it. Try:

handleFormSubmit (values) {
    this.callCloseModal();
}
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
0

I guess this would work as expected. Just call callCloseModal as a function inside handleFormSubmit

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

    callCloseModal = () => {
        // ideally you want to check if props is a func
        if (typeof this.props.closeModal === 'function') {
            this.props.closeModal();
        }
    }

    handleFormSubmit = (values) => { // no need to mix binding with arrow funcs
        this.callCloseModal() // should be calling as a function
    }

    render() {
         <form onSubmit= 
            {handleSubmit(this.handleFormSubmit)}>
            .....
         </form>
    }
}
JCQuintas
  • 1,060
  • 1
  • 8
  • 18
0

you just have to change the function from this

callCloseModal = () => {
    this.props.closeModal();
}

to this

callCloseModal = () => {
    this.props.handleModalClose();
}

Let me know if you face any other issue.

Aniruddh Agarwal
  • 900
  • 1
  • 7
  • 22