Home > Enterprise >  How to convert HTMLElement to JSX.Element
How to convert HTMLElement to JSX.Element

Time:11-24

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!

CodePudding user response:

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.

CodePudding user response:

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);
}
  • Related