LoginSignup
10
12

More than 5 years have passed since last update.

JSXを使わずにreact-jadeで仮想DOM出力

Last updated at Posted at 2015-08-03

適当にReact書いていたら、*.jsxの中がrender()のとこのJSXでいっぱいになる。
このJSX、エンジニア的にはそんなに苦じゃない(たぶん)
が、デザイナー(コーダー)とキャッチボールしながら作ってく際にはベストなやり方じゃないかも...と思ってチョット調べたら、react-jadeというのを使っていくやり方もあるようだ。

jadejs/react-jade

jade形式のファイル(文字列)をコンパイルして、仮想DOMを返す関数にしてくれるというもの。
ほぼREADMEに書いてあるとおりなんだけど、試してみる。

cd /path/to/app

npm init -y
npm install react react-jade --save-dev

HTMLに簡単な文字列出してみることにする。

index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Hello world</title>
  </head>
  <body>
    <div id="container"></div>
    <script src="./bundle.js"></script>
  </body>
</html>

index.jsというのを書く。(あとでbrowserifyでbundle.jsに変換する)

index.js
var React = require('react');
var jade  = require('react-jade');

var template = jade.compileFile(__dirname + '/template.jade');

var Hoge = React.createClass({
  render: function() {
    return (
      template({ foo: 'bar' })
    );
  }
});

React.render(React.createElement(Hoge), document.getElementById('container'));

同じ階層にあるtemplate.jadeに、変換したい文字列(≒ HTML)を書いてcompileFile()で仮想DOMを返す関数にする。compileFileは以下の様な役割だとREADMEに書いてある

Compile a jade file into a function that takes locals and returns a React DOM node.

ほとんど書いてないけど、jadeのファイルは以下。

template.jade
h1(class=foo)
  | Hello, world!!
h2
  | Hello, react-jade!

index.jsでtemplateの引数を渡しているが、これがjade側で使えるローカル変数。
よって、h1タグのclassは"bar"となる。

browserify。

browserify -t react-jade index.js -o bundle.js

これでbundle.jsができるので、最初のHTMLをブラウザで開いてみる。
以下の様な結果になる。

Screen Shot 2015-08-03 at 11.58.26 PM.png

reactjs - react-jadeでjadeテンプレートから仮想DOMを出力する - Qiita

↑ こちらの記事を読んでいて知ったが、React側で宣言した関数を変数としてjade側に渡す、ということもできる。
これは良いなと思った

おわり

短いけど以上。

普段Railsを書いていてテンプレートエンジンはerbとslimしか触ったことないため、結局jadeを覚えることにはなるのだが、JSXを素直に修得する以外にも方法があるのだなと分かった。
jsのロジック部分と仮想DOMの部分が上手く分離できそうな気もするので、協業という意味では良いのかも。

10
12
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
10
12