Reputation: 990
I'd like to start using React components in Django project. React would be used only for some parts of project (e.g. some filters, search box etc).
I looked to answer in other similar question but it doesn't work for me as I don't want to use python-webpack
and espacially js-host
as it will run additional proccess and is hard to configure and deploy.
Do anyone knows any other good solution how to use React with Django?
Upvotes: 6
Views: 2502
Reputation: 990
My colleague created Django Compressor compiler for JSX
(see his pull request) so I'm using it.
After configuring compressor it's enough to just add following stuff in your template files:
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js" type="text/javascript" />
{% compress js %}
<script src="{% static 'components/react_component.jsx' %}" type="text/jsx", charset="utf-8" />
{% endcompress %}
<div id="my-component"></div>
And in react_component.jsx
:
React.render(
<Some_Component />,
document.getElementById('my-component')
);
Also I had to create new view which returns json with needed data. I'll call it later in ReactComponent to fill initial state.
var Some_Component = React.createClass({
getInitialState: function() {
return {
items: [],
loaded: false
}
},
componentDidMount: function() {
$.get('/my_json', function(result) {
if (this.isMounted()) {
this.setState({
items: result.items,
loaded: true
})
}
}.bind(this))
},
...
});
Upvotes: 2
Reputation: 12410
So I've put together http://www.noobmovies.com using Django, Django-Rest-Framework and ReactJS. In a nutshell, I described this process in 2 videos I made available on YouTube.
video 1: https://www.youtube.com/watch?v=wU-KUapq1kQ
video 2: https://www.youtube.com/watch?v=6tiaiSr6Pqw
I like to pass essential data to the template in the Django view to render enough data to populate meta tags and things which are needed by search engines when the page is loaded for the first time. I then use the API to grab the rest of the data via REST AJAX calls and use React to render the JSON data into a nice UI. This allows the page to load quickly and get the data via subsequent api calls using React.
Upvotes: 7