How to get Django and ReactJS to work together?

cjones picture cjones · Jan 26, 2017 · Viewed 106.3k times · Source

New to Django and even newer to ReactJS. I have been looking into AngularJS and ReactJS, but decided on ReactJS. It seemed like it was edging out AngularJS as far as popularity despite AngularJS having more of a market share, and ReactJS is said to be quicker to pickup.

All that junk aside, I started taking a course on Udemy and after a few videos it seemed important to see how well it integrates with Django. That is when I inevitably hit a wall just getting it up and running, what kind of documentation is out there so that I am not spinning my wheels for several hours and nights.

There really isn't any comprehensive tutorials, or pip packages, I came across. The few I came across didn't work or were dated, pyreact for example.

One thought I had was just to treat ReactJS completely separate, but keeping into consideration the classes and IDs I want the ReactJS components to render in. After the separate ReactJS components are compiled into a single ES5 file, just import that single file into the Django template.

I think that will quickly breakdown when I get to rendering from Django models although the Django Rest Framework sounds like it is involved. Not even far enough to see how Redux affects all of this.

Anyway, anyone have a clear way they are using Django and ReactJS they care to share?

At any rate, the documentation and tutorials are plentiful for AngularJS and Django, so it is tempting to just go that route to get started with any front-end framework... Not the best reason.

Answer

KA01 picture KA01 · Jan 26, 2017

I don't have experience with Django but the concepts from front-end to back-end and front-end framework to framework are the same.

  1. React will consume your Django REST API. Front-ends and back-ends aren't connected in any way. React will make HTTP requests to your REST API in order to fetch and set data.
  2. React, with the help of Webpack (module bundler) & Babel (transpiler), will bundle and transpile your Javascript into single or multiple files that will be placed in the entry HTML page. Learn Webpack, Babel, Javascript and React and Redux (a state container). I believe you won't use Django templating but instead allow React to render the front-end.
  3. As this page is rendered, React will consume the API to fetch data so React can render it. Your understanding of HTTP requests, Javascript (ES6), Promises, Middleware and React is essential here.

Here are a few things I've found on the web that should help (based on a quick Google search):

Hope this steers you in the right direction! Good luck! Hopefully others who specialize in Django can add to my response.