0

I'm searching for a way to retrieve the type of my children's prop. I've created a component that can receive as children a single react element or an array of React elements with specific props. According to the type of my children, I need to perform different actions. How can I understand the type of my children?

const CodeFragmentsWrapper: React.FC<{ children?: React.ReactElement<MyProps> | React.ReactElement<MyProps>[] }> = (props) => {
  return (
    <div>
      {
        children.isAnArray //HOW TO DO THIS? (or something similar)
        ? //DO SOMETHING
        : //DO SOMETHING ELSE
      }
    </div>
  );
}
AndreaCostanzo1
  • 1,799
  • 1
  • 12
  • 30
  • 2
    `Array.isArray(children)` – D Pro Apr 13 '21 at 16:19
  • 1
    Does this answer your question? [Detecting React children array length in Typescript](https://stackoverflow.com/questions/66738411/detecting-react-children-array-length-in-typescript) – Ajeet Shah Apr 13 '21 at 16:23
  • add a check for undefined children https://www.typescriptlang.org/play?ssl=1&ssc=1&pln=12&pc=2#code/JYOwLgpgTgZghgYwgAgBIFcC2cTIN4CwAUMqciHJhAFzIDOYUoA5gNzFnJzM3lYBG0dkQC+xYjHQgEYYAHtcAdwAWcgBTKsOOgH5aGbLgA+aLSADaAXQCU+DmWAwNZutcIkyAQShQ4ATwA6YDpvXz9nQ1dke1IdZE1I8wAGSwCKKhjkWgTtNMoITLFRIA – D Pro Apr 13 '21 at 16:24
  • Array.isArray works but it doesn't allow me to recognize the type of my props – AndreaCostanzo1 Apr 13 '21 at 16:34
  • You will never be able to get the props type for `JSX` children. The `ReactElement` type only gets the generic set when called with `React.createElement`. It is much easier if your children are functions or components instead of elements. – Linda Paiste Apr 14 '21 at 01:12
  • These answers might help you: [Is there a way to extract the type of the props of a JSX Element?](https://stackoverflow.com/a/66754751/10431574) and [TypeScript and JSX don't understand cases when I want to set specific props](https://stackoverflow.com/a/64180136/10431574) – Linda Paiste Apr 14 '21 at 01:15

0 Answers0