4

Here I have something like below as HTMLElement

<div id='hiddenDiv'>
  <div>foobar</div>
</div>

And I am doing something like below trying to convert it into JSX.Element:

function renderMailCompose(): JSX.Element {
    const content = document.getElementById('hiddenDiv');
    return content;
}

but I am getting the error

Type 'HTMLElement' is missing the following properties from type 'ReactElement<any, any>': type, props, key

I am wondering how I can properly convert the div including all its content to JSX.Element. Any help would be appreciated!

flyingbee
  • 601
  • 1
  • 7
  • 17
  • I know this is from a string, but could this help? https://stackoverflow.com/questions/56675652/proper-typescript-type-for-creating-jsx-element-from-string – Bms bharadwaj Nov 24 '21 at 14:01

2 Answers2

0

Generally, unless you have a specific reason for using getElementById, what we usually want to do in-order to store elements inside variables in React, is to use the built-in useRef hook.

So you can do this -

const hiddenDivRef = useRef<HTMLDivElement>(null);

return (
  <div ref={hiddenDivRef}>
    <div>foobar</div>
  </div>
);

After which we can access the value like this -

console.log(hiddenDivRef.current);

You can also use all the relevant functions you would normally have,
i.e. - .focus(), etc...

  • Note: The hook is not exclusive to storing elements.
tomleb
  • 2,409
  • 2
  • 9
  • 24
-2

You can use html-react-parser to render html like this:

npm install html-react-parser --save
import parse from 'html-react-parser';

function renderMailCompose(): JSX.Element {
    const content = document.getElementById('hiddenDiv');
    return parse(content.innerHTML);
}
Abdellah Sabiri
  • 396
  • 3
  • 10