Skip to content

Commit 214e88d

Browse files
committed
overridable: add dynamicParametrize function
* Added a function to 'dynamically' parametrize a component, based on values from the context. Currently, this includes the field values stored in Formik, but we can easily add more values from the React context as needed. * The user can implement a function that receives these input values and returns the override props for a given `Overridable` component. They need to import the `dynamicParametrize` function from the top level of this module, as well as the component they want to override. * `dynamicParametrize` might currently throw an error if used on a component that's rendered outside of the Formik context
1 parent 52e9351 commit 214e88d

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

src/lib/utils/fieldComponents.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { useFormikContext } from "formik";
2+
import * as React from "react";
3+
4+
export function dynamicParametrize(Component, propsFactory) {
5+
const ParametrizedComponent = (props) => {
6+
const { values } = useFormikContext();
7+
const extraProps = propsFactory({ formValues: values });
8+
9+
// Store the original component in an attribute
10+
if (Component.originalComponent) {
11+
Component = Component.originalComponent;
12+
}
13+
14+
// overrideProps override props if there is a name collision
15+
const { children, ...attrProps } = { ...props, ...extraProps };
16+
return React.createElement(Component, attrProps, children);
17+
};
18+
19+
const name = Component.displayName || Component.name;
20+
ParametrizedComponent.displayName = `Parametrized(${name})`;
21+
return ParametrizedComponent;
22+
}

src/lib/utils/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export { humanReadableBytes } from "./humanReadableBytes";
22
export { dropdownOptionsGenerator } from "./dropdownOptionsGenerator";
3+
export { dynamicParametrize } from "./fieldComponents";

0 commit comments

Comments
 (0)