0

How would I declare a proptype definition for an array that can contain a set of different object shapes? e.g.,

If I have a component, e.g., EmailRenderer that takes a prop called called sections that is an array of different objects, each with a unique type and it's associated properties.

const sections = [
    {
        type: "h1",
        copy: "Header!",
    },
    {
        type: "p1",
        copy: "lots of copy....",
    },
    {
        type: "image-main",
        src:
            "http://www.some-image.com",
        alt: "blah",
    },
    {
        type: "button",
        buttonType: "secondary",
        copy: "Watch now!",
        href: "#",
    },
    {
        type: "p1",
        copy: "more copy...",
    },
];

// ...

class EmailRenderer extends React.Component {
  // ...
}

//...

EmailRenderer.propTypes = {
  sections: PropTypes.arrayOf(
    // ???
  )
}

<EmailRenderer sections={sections} />

1 Answer 1

1

Declare classes for each of the "types", let's call them TypographyElement (copy), MediaElement (src), ButtonElement (href).

Then the sections prop can be declared as

sections : PropTypes.arrayOf(
  PropTypes.oneOf(
   [
      PropTypes.instanceOf(TypographyElement), 
      PropTypes.instanceOf(MediaElement), 
      PropTypes.instanceOf(ButtonElement), 
      ...
   ]
  )
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.