Home > Blockchain >  How to declare attribute on custom JSX elements?
How to declare attribute on custom JSX elements?

Time:11-19

Im am creating a ReactJs application and want to combine React components with Web Components.

I declared the CustomElement <layout /> like this:

import { DOMAttributes } from "react";
    
type CustomElement<T> = Partial<T & DOMAttributes<T> & { children: any }>;

declare global {
  namespace JSX {

    interface IntrinsicAttributes {
        columns?: boolean;
    }

    interface IntrinsicElements {
      ['layout']: CustomElement<HTMLDivElement>;
    }
  }
}

Then I use it in my React component like this:

const MyComponent = (props) =>
{
  const { children } = props;

  return (
    <layout columns>
      { children }
    </layout>
  );
};

I also want to add an "columns" attribute to the element, but eslint shows an error.

enter image description here

I cannot figure out how to correctly add an attribute to the element.

CodePudding user response:

You should add columns to your type declaration too:

import { DOMAttributes } from "react";
    
type CustomElement<T> = Partial<T & DOMAttributes<T> & { children: any, columns: boolean }>;

declare global {
  namespace JSX {

    interface IntrinsicAttributes {
      columns?: boolean;
    }

    interface IntrinsicElements {
      ['layout']: CustomElement<HTMLDivElement>;
    }
  }
}
  • Related