1

I'm not using React, so this won't work

ReactDomServer.renderToString(<div>p</div>)

I'm currently rendering the jsx in a hidden div with an id on the browser and then using

document.getElementById(id).outerHTML

to get the HTML, but I'm wondering if there's a more elegant solution

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
chad steele
  • 828
  • 9
  • 13

3 Answers3

2

In SolidJS components actually render as plain DOM nodes, so you can actually just use all of the DOM nodes properties

In your specific example that could be something like

const SomeComponent = <div></div>;
console.log(SomeComponent.outerHTML) //this will output -> "<div></div>"

I hope this helps!

Edlingao
  • 96
  • 3
0

I'm currently rendering the jsx in a hidden div with an id on the browser and then using

document.getElementById(id).outerHTML

to get the HTML, but I'm wondering if there's a more elegant solution

chad steele
  • 828
  • 9
  • 13
0

JSX is not directly supported by the browser so it requires a compiler to be compiled into proper HTML that means you have to use a library like Solid, React ect.

In Solid, you don't need to render it into a hidden div, just don't output it to the DOM.

import { render, renderToString } from "solid-js/web";
import { createSignal } from "solid-js";

function Counter() {
  const [count, setCount] = createSignal(0);
  const increment = () => setCount(count() + 1);

  return (
    <button type="button" onClick={increment}>
      {count()}
    </button>
  );
}


function App() {
  
  let el = <Counter />

  const increment = () => {
    console.log((el.outerHTML));
  };

  return (
    <button type="button" onClick={increment}>
      get content
    </button>
  );
}

render(() => <App />, document.getElementById("app")!);

There is renderToString in Solid to support server side rendering, but it appears it does not work in browsers.

snnsnn
  • 10,486
  • 4
  • 39
  • 44