Gaurav
Gaurav

Reputation: 2018

how to pass a child component's validated data (as a formik form) to its parent component and handle form submission in parent

Is there a way to pass formik form values from a child component to a parent component and handle form submission in parent component only. I have a use case where I'm building a form for restaurant. The form will have many many fields. So I grouped them and created seperate smaller formik forms component. All the child components' validation schema (yup) are written there inside the child component.

Or if there is any another method to accomplish this task, please let me know.

class FirstChildForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            firstChildFormData: {}
        }
    }

    render() {
        return (
            <Formik
              initialValues={{ }}
              validationSchema={{ }}
              {props => {const {values} = props;
                return(
                 <div>First Form</div>
                )
              }}
            )
      }
}


class SecondChildForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            secondChildFormData: {}
        }
    }

    render() {
        return (
            <Formik
              initialValues={{ }}
              validationSchema={{ }}
              {props => {const {values} = props;
                return(
                 <div>Second Form</div>
                )
              }}
            )
      }
}



export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {
              firstFormData : '',
              secondFormData : '',
            },
        }
    }

    handleSubmit = () => {

    }

    render() {
        return (
            <Formik
              initialValues={{ }}
              validationSchema={{ }}
              {props => {const {values, isSubmitting} = props;
                return(
                 <div className='finalform'>
                   <FirstChildForm />
                   <SecondChildForm />

                    <button onClick={this.handleSubmit}> 
                     Submit</button>
                 </div>
                )
              }}
            )
      }

}

Upvotes: 2

Views: 3385

Answers (1)

Krishnamani
Krishnamani

Reputation: 29

by using props you can achieve this.

Screen 1:

render(
 <View>
          <Screen2
            onValueChange={() => {
              this.setState({formProps: formProps});
            }}
          />
          <FormButton
            formProps={this.state.formProps}
            // @ts-ignore
            onPress={formProps.handleSubmit}
            // tslint:disable-next-line:no-duplicate-string
            title={'checkout'}
          />
        </View>
)

Screen 2:

if (onValueChange) {
     onValueChange(formProps);
 }

Upvotes: 1

Related Questions