Get familiar with Backbone and requireJS.
Incorporate React JSX components into existing Backbone app, and use ReactDOM.render()
in place of Backbone.View.render()
, so we can use React components instead of Backbone templates.
Browsers do not understand JSX.
Although React can do it with pre-configured Babel, Backbone does not transpile JSX to JS automatically.
To do this, we need to use external transpiler:
- manually - we can use react-tools and jsx.js
- automatically - we can use Grunt and Babel with the following packages:
npm install --save-dev grunt-babel @babel/core @babel/preset-env @babel/preset-react
- Install all dependencies from package.json running
npm install
. - Download all libraries from js/libs.
- Verify that require.config is configured properly for libraries - see js/app.js
- Create React components in .jsx files, wrap them in requireJS define() and return - see js/Templates/RecipeCard.jsx
- Transpile .jsx files into .js files (see below)
- Use transpiled .js files in your Backbone.View files (see below and in js/Views/RecipeView.js)
Run in CLI:
node_modules\.bin\jsx -x jsx js\Templates js\Templates
Here you tell react-tools and jsx to transpile all .jsx files from ./js/Templates folder and put all resulting .js files to the same location.
Run in CLI:
grunt
Grunt is already configured in Gruntfile.js
to use Babel to compile all .jsx files into .js.
Import it using requireJS:
define(
['Templates/RecipeCard', 'react', 'reactDom', ...otherModules],
function(RecipeCard, React, ReactDOM, ...otherDependencies) {
const RecipeView = Backbone.View.extend({
...
render: function () {
ReactDOM.render(
React.createElement(RecipeCard, this.model.toJSON(), null),
this.$el.get(0)
)
return this // enable chained calls
},
...
})
return RecipeView
})