Availity / availity-reactstrap-validation

Easy to use React validation components compatible for reactstrap.
https://availity.github.io/availity-reactstrap-validation/
MIT License
191 stars 70 forks source link

this.context.FormCtrl is undefined #185

Closed diegodesouza closed 4 years ago

diegodesouza commented 4 years ago

Hey guys,

can someone point me to how to get the form context.

I have tried something like https://github.com/Availity/availity-reactstrap-validation/issues/33 https://stackblitz.com/edit/reactstrap-validation-v2-9hgegg?file=Example.js https://github.com/Availity/availity-reactstrap-validation/issues/103 https://github.com/Availity/availity-reactstrap-validation/issues/92 and https://github.com/Availity/availity-reactstrap-validation/issues/29

@observer
export default class Inquiry extends Component {
  constructor(props) {
    super(props);

    this.form = createRef();
  }

  render() {
    return (
      <Card>
        <CardBody>
          <AvForm onValidSubmit={this.submit} ref={this.form}>
          ... fields go here
          </AvForm>
        </CardBody>
      </Card>
    );
  }
}

What I'm trying to accomplish is reset the form on submit, as well as be able to reset some fields based on user interaction. any help will be highly appreciated.

TheSharpieOne commented 4 years ago

It's ref vs context. You are getting a ref, and you should be able to use that ref to get the context via this.form.current.getChildContext().FormCtrl. That will give you access to the context as defined here: https://github.com/Availity/availity-reactstrap-validation/blob/ec3062beddaa8bb36ca19b4c147d7bf9c1a7d5fc/src/AvForm.js#L130-L148

The context just exposes many of the form methods you could access directly on the ref. If you wanted to reset a specific field you can do this.form.current._inputs[inputName].reset() Check out https://stackblitz.com/edit/reactstrap-validation-v2-42indb?file=Example.js

You can do this in a loop with different inputName values to affect more fields and you can trigger it in your onValidSubmit callback.

diegodesouza commented 4 years ago

@TheSharpieOne excellent thank you for the example

diegodesouza commented 4 years ago

@TheSharpieOne this approach doesn't seem to be working on AvSelectField, how would you go about reseting one?

TheSharpieOne commented 4 years ago

It is working for me. https://stackblitz.com/edit/reactstrap-validation-v2-ksmbn2?file=Example.js Kapture 2020-04-06 at 16 09 02

diegodesouza commented 4 years ago

odd, ok let me double check my logic, thanks again @TheSharpieOne