EN
React - get HTML code from rendered component
0 points
In this article, we would like to show you how to get HTML code from a rendered component in React.
To do this, we will use the useRef
hook to store a reference to the div element we'll render. The HTML code can be found in the current.outerHTML
property.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const divRef = React.useRef();
7
React.useEffect(() => {
8
console.log(divRef.current.outerHTML);
9
});
10
return (
11
<div ref={divRef}>
12
Some text inside ...
13
</div>
14
);
15
}
16
17
const root = document.querySelector('#root');
18
ReactDOM.render(<App />, root);
Below is an example with a button - when you click on it, the HTML code will be displayed in the console:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const divRef = React.useRef();
7
const handleClick = () => {
8
console.log(divRef.current.outerHTML);
9
};
10
return (
11
<div ref={divRef}>
12
<button onClick={handleClick}>Get HTML</button>
13
<p>Some text inside ...</p>
14
</div>
15
);
16
}
17
18
const root = document.querySelector('#root');
19
ReactDOM.render(<App />, root);