If I do
const clicked = () => console.log(“click”);
renderToString(<button onClick={clicked}>Click here</button>
and when I print out the rendered string, all I see is <button>Click here</button>
Is it possible that the JS is not rendered from this function?
renderToString()
gives you your react app in pure HTML as it would look in a particular state. It does not give a fully functionaly react app.
The JS doc renderToString()
says the following:
Render a React element to its initial HTML. This should only be used on the server. React will return an HTML string. You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.
If you call ReactDOM.render() on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
What this means is that renderToString
will never have event handlers in the output. It's meant for you to generate the raw HTML of a page in a particular state on the server, then react can rehydrate those elements will event handlers once loaded on the browser.