How to pass props from template to react root node?

被刻印的时光 ゝ 提交于 2021-02-10 05:11:49

问题


I have managed to render my component on a div on my template like so:

Index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Example</title>
</head>
<body>

{% load render_bundle from webpack_loader %}<h1>Example</h1>
<div id="react-app"></div>
{% render_bundle 'main' %}

</body>
</html>

My react app:

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

const rootElement = document.getElementById('react-app');
ReactDOM.render(<App />, rootElement);

Whats a good approach to pass in data to react? i'm using Django templates


回答1:


It is possible to pass props to the root element through data attributes and pass them to root element in index.js

<div
    id="root"
    data-custom-props='{aKey: "a value"}'
></div>

index.js file:

ReactDOM.render(<App {...(root.dataset)}/>, root);



回答2:


A common pattern is to output a json string into a script tag, which you can then refer to in your init function.

For example:

// Above where you include your main bundle
<script>
   window.__INITIAL_STATE.__ = { your: 'DATA', encodedIn: 'json', here: true }
</script>

You can then reference window.__INITIAL_STATE__ in your index.js and pass data as props into your root component.




回答3:


What data do you want to pass to react? Props is the concept that allow user to pass data from one component to another within react. It is not made to pass data from outside world to react app.

I believe this answer can guide you in right direction. How to get Django and ReactJS to work together?

also read following to get some idea of back-end and front-end working together. http://geezhawk.github.io/using-react-with-django-rest-framework http://www.openmindedinnovations.com/blogs/3-ways-to-integrate-ruby-on-rails-react-flux



来源:https://stackoverflow.com/questions/43847077/how-to-pass-props-from-template-to-react-root-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!