Skip to content

Commit

Permalink
feat(utils): allow object props to make it to the component (#99)
Browse files Browse the repository at this point in the history
  • Loading branch information
robin-ray authored Mar 16, 2023
1 parent e660b6e commit f872ccc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
14 changes: 4 additions & 10 deletions src/utils/mjml-component-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ import kebabCase from "lodash.kebabcase";

const DANGEROUSLY_SET_INNER_HTML = "dangerouslySetInnerHTML";

type MJMLDangerouslySetInnerHTML = {
__html: string;
};

export function convertPropsToMjmlAttributes<P>(props: {
[K in keyof P]: unknown;
}) {
Expand All @@ -23,7 +19,7 @@ export function convertPropsToMjmlAttributes<P>(props: {
mjmlProps[mjmlProp] = mjmlValue;
}
return mjmlProps;
}, {} as Record<string, string | MJMLDangerouslySetInnerHTML>);
}, {} as Record<string, string | object>);

// className is a special prop used extensively in react in place of the html class attribute.
// mjml uses a different name (css-class) for the same thing.
Expand Down Expand Up @@ -57,21 +53,19 @@ const numberToPixel = [
"text-padding",
];

const allowObject = [DANGEROUSLY_SET_INNER_HTML];

function convertPropValueToMjml(
name: string,
value: unknown
): string | MJMLDangerouslySetInnerHTML | undefined {
): string | object | undefined {
// This assumes that all numbers will be pixels which might not always be the case
if (typeof value === "number" && numberToPixel.includes(name)) {
return `${value}px`;
}
if (typeof value === "boolean" && booleanToString.includes(name)) {
return name;
}
if (typeof value === "object" && allowObject.includes(name)) {
return value as MJMLDangerouslySetInnerHTML;
if (typeof value === "object" && value !== null) {
return value;
}
if (typeof value === "string") {
return value;
Expand Down
14 changes: 12 additions & 2 deletions test/mjml-props.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,22 @@ describe("mjml components prop values", () => {
).toBe('<mj-column border-radius="5px dashed blue">Column1</mj-column>');
});

it("object prop value type does not make it to the component", () => {
it("object prop value type does make it to the component", () => {
const { MjmlSpacer } = mjmlComponents;
expect(
renderToMjml(
// @ts-expect-error invalid prop value type of object on height
<MjmlSpacer height={{ someValue: 10 }} />
<MjmlSpacer height={{ toString: () => "10px" }} />
)
).toBe('<mj-spacer height="10px"></mj-spacer>');
});

it("null prop value does not make it to the component", () => {
const { MjmlSpacer } = mjmlComponents;
expect(
renderToMjml(
// @ts-expect-error invalid prop value type of object on height
<MjmlSpacer height={null} />
)
).toBe("<mj-spacer></mj-spacer>");
});
Expand Down

0 comments on commit f872ccc

Please sign in to comment.