ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Saturday, November 19, 2022

[FIXED] How to declare attribute on custom JSX elements?

 November 19, 2022     jsx, reactjs   

Issue

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.


Solution

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>;
    }
  }
}


Answered By - Amirhossein
Answer Checked By - - Pedro (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix