score:46

Accepted answer

html supports data-* attribute type for custom attributes. you can read about it more here.

definition and usage the data-* attributes is used to store custom data private to the page or application.

the data-* attributes gives us the ability to embed custom data attributes on all html elements.

the stored (custom) data can then be used in the page's javascript to create a more engaging user experience (without any ajax calls or server-side database queries).

the data-* attributes consist of two parts:

  • the attribute name should not contain any uppercase letters, and must be at least one character long after the prefix "data-"
  • the attribute value can be any string

note: custom attributes prefixed with "data-" will be completely ignored by the user agent.

rather than just using size="a4" you can use data-size="a4"

example

<div classname="page" data-size="a4">
  // ....
</div>

score:5

not entirely related, but say you want to accept extra attributes in your custom component, using the spread operator like ...rest. hereĀ“s how you do it:

interface props{
  icon?: string; 
}

type button = props & react.htmlprops<htmlbuttonelement> & react.htmlattributes<htmlbuttonelement>;

function button({ 
  icon,
  ...rest
}: button) {
  return (
    <button 
      {...rest}
    >
     {icon && <span>{icon}</span>}
     {children}       
    </button>
}

score:7

if you are using styled-components, you can do it even simplier:

const app = props => {
  return <styleddiv version={2.0}>my custom div</styleddiv>
}

type custom = {
  version?: number
}

const styleddiv = styled.div<custom>`
  // styles
`

score:15

react type definition file (by default - index.d.ts when staring with create-react-app) contain list of all the standard html elements, as well as known attributes.

in order to allow custom html attributes, you need to define it's typing. do that by expanding htmlattributes interface:

declare module 'react' {
  interface htmlattributes<t> extends ariaattributes, domattributes<t> {
    // extends react's htmlattributes
    custom?: string;
  }
}

possibly related question:

how do i add attributes to existing html elements in typescript/jsx?


Related Query

More Query from same tag