Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jinja2 server side rendering alongside react without violating inline-script CSP

I am new to React and experimenting a bit. I would like to use it on my Flask site that uses Jinja2 templates.

People seem to recommend to render data on the server-side first instead of having to always make an initial call for data on page load. I found this nodejs example but it just puts the data on the page in a global variable in an inline script tag. I was wondering if there was a clean way to do this other than just putting the data on the page inside an inline script tag. Because of my secure CSP policy I can't use inline scripts or eval.

Is there an standard pattern people use to render data for React on the server without using an inline variable?

like image 628
anthony-dandrea Avatar asked Sep 21 '15 22:09

anthony-dandrea


1 Answers

You can certainly use it on sites that have server side rendering via Jinja. The question becomes - what do you want to update on the page without reloading? Usually, the component state in React is updated via user interaction or a changing data source (i.e. db API).

My experience has been to render (via Jinja) the static page data and then use React components to update based on and/or listen for changes to the state of an API (maybe through Flask-Restful). These APIs can be accessed through React's life cycle methods (usually 'getInitialState' or 'setState')

For example - you may have portions of your site that are rendered server-side in layout.html and then the {% block content %} is rendered client side by the React js components.

{% extends "layout.html" %}


{% block content %}

<h2>Some Header</h2>

<script type="text/jsx" src="/scripts/ReactComponent1.js">
</script>

<div id="one">
<!-- This element's contents will be replaced with ReactComponent1. -->
</div>

<script type="text/jsx" src="/scripts/ReactComponent2.js">
</script>

<div id="two">
<!-- This element's contents will be replaced with ReactComponent2. -->
</div>



{% endblock %}

I really recommend going through the React Tutorial and trying to apply it to a Flask App.

like image 135
siegerts Avatar answered Oct 17 '22 20:10

siegerts