Sharing code between a React SmartTV Web App & React Web App
Samsung SmartTV an LG webOS TV APPs are based on a regular HTML/CSS/JS web app, with that in mind, sharing code between a normal web app and a SmartTV web app can be very useful.
Presentational and Container components
As explained very clearly by Dan in smart and dumb components, one of the very first patterns you will learn in React that will be very helpful is the separation of components in two types: presentational and container components (or dumb and smart). I won’t get into much detail (Dan explained it better) but a presentational component cares about how things looks, and a container component cares about how things work, kinda like the old view and logic separation argument.
Module specific files
As you may know, React Native loads platform specific modules based on the extension of the file [1], so if you want your Android APP to load specific code, you would have specific files for each platform:
BigButton.ios.js
BigButton.android.js
And you would require the component like this:
const BigButton = require('./BigButton');
Our application
By using what we just learned, we are going to use the following project structure:
app
├── node_modules
├── package.json
├── webpack.tv.config.js
├── webpack.web.config.js
└── src
Header
└── Header.tv.js
└── Header.web.js
└── index.js
└── index.js
For each presentational component that behaves differently between TV and web, we are going to create two presentational modules and import the component as usual:
By using an index file inside each components folder, we will keep our imports clean:
Now, our header presentational modules can behave differently depending the environment, and any logic can be reused inside a container module (smart component). Finally we just need the bundle process to pack the correct files, we can accomplish that by using the extensions attribute in Webpack, use the following code for the web bundle:
And the following code for the TV bundle:
As you can see the main difference are the file extensions that are loaded:
extensions: ['.js', '.json', '.jsx', '.tv.js', ''],
¡Happy coding!