DrummerGenius
DrummerGenius

Reputation: 545

Difficulty trying to call a method from a parent to a child in React, with the child being an AntD form component

I have a Component titled 'CollectionsPage' where I am trying to create a reference to a child, and call one of its methods via its onClick function.

The reason for this is because I want the child to handle its own state, rather than pass it all down from the parent component. The child is called 'CollectionsCreateForm' and I currently just have a function in it called 'test'. I tried to call the function but it never runs -- however, when I tried the same function from a different component, it worked. Is there something about AntD's form-within-a-modal that is causing me difficulty?

I have tried changing the reference, and I also passed in 'wrappedComponentRef' to child to ensure that wasn't the issue. I need to be able to access form in the child, but AntD says it needs to be passed in as props from the parent. I would love to put the 'onCreate' method in the child, so the modal handles everything that it should without help from the parent, but I believe it needs a reference to the formRef.

I have made an example of my issue on a sandbox. Here is the link.

Upvotes: 0

Views: 169

Answers (1)

Alex Kolarski
Alex Kolarski

Reputation: 3425

When using antd to create a form you basically use the Higher-Order Component - (Form.create(Component)) that wraps your component with the test method inside.

this.testRef.current will refer to your Higher-Order Component basicly Form.create class not your own component.

You can use wrappedComponentRef like so to get reference to your own component:

<CollectionCreateForm
  wrappedComponentRef={(inst) => this.formRef = inst} 
/>

and then simply call this.formRef.test();

Here is a working example: https://codesandbox.io/s/n34ppwnq9j

Upvotes: 1

Related Questions