Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactDOMServer.renderToStaticMarkup full markup

I'm using ReactDOMServer to generate a static site via the server side and it doesn't seem to like this component specifically the opening <!DOCTYPE html> tag. (see below)

I'm doing this as I'm trying to use React to fully render a page via the server-side for IE8 compatibility and eventually become an isomorphic app.

Is there a best practice on how to fully render static markup with React via the server-side (with inclusions of the opening html tags, etc.)?

'use strict';

import React from 'react';

export default class Root extends React.Component {

  render() {
    return (
      <!DOCTYPE html>
      <head>
      <title>Hello World!</title>
      </head>
      <body>

      <h1>Hello World!</h1>

      </body>
      </html>
    );
  }

}

let html = ReactDOMServer.renderToStaticMarkup(<Root />);

Bonus: Although a simple DOCTYPE is breaking it, eventually I'd like to add additional IE tags like below at the top.

<!--[if lt IE 7]>  <html dir="ltr" lang="en-US" class="no-js ie ie6 lte9 lte8 lte7"> <![endif]-->
<!--[if IE 7]>     <html dir="ltr" lang="en-US" class="no-js ie ie7 lte9 lte8 lte7"> <![endif]-->
<!--[if IE 8]>     <html dir="ltr" lang="en-US" class="no-js ie ie8 lte9 lte8"> <![endif]-->
<!--[if IE 9]>     <html dir="ltr" lang="en-US" class="no-js ie ie9 lte9"> <![endif]-->
<!--[if gt IE 9]>  <html dir="ltr" lang="en-US" class="no-js"> <![endif]-->
<!--[if !IE]><!--><html><!--<![endif]-->
like image 496
vutran Avatar asked Dec 01 '25 20:12

vutran


1 Answers

You'll likely want to emit the DOCTYPE header outside of your React component and replace <!DOCTYPE html> with an <html> node. JSX isn't HTML and just maps your elements to a corresponding React.createElement() call, which doesn't make sense for a DOCTYPE.

Take a look at these for reference:

  • Emitting a DOCTYPE before rendering the component

res.send('<!doctype html>\n' + ReactDOM.renderToString(<Html />));

  • An HTML component that handles tag generation

render() { return ( <html lang="en-us"> <head></head> ... </html>) }

like image 147
Gabriel Isenberg Avatar answered Dec 04 '25 10:12

Gabriel Isenberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!