DEV Community

[Comment from a deleted post]
Collapse
vonheikemen profile image
Heiker

Is more like JSX and javascript are not compatible.

Even if you do manage to send this to the browser:

return (
  <h1>This is a react component</h1>
  <h2>The date is {Date.now()}</h2>
  <h3>Your number from python script is 5</h3>
)
Enter fullscreen mode Exit fullscreen mode

Is not valid javascript. The browser will not understand that.

You can still use both React and Jinja2, but no JSX.

What I would do is pass the state to the component in a script tag. Like this.

<script>
  ReactDOM.render(
    React.createElement(
      App,
      {
        number: {{ number_from_server }}
      }
    ),
    document.getElementById('root')
  );
</script>
Enter fullscreen mode Exit fullscreen mode

Actually I would put all the "state" in a single place.

<script>
  // Jinja needs to give me a JSON object for this to work.
  const state = {{ all_the_state_i_need_from_the_server }}

  ReactDOM.render(
    React.createElement(App, state),
    document.getElementById('root')
  );
</script>
Enter fullscreen mode Exit fullscreen mode
Collapse
ironcladdev profile image
IroncladDev

Ah, that is really smart. Thanks!

Collapse
hamishwhc profile image
HamishWHC

That snippet is valid, provided the parentheses are changed to a React fragment (<> </>):

return <>
  <h1>This is a react component</h1>
  <h2>The date is {Date.now()}</h2>
  <h3>Your number from python script is 5</h3>
</>
Enter fullscreen mode Exit fullscreen mode
Collapse
vonheikemen profile image
Heiker

Even with that, it still isn't valid javascript.