skip to Main Content

My current component looks like the following:

interface MyComponentProps {
   children: HTMLSpanElement
}

...

export default function MyComponent({children}: MyComponentProps){
   ...
   return (
      <div>
         {children}
      </div>
   )
}

I want my children to only allow a span, no other element.

Problem is, I get an error underneath {children} telling me that Type HTMLSpanElement is not assignable to ReactNode

It seems this happens with any HTMLElement, giving the error Type HTMLElement is not assignable to ReactNode

I was curious if there’s a way to properly handle such a scenario, or some other method of wanting to set up an instance where I type check to only pass span elements as the child node of a React element.

2

Answers


  1. import React from 'react';
    
    interface MyComponentProps extends React.PropsWithChildren<HTMLSpanElement>  {
      hello: 'world' // if needed some extra props
    };
    
    export default function MyComponent({children}: MyComponentProps){
    
      return (
         <div>
            {children}
         </div>
      )
    }
    
    

    _or using type instead of interface

    type MyComponentProps = React.PropsWithChildren<HTMLSpanElement> & {
      hello: 'world'
    };
    
    Login or Signup to reply.
  2. you can use React's React.ReactElement type along with the React.ReactElementProps utility type. Here’s an example of how you can restrict the children prop to only accept span elements:

    import React, { ReactElement, ReactElementProps } from 'react';
    
    interface MyComponentProps {
    children: ReactElement<ReactElementProps<'span'>>;
    }
    
    export default function MyComponent({ children }: MyComponentProps) {
      return (
       <div>
        {children}
       </div>
      );
    }
    

    Now, when you use MyComponent TypeScript will enforce that only span elements (or components with span-compatible props) can be passed as children. If you try to pass any other element or component, TypeScript will raise a type error.

    like this :

    import React from 'react';
    import MyComponent from './MyComponent';
    
    function App() {
      return (
       <MyComponent>
         <span>Hello, World!</span>
       </MyComponent>
     );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search