Skip to main content

An easy way to Write React Component with Django.

Project description

An easy way to use React with Django.

QuickStart

Install

pip install django-vite-react

Update Settings.py

INSTALLED_APPS = [
    ...
    'react',
    ...
]

Setup Vite

Create file package.json

{
  "name": "django-react",
  "version": "1.0.0",
  "description": "use react.js in django templates",
  "main": "index.js",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "ChanMo",
  "license": "ISC",
  "devDependencies": {
    "@vitejs/plugin-react": "^3.1.0",
    "vite": "^4.1.1"
  },
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  }
}

Create file vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'static/dist/',
    manifest: true,
    rollupOptions: {
      input: [
        'components/app.jsx',
      ]
    }
  }
})

Install npm package

npm install
npm run dev

Create your jsx file

Example components/app.jsx

import React from 'react';
import ReactDom from 'react-dom/client';

function App(props) {
  return (
    <h1>{props.title}</h1>
  )
}

const root = ReactDom.createRoot(document.getElementById("app"));
root.render(
  <App {...window.props} />
);

Use ReactMixin in your ClassView

from django.views.generic import TemplateView
from react.mixins import ReactMixin


class IndexView(ReactMixin, TemplateView):
    app_root = 'components/app.jsx'
    def get_props_data(self):
        return {
            'title': 'Hello'
        }

Visit url in your brower

http://localhost:8000/

Build js

Before deploy, run yarn dev,

Todo

  • [ ] easier to integrate

  • [ ] decorate function

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-vite-react-0.0.2.tar.gz (4.8 kB view details)

Uploaded Source

File details

Details for the file django-vite-react-0.0.2.tar.gz.

File metadata

  • Download URL: django-vite-react-0.0.2.tar.gz
  • Upload date:
  • Size: 4.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.10

File hashes

Hashes for django-vite-react-0.0.2.tar.gz
Algorithm Hash digest
SHA256 6940248390531a210ba41c66091fd311cbef4aecc48938ddf4cc6d8aff3db3f6
MD5 08ed4affec6a92ff0180f38f2b575be0
BLAKE2b-256 6c716b7d1e75c580f9ce00dacf5c1b7010092106ce3efb99d6b806eaadc00051

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page