Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
196
rated 0 times [  197] [ 1]  / answers: 1 / hits: 21264  / 8 Years ago, sun, december 25, 2016, 12:00:00

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

More From » reactjs

 Answers
18

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.


[#59566] Thursday, December 22, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamaal

Total Points: 515
Total Questions: 102
Total Answers: 107

Location: France
Member since Thu, May 6, 2021
3 Years ago
;