1

I am practicing Flask + React in this repo.

I currently have the same issue, I am unable to pass variables from Flask to React components through props. I have found this older post but it didn't provide more insight.

My code boils down to:

server.py

def index():
return render_template('index.html', bar='hello')

index.jsx

ReactDOM.render(<App foo={ bar } />, document.getElementById('content'));

Console Error

index.jsx?3769:5 Uncaught ReferenceError: bar is not defined

What is the appropriate way of passing information from the server to the components?

Thank you very much in advance

UPDATE

I figured out a solution, here are the changes.

Is that the "scotch-taped" way of passing data? or that is as good as it gets?

2
  • Can you push the branch that you are working on in github? It's hard to figure out how did you mount your component. Commented Nov 13, 2017 at 7:55
  • Yes of course, sorry. I had continued trying to solve the issue and modified the original code. Here is the branch with the exact setup that I asked about in this post Commented Nov 13, 2017 at 12:16

1 Answer 1

2

Your problem is that you are trying to access to template variable directly from your javascript code. you cannot have a direct access.

There is multiple ways to pass variables from your html template to your React DOM. Here are two options that you can use :

in your template index.html, the variable bar passed through attributes :

<div id="content" data-foo={bar}></div> <script> window.test = { bar }; // the variable bar passed in a script tag </script>

in your index.jsx:

ReactDOM.render( <App{...(content.dataset)} test={test}/>, document.getElementById('content') );

Here is a jsfiddle with an example of code in jsfiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.