Home > Blockchain >  React with Typescript: Property 'name' does not exist on type 'DetailedHTMLProps<H
React with Typescript: Property 'name' does not exist on type 'DetailedHTMLProps<H

Time:05-17

I started using React with Typescript and I'm trying to add a "name" property to a "div" but Typescript is complaining about that and won't allow me to add it because that property doesn't exist.

This is the full message I get back:

Type '{ children: Element[]; name: string; className: string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.
  Property 'name' does not exist on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'.ts(2322)

How can I solve it? Here is an example of the .tsx file:

import React from "react";

export default function TestComponent() {
    return <div name="component-name">Test</div>;
}

I'm using the library react-scroll that requires a name property on the component.

CodePudding user response:

I'm using the library react-scroll that requires a name property on the component.

You've misread the documentation.

Here is a quote from it:

var Scroll   = require('react-scroll');
var Element  = Scroll.Element;
var scroller = Scroll.scroller;

<Element name="myScrollToElement"></Element>

It requires a name prop on an Element component (which is provided by the library), not on a div.

CodePudding user response:

The error is correct, HTMLDivElement has no name property, and name is an invalid attribute for div elements.

If you want to put non-standard, non-visible information on an element, use a data-* attribute:

<div data-name="component-name">Test</div>

...and if you need to retrieve its value from the DOM element (for instance, via a ref), use getAttribute or dataset.

  • Related