LoginSignup
1
4

More than 3 years have passed since last update.

Django+ReactでWebアプリを作る時に困るかもしれないRoutingのお話

Last updated at Posted at 2019-10-14

概要

Python製WebアプリケーションフレームワークDjangoとフロントエンドフレームワークReactの融合方法とつまづくと思われるRoutingについてまとめ

準備

Django準備

コマンドライン

#アプリケーション生成
django-admin startproject webapp
#ディレクトリへ
cd webapp

#Reactコードを格納するディレクトリをプロジェクトルート直下に
mkdir frontend
mkdir frontend/src
mkdir frontend/src/component
touch frontend/src/index.js

#staticファイルを入れるディレクトリをプロジェクトルート直下に
mkdir static
mkdir static/js

コマンド一発でできるDjangoはやはり神であったか・・・
/templetes/index.html

{% load static %}
<!DOCTYPE html>
<html lang="ja" id="mysite">
<head>
  <title></title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
  <div id=App>
  </div>
</body>
<script src="{% static "js/main.js" %}"></script>
</html>

React

コマンドライン

#プロジェクトのディレクトリにて(manage.pyがあるところ)
npm init -y
npm i webpack --save-dev
npm i webpack-cli --save-dev
npm i @babel/core babel-loader @babel/preset-env @babel/preset-react babel-plugin-transform-class-properties --save-dev
npm i react react-dom prop-types --save-dev

/.babelrc

{
    "presets": [
        "@babel/preset-env", "@babel/preset-react"
    ],
    "plugins": [
        "transform-class-properties",
        "styled-jsx/babel"
    ]
}

/package.json

(省略)
  "scripts": {
    "dev": "webpack --mode development ./frontend/src/index.js --output ./static/frontend/main.js",
    "build": "webpack --mode production ./frontend/src/index.js --output ./static/frontend/main.js"
  },
(省略)

/webpack.config.js


module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  }
};

reactアプリはRoutingをする感じで好きなのを作ってみてください。
APIも必要なら作りましょう。
そんな感じで作ったアプリケーションのRoutingについて次で触れます。

Routing

SPAで意外と難しいのがこのRouting。というのもDjangoとReact双方のRouting機能が競合して面白いことになってしまいます。なのでURL周りは以下のように設定します。

/webapp/urls.py

#省略

api_urlpatterns = [
    省略
]

urlpatterns = [
    #この順番を守ろう。
    path('admin/', admin.site.urls),#管理ページのURL
    path('spa/1.0/', include(api_urlpatterns)),#APIのURL
    url(r'^',TemplateView.as_view(template_name='index.html'))#index.html配信URL
]

/webapp/settings.py

#以下適当な箇所に追加
APPEND_SLASH=False

そしてReactでは

<Switch>
    <Route exact path="/" component={component_of_top} />
    <Route exact path="/hoge" component={component_of_hoge}/>
</Switch>

こんな感じにしてURLの最後に/をつけないようにしましょ。

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4