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
From what I understood by your question, you want to add additional props to the child components.
This can be achieved using
React.cloneElement()
React.cloneElement() takes the element(component), new props and children as parameter.
I’d suggest passing a function that returns the component instead of passing it directly. It could be something like this:
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