14

What's the type of the following statement in React?

let element = <div>Blah blah</div>

I thought I could use element: HTMLElement but when I do, I get Property 'accessKey' is missing in type 'Element'.

What about another imported component?

import Row from './partials/Row';
let row = <Row cols={cols} />

1 Answer 1

8

The type for the div jsx element is HTMLFactory<HTMLDivElement>.

The reference you have isn't for an actual dom element in the browser but for a react element which represent such an element which might not be rendered yet.

The html properties should be accessed through the props:

let element = <div>Blah blah</div>
console.log(element.props.accessKey);

If you'd like to get the dom element you can use the ref attribute:

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument

So:

let divElement: HTMLDivElement;
let element = <div ref={ (el) => { divElement = el; console.log(el); } }>Blah blah</div>

In the case of the imported Row, again, you have a reference to a react element which has a dom representation.
Which properties or methods it has depends on the class itself.

Sign up to request clarification or add additional context in comments.

2 Comments

Well, HTMLDivElement now says property align is missing. I tried to change to span, but I get addEventListener is missing.
Are you sure? For me divElement.align exist. It's part of the lib.d.ts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.