skip to Main Content

Let’s say I have a parent component like the following:

<ParentComponent
    contentComponent={
      <GenericContent
        content={<FormContent
          title="Content Title"
          formComponent={<ChildComponent />}
        />}
      />
    }
/>

Now, in my FormContent component, I would like to pass props to my formComponent which in this example is a ChildComponent but can actually be another component.
However, I know that the props I want to pass are always expected in the formComponent component.

const FormContent = ({
  title,
  formComponent,
}: FormContentPropsType) => (
  <>
    <Formik
      enableReinitialize
      validateOnChange={false}
      initialValues={{
        ...formData,
      }}
      validationSchema={SandboxFormValidationSchema}
      onSubmit={sendForm}
    >
      {({
        values,
        setValues,
        errors,
        setErrors,
        handleSubmit,
      }) => (
        <Form>
        {/* Here I would like to use formComponent with the following props :
            formData={values}
            setFormData={setValues}
            formErrors={errors}
            setFormErrors={setErrors}
            handleSubmit={handleSubmit}
        */}
        </Form>
      )}
    </Formik>
  </>

How could I achieve this?

2

Answers


  1. From what I understood by your question, you want to add additional props to the child components.

    This can be achieved using React.cloneElement()

    <Form>
        React.cloneElement(fromComponent,{
                formData={values}
                setFormData={setValues}
                formErrors={errors}
                setFormErrors={setErrors}
                handleSubmit={handleSubmit}
        })
    </Form>
    
    

    React.cloneElement() takes the element(component), new props and children as parameter.

    Login or Signup to reply.
  2. I’d suggest passing a function that returns the component instead of passing it directly. It could be something like this:

    <FormContent formComponent={(props) => <ChildComponent {...props} />} />
    

    I’ve created a simplified example here to show what I mean, hope it’s helpful:

    https://codesandbox.io/p/sandbox/facc-p92mlk?file=%2Fsrc%2FApp.tsx%3A7%2C26

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search