<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amer Lotfi Orimi on Medium]]></title>
        <description><![CDATA[Stories by Amer Lotfi Orimi on Medium]]></description>
        <link>https://medium.com/@amerllica?source=rss-bc9f9d803d88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L_Yk-IzQe4hABzoSZFf3aw.png</url>
            <title>Stories by Amer Lotfi Orimi on Medium</title>
            <link>https://medium.com/@amerllica?source=rss-bc9f9d803d88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:56:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amerllica/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tinode chat for React Native and web, the react-native-tinode]]></title>
            <link>https://medium.com/@amerllica/tinode-chat-for-react-native-and-web-the-react-native-tinode-60ad0193ccce?source=rss-bc9f9d803d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/60ad0193ccce</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[tinode]]></category>
            <category><![CDATA[chat]]></category>
            <dc:creator><![CDATA[Amer Lotfi Orimi]]></dc:creator>
            <pubDate>Sun, 25 Oct 2026 22:55:33 GMT</pubDate>
            <atom:updated>2026-10-25T22:55:33.678Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAutteL-DpE0ND-6ZU7GLQ.jpeg" /><figcaption>react-native-tinode on iOS and web</figcaption></figure><p><strong>Abstract</strong><br>In this article, I will explain a short history of react-native-tinode, the idea behind it, and how you can install it and have a working chat inside your React Native or Expo app with a few files.</p><p><strong>Introduction</strong><br>A year and a half ago, I needed to put a chat inside a React Native app. A real chat, not a demo screen: a contact list, unread counters, “typing…” (the is-typing indicator) and read receipts. Building a chat server from scratch is not a one-person job, and paying a ready-made service per user is very expensive, more than a startup could afford. So the team went looking for an open source server, and I found <a href="https://github.com/tinode/chat">Tinode</a>.</p><p>Tinode is an instant messaging server written in Go, and it has an official JavaScript SDK called <a href="https://github.com/tinode/tinode-js">tinode-js</a>, published on npm as tinode-sdk.</p><p>I told myself, well, it’s JavaScript, and React Native runs JavaScript, so I just install it and I’m done. But I wasn’t done at all. That library was written entirely for the browser!</p><p><strong>TL;DR:</strong> If you don’t have patience for the story, the package is on <a href="https://www.npmjs.com/package/react-native-tinode">npm</a> and the codes are on <a href="https://github.com/amerllica/react-native-tinode">GitHub</a>.</p><p><strong>A short history</strong><br>My first plan was so simple. Wrap tinode-sdk, write TypeScript types for it, put some shims for the parts that React Native doesn&#39;t have, and add React hooks on top. I wrote the plan in a file and I was happy.</p><p>Then I started to read the tinode-js source file by file, and the list of browser things became longer and longer:</p><ul><li>window.location inside the large file helper</li><li>document for saving downloaded files</li><li>indexedDB for the cache</li><li>Intl.Segmenter inside Drafty (Tinode&#39;s rich text format), and Hermes doesn&#39;t have it</li><li>navigator.userAgent in the constructor</li><li>and at import time, it writes a fake global.window</li></ul><p>Shimming all of these from outside means changing global stuff of the whole app, and I really don’t like a library that plays with my globals. So I changed my mind and ported tinode-js v0.25.4 to TypeScript, module by module, with the same file names, class names and method names. Version 0.1.0 of react-native-tinode went to npm on 5 October 2026.</p><p><strong>Talking with the Tinode maintainer</strong><br>The same day, I opened <a href="https://github.com/tinode/tinode-js/issues/102">an issue</a> on tinode-js to introduce the library. <a href="https://github.com/or-else">or-else</a>, the maintainer of Tinode, answered kindly, but the answer was clear: it’s a complete rewrite in TypeScript, so it can’t be merged into the JS SDK, and nobody can keep the two in sync.</p><p>So I opened <a href="https://github.com/tinode/tinode-js/pull/103">a PR</a> that put my TypeScript port inside tinode-js itself. Again the answer was no, and this time I got the real point: the SDK stays JavaScript, and the PR should have only the changes React Native needs.</p><p>Actually, it was a fair answer. When I looked again, the real problem was never JavaScript. The problem was that the SDK picked its storage and its network by itself, from browser globals. So I removed the TypeScript port from the PR and kept only a small dependency injection change, in plain JavaScript:</p><ul><li>a storage option, with three adapters inside the SDK: IndexedDBAdapter (still the default in browsers), KeyValueAdapter for stores like expo-sqlite kv-store, MMKV and AsyncStorage, and MemoryAdapter</li><li>a netInfo option, so the client reconnects at once when the network comes back</li><li>a network option for WebSocket and XMLHttpRequest</li></ul><p>The Tinode web app builds and runs against it with no change, and on 25 October 2026 it was merged into the devel branch. So now tinode-sdk is not a browser-only library anymore. It&#39;s plain JavaScript that runs anywhere, you only pass what your platform has when you create the Tinode instance.</p><p>The same day I released react-native-tinode 0.2.0. My TypeScript port is deleted, and the package is now a thin React layer on top of the official tinode-sdk. Protocol fixes come from upstream, and I don&#39;t port anything by hand anymore.</p><p><strong>The idea</strong><br>The idea is a Tinode client that runs wherever React Native runs, with the official SDK under it:</p><ul><li>No native code. The same package works in Expo Go, in bare React Native and on the web.</li><li>The client is the official tinode-sdk, so the <a href="https://tinode.github.io/js-api/">official docs</a> are valid for you.</li><li>TypeScript types for the whole SDK, because tinode-sdk is plain JavaScript and ships no types.</li><li>Two small polyfills for Hermes, Intl.Segmenter and TextDecoder, installed only when they are missing. Without them the SDK crashes on Hermes when it loads.</li><li>React hooks on top: useConnection, useLogin, useMeTopic, useTopic, useMessages and useTyping.</li><li>The cache store and NetInfo are your app’s dependencies. You pass them in, and the library never imports them.</li></ul><p><strong><em>Here is a small thing</em></strong> that I like a lot. In Tinode, callbacks like onData are single-slot, it means only one function. If a hook sets it, your own handler is gone without any noise. So the hooks add their listeners through a tiny multiplexer, and it is exported as attach if you need it too. Also if several components use the same topic, they share one subscription, and the topic is left shortly after the last one unmounts.</p><p><strong>Let’s start</strong><br><em>Please do the steps one by one</em>:</p><p>1. Install the package. I pin the version, because 0.x versions move fast:</p><pre>yarn add react-native-tinode@0.2.0</pre><p>tinode-sdk comes with it. Pay attention, my change is merged but the next tinode-sdk is not on npm yet, so for now it is installed from a pinned commit of the tinode-js devel branch. It means your machine and your CI need git and access to github.com. After the next npm release of tinode-sdk, this note is gone.</p><p>2. You need a Tinode server. For testing, run a local one with Docker by <a href="https://github.com/tinode/chat/tree/master/docker">this guide</a>. It comes with test users, for example alice with the password alice123.</p><p>3. Make a folder and name it chat inside your src, inside it make a file ChatRoot.tsx and put the below codes in it:</p><pre>import { TinodeProvider } from &#39;react-native-tinode&#39;;<br>import { SupportChat } from &#39;./SupportChat&#39;;</pre><pre>const config = {<br>  appName: &#39;CoinWallet/1.0&#39;,<br>  host: &#39;localhost:6060&#39;,<br>  apiKey: &#39;AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K&#39;,<br>  secure: false,<br>};</pre><pre>export function ChatRoot() {<br>  return (<br>    &lt;TinodeProvider config={config}&gt;<br>      &lt;SupportChat /&gt;<br>    &lt;/TinodeProvider&gt;<br>  );<br>}</pre><p>If you are on the Android emulator, localhost is the emulator itself, so write 10.0.2.2:6060 instead.</p><p>4. Now the login and the list of chats. Make SupportChat.tsx next to it:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br>import { FlatList, Pressable, Text } from &#39;react-native&#39;;<br>import { useConnection, useLogin, useMeTopic } from &#39;react-native-tinode&#39;;<br>import { ChatRoom } from &#39;./ChatRoom&#39;;</pre><pre>export function SupportChat() {<br>  const { status } = useConnection();<br>  const { loginBasic, user } = useLogin();</pre><pre>  useEffect(() =&gt; {<br>    loginBasic(&#39;alice&#39;, &#39;alice123&#39;);<br>  }, [loginBasic]);</pre><pre>  if (!user) {<br>    return &lt;Text&gt;{status}...&lt;/Text&gt;;<br>  }</pre><pre>  return &lt;Chats /&gt;;<br>}</pre><pre>function Chats() {<br>  const { contacts } = useMeTopic();<br>  const [openTopic, setOpenTopic] = useState&lt;string | null&gt;(null);</pre><pre>  if (openTopic) {<br>    return &lt;ChatRoom topic={openTopic} onBack={() =&gt; setOpenTopic(null)} /&gt;;<br>  }</pre><pre>  return (<br>    &lt;FlatList<br>      data={contacts}<br>      keyExtractor={(item) =&gt; item.name}<br>      renderItem={({ item }) =&gt; (<br>        &lt;Pressable onPress={() =&gt; setOpenTopic(item.name)}&gt;<br>          &lt;Text&gt;<br>            {(item.public as { fn?: string } | undefined)?.fn ?? item.name}<br>            {item.unread &gt; 0 ? `  (${item.unread})` : &#39;&#39;}<br>          &lt;/Text&gt;<br>        &lt;/Pressable&gt;<br>      )}<br>    /&gt;<br>  );<br>}</pre><p>loginBasic connects by itself, so there is no need to call connect first. The list is rendered only after login, because the me topic needs an authenticated user. contacts is sorted, the most recent chat is the first one.</p><p>5. And the chat room itself, ChatRoom.tsx:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br>import { Button, FlatList, Text, TextInput, View } from &#39;react-native&#39;;<br>import { useMessages, useTyping } from &#39;react-native-tinode&#39;;</pre><pre>export function ChatRoom({ topic, onBack }: { topic: string; onBack: () =&gt; void }) {<br>  const { messages, hasMore, loadMore, send, markRead } = useMessages(topic, { pageSize: 20 });<br>  const { typingUsers, notifyTyping } = useTyping(topic);<br>  const [text, setText] = useState(&#39;&#39;);</pre><pre>  const lastSeq = messages[messages.length - 1]?.seq;</pre><pre>  useEffect(() =&gt; {<br>    if (lastSeq !== undefined) {<br>      markRead(lastSeq);<br>    }<br>  }, [markRead, lastSeq]);</pre><pre>  const submit = () =&gt; {<br>    if (text.trim()) {<br>      send(text.trim());<br>      setText(&#39;&#39;);<br>    }<br>  };</pre><pre>  return (<br>    &lt;View style={{ flex: 1 }}&gt;<br>      &lt;Button title=&quot;Back&quot; onPress={onBack} /&gt;<br>      &lt;FlatList<br>        inverted<br>        data={[...messages].reverse()}<br>        keyExtractor={(msg) =&gt; String(msg.seq)}<br>        onEndReached={() =&gt; hasMore &amp;&amp; loadMore()}<br>        renderItem={({ item }) =&gt; (<br>          &lt;Text&gt;{typeof item.content === &#39;string&#39; ? item.content : item.content?.txt}&lt;/Text&gt;<br>        )}<br>      /&gt;<br>      {typingUsers.length &gt; 0 &amp;&amp; &lt;Text&gt;typing...&lt;/Text&gt;}<br>      &lt;TextInput<br>        value={text}<br>        placeholder=&quot;Write to support&quot;<br>        onChangeText={(value) =&gt; {<br>          setText(value);<br>          notifyTyping();<br>        }}<br>        onSubmitEditing={submit}<br>      /&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>As you see, there is no onData, no subscribe and no leave in this file. useMessages subscribes, loads the first page, gives you loadMore for older ones, and markRead sends the read receipt to the other side. notifyTyping is throttled inside the library, so calling it on every key press is ok.</p><p>6. Run your app, open the chat of bob from Alice&#39;s list and say hi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oPbv3Wm_RhK8a7waGJpJlg.jpeg" /><figcaption>The example app on iOS simulator</figcaption></figure><p><strong>Cache, so chats open at once</strong><br>By default nothing is cached (persist: false). If you want the chats to open immediately on start and stay readable offline, give it a store. For an Expo app, expo-sqlite/kv-store is my choice, because it works in Expo Go and has no size limit like AsyncStorage on Android:</p><pre>yarn expo install expo-sqlite</pre><p>Then change the config like this:</p><pre>import Storage from &#39;expo-sqlite/kv-store&#39;;<br>import { KeyValueAdapter } from &#39;react-native-tinode&#39;;</pre><pre>const config = {<br>  appName: &#39;CoinWallet/1.0&#39;,<br>  host: &#39;localhost:6060&#39;,<br>  apiKey: &#39;AQEAAAABAAD_rAp4DJh05a1HAwFT3A6K&#39;,<br>  secure: false,<br>  persist: true,<br>  storage: new KeyValueAdapter(Storage),<br>};</pre><p>These adapters live inside tinode-sdk now, and react-native-tinode only re-exports them. If your app has @react-native-community/netinfo, put netInfo: NetInfo in the same config, and the client reconnects as soon as the network is back.</p><p>On the web, persist: true uses IndexedDB and needs no store, so put the store in a .native.ts file. For bare React Native there is a guide for MMKV, and one for AsyncStorage if your app has it already. I won&#39;t explain them here, they are in the <a href="https://github.com/amerllica/react-native-tinode/tree/main/docs/persistence">docs folder</a>. The login token is not cached by the library, there is a separate guide for keeping the user signed in with expo-secure-store.</p><p><strong>See the full example</strong><br>The repo has an Expo example app with login, contacts, paging and typing indicator. Clone it, run yarn in the root, and then:</p><pre>EXPO_PUBLIC_TINODE_HOST=localhost:6060 EXPO_PUBLIC_TINODE_SECURE=false yarn example start</pre><p><strong>What is next</strong><br>My next PR to tinode-js brings the React Native runtime fixes into the SDK itself (Hermes fallbacks and downloads without a DOM), and after it my two polyfills go away. Until then, download() of the large file helper works only on the web, so on native download attachments with fetch yourself. A SQLite adapter for big offline histories is planned too, you can follow it in <a href="https://github.com/amerllica/react-native-tinode/issues/1">issue #1</a>. Push notifications already work with registerDeviceToken, but it&#39;s another article.</p><p>If you use Tinode in a React Native app, test it and tell me what breaks, I will answer every issue. And if you have a better idea, fork it and send a PR, I really welcome it.</p><p><strong>Acknowledgements</strong><br>Thanks to <a href="https://github.com/or-else">or-else</a>, the maintainer of Tinode, for the honest review and for merging the PR.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60ad0193ccce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A VLC player for React Native with Nitro Modules, from scratch to 1.0.1]]></title>
            <link>https://medium.com/@amerllica/a-vlc-player-for-react-native-with-nitro-modules-from-scratch-to-1-0-1-38e2a4a3590b?source=rss-bc9f9d803d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/38e2a4a3590b</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[players]]></category>
            <category><![CDATA[vlc]]></category>
            <dc:creator><![CDATA[Amer Lotfi Orimi]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 15:20:37 GMT</pubDate>
            <atom:updated>2026-10-13T15:20:37.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptIwL9X8H2RqdfDcGrDATw.png" /><figcaption>rn-vlc-plyr</figcaption></figure><p><strong>Abstract</strong><br>For a few years I wanted to write about this library, and in the last months finishing its final parts took a lot of my time, and I learned many things by making it. In this article, I will explain a short history of <a href="https://github.com/amerllica/rn-vlc-plyr">rn-vlc-plyr</a>, a video and audio player for React Native on top of the VLC engine, why VLC and why Nitro Modules, how you can install and use it, and at last how to show the playing time, in <em>mm:ss</em>, or <em>hh:mm:ss</em> when the media is one hour or longer.</p><p><strong>Introduction</strong><br>It started when I needed to play MKV files with several audio and subtitle tracks inside a React Native app, or even other formats like MP4 and MOV, and the problem was nobody knew the format of the files, even the backend couldn’t tell what kind of video or audio file it is. I had another need too, the RTSP stream of a camera. The usual players sit on AVPlayer on iOS and ExoPlayer on Android, so what is playable depends on the device, one phone plays the file and the other one shows you an error. VLC doesn’t care about the device, it carries its own codecs with itself.</p><p><strong>TL;DR:</strong> If you have no patience for the story, the codes are <a href="https://github.com/amerllica/rn-vlc-plyr">on GitHub</a> and the package is <a href="https://www.npmjs.com/package/rn-vlc-plyr">on npm</a>.</p><p><strong>A short history</strong><br>This library is much older than its 1.0.1 I created the repository in the middle of August 2020 and its first name was react-native-video-spieler. Yes, German! <em>Spieler</em> means player. I scaffolded it with @react-native-community/bob on React Native 0.62.</p><p>In the autumn of the same year I renamed it to react-native-ir-player and moved it under the <strong>iran-react-community</strong> organisation on GitHub. Then Maziar Saadatfar and I wrote the iOS side with MobileVLCKit in Swift: play, pause, the events, the parsing status of the file and the volume. Honestly, the main part of the work was <strong>Maziar</strong>’s, and I made the TypeScript types, the example app, its theme, the icons and the logo. The last commit of that period was in the beginning of December 2020. The Android side never reached VLC, the work stopped there, and because of financial reasons it didn’t go further.</p><p>In the last days of the Iranian year 1400, better to say exactly on the last day of the year, in March 2022, I came back to it. I simplified the name to rn-vlc-plyr and moved the repository to my own account. First I made a test publish of react-native-ir-player 0.1.1 on npm and quickly unpublished it, but again, no serious work happened on it.</p><p>Again in December 2025 I deleted the old branches and started from zero with a fresh scaffold. This time it was a Fabric view component on React Native 0.81, the configs were props on the view (url, autoPlay, loop, muted) and play, pause, stop, seek and setVolume were native commands which you called by the view&#39;s ref. And this time Android got VLC-Android too. It was near the end of December that I was setting up the CI/CD with GitHub Actions and npm trusted publishing (OIDC), and I&#39;m not ashamed to say I made a lot of tags, from 0.2.1 to 0.2.9-beta.1, until hours after midnight npm finally accepted one of them. After that a few more betas until 26 December, and the onError event, which reached the Android side only in February 2026. What days they were 💔 Then the war happened and the project stayed in the dust for months, until these days.</p><p>When I came back in October 2026, I saw the problem was not one or two bugs, it was the structure, and the scaffold was old too. The player was living inside the view, so a second view, like fullscreen, meant a second player and loading the media again. So I decided to start again from zero. I kept the old history on the legacy branch and the legacy-v0.2.0 tag, nothing is lost, and made a fresh scaffold on an orphan branch, this time with Nitro Modules and a written behaviour contract for both platforms. On 7 October 2026 I released 1.0.0, and the day after 1.0.1 with a fix for Android. And that became the stable version of this library.</p><p><strong>Why VLC</strong><br>On iOS it uses MobileVLCKit 3.7 and on Android libvlc-android 3.7. Both of them come from the same libvlc 3 line, so the engine behaves the same on two sides. VLCKit 4 is still alpha, so I didn’t touch it. MKV, MP4, AVI, WebM, TS, HLS, RTSP, HEVC, AV1, AC3, DTS, ASS and SRT subtitles, almost everything plays.</p><p>Surely, it has a price. VLCKit adds about 40 MB to the iOS app and libvlc adds about 25 MB for each ABI on Android.</p><p><strong>Why Nitro Modules</strong><br>I had three options: Fabric codegen, the Expo Modules API and <a href="https://nitro.margelo.com/">Nitro Modules</a>. I wanted pure Swift and Kotlin, JSI speed and no Expo dependency for bare apps, and Nitro gave me all of them. I write one TypeScript spec and Nitro generates the typed Swift and Kotlin parts, so the two platforms can’t go far from each other.</p><p>The part I like the most is the synchronous getters. When you read player.currentTime you get the value at once, no promise and no await. For a progress bar it is very very handy. The bad news is Nitro still didn&#39;t reach 1.0.0, so I follow its versions closely, and the library works only on the new architecture.</p><p>One more decision, the player is an object and the view only draws it. So one player can be shown by several views, and when you go fullscreen the media doesn’t reload. I also wrote a behaviour contract for both platforms and checked iOS and Android against it item by item, the result is in <a href="https://github.com/amerllica/rn-vlc-plyr/blob/main/docs/parity.md">docs/parity.md</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljRAnLgWqbHtG9YH0cgW4g.png" /><figcaption>One player, two views</figcaption></figure><p><strong>Let’s install it</strong><br>The minimums are React Native 0.79 with the new architecture, Expo SDK 53 with a development build, iOS 16 and Android API 24. Old architecture, Expo Go and web are not supported.</p><p>1. For a bare React Native app, install these versions, I tested them together:</p><pre>yarn add rn-vlc-plyr@1.0.1 react-native-nitro-modules@0.37.1<br>cd ios &amp;&amp; pod install</pre><p>2. For Expo you need a development build, because Expo Go can’t load native codes:</p><pre>npx expo install rn-vlc-plyr react-native-nitro-modules<br>npx expo prebuild<br>npx expo run:android</pre><p>3. libvlc brings native codes for four ABIs, so keep your Android app small with app bundles, or filter the ABIs inside android/app/build.gradle:</p><pre>android {<br>  defaultConfig {<br>    ndk {<br>      abiFilters &quot;arm64-v8a&quot;, &quot;armeabi-v7a&quot;<br>    }<br>  }<br>}</pre><p><strong>Let’s use it</strong><br>Make a file and name it Player.tsx, then put the below codes inside it:</p><pre>import { StyleSheet, Button, View } from &#39;react-native&#39;;<br>import { VlcPlayerView, useVlcPlayer, useVlcPlayerStatus } from &#39;rn-vlc-plyr&#39;;<br> <br>export const Player = () =&gt; {<br>  const player = useVlcPlayer(&#39;https://example.com/movie.mkv&#39;, (p) =&gt; {<br>    p.loop = true;<br>  });<br>  const status = useVlcPlayerStatus(player);<br> <br>  return (<br>    &lt;View&gt;<br>      &lt;VlcPlayerView player={player} style={styles.video} resizeMode=&quot;contain&quot; /&gt;<br>      &lt;Button<br>        title={status === &#39;playing&#39; ? &#39;Pause&#39; : &#39;Play&#39;}<br>        onPress={() =&gt; (status === &#39;playing&#39; ? player.pause() : player.play())}<br>      /&gt;<br>    &lt;/View&gt;<br>  );<br>}<br> <br>const styles = StyleSheet.create({<br>  video: { width: &#39;100%&#39;, aspectRatio: 16 / 9 },<br>});</pre><p>I have to explain the main parts:</p><ul><li><em>useVlcPlayer</em>: It creates the player for the life of the component and releases it on unmount. The second argument runs once, before the first source, so loop, volume, autoPlay and friends go there.</li><li><em>useVlcPlayerStatus</em>: It gives you the current status, like playing, paused or ended, and re-renders on each change.</li><li><em>VlcPlayerView</em>: It only draws the player. resizeMode can be contain, cover, stretch or original.</li></ul><p>For fullscreen, give the same player to VlcFullscreenModal and put your own controls inside it:</p><pre>&lt;VlcFullscreenModal player={player} visible={fullscreen} onClose={() =&gt; setFullscreen(false)}&gt;<br>  &lt;MyControls /&gt;<br>&lt;/VlcFullscreenModal&gt;</pre><p>Tracks, external subtitles, snapshot and the events are in the README, I won’t repeat them here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*de6RzKdVZVcYYhHtK6I9bw.png" /><figcaption>The example app</figcaption></figure><p><strong>Showing the playing time</strong><br>The first thing everybody builds after putting a player on the screen is a progress bar and a label like 05:12 / 47:30. Some things in this library make it easy:</p><ul><li>All times are integer milliseconds on both platforms, not seconds on one side and milliseconds on the other.</li><li>While playing, timeUpdate comes every 250 ms. If you show only seconds, you can set timeUpdateInterval to 1000 and save some renders.</li><li>After each seek you get exactly one timeUpdate with the new time, and after stop() one with 0, so the bar doesn&#39;t jump here and there.</li><li>player.currentTime and player.isLive are synchronous, you read them and you have the value at once.</li></ul><p>About the format, I show hh:mm:ss when the media is one hour or longer, and mm:ss when it is shorter. The point is, the duration decides, not the current time. If the current time decides, a two hours movie starts with 05:12 and later suddenly becomes 01:00:00, the label gets wider and everything around it moves. The library’s own formatVlcTime decides by the time itself, so here I wrote a small function of mine. Make a file and name it PlayingTime.tsx, then put the below codes inside it (the slider is @react-native-community/slider):</p><pre>import Slider from &#39;@react-native-community/slider&#39;;<br>import { useState } from &#39;react&#39;;<br>import { Text, View } from &#39;react-native&#39;;<br>import { useVlcPlayerEvent, type VlcPlayer } from &#39;rn-vlc-plyr&#39;;<br> <br>const ONE_HOUR = 60 * 60 * 1000;<br>const pad = (value: number) =&gt; String(value).padStart(2, &#39;0&#39;);<br> <br>const formatTime = (ms: number, duration: number) =&gt; {<br>  const totalSeconds = Math.floor(ms / 1000);<br>  const hours = Math.floor(totalSeconds / 3600);<br>  const minutes = Math.floor((totalSeconds % 3600) / 60);<br>  const seconds = totalSeconds % 60;<br><br>  return duration &gt;= ONE_HOUR<br>    ? `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`<br>    : `${pad(minutes)}:${pad(seconds)}`;<br>}<br><br>type PlayingTimeProps = {<br>  player: VlcPlayer;<br>};<br> <br>export const PlayingTime = ({ player }: PlayingTimeProps) =&gt; {<br>  const [time, setTime] = useState({ currentTime: 0, duration: 0 });<br>  useVlcPlayerEvent(player, &#39;timeUpdate&#39;, setTime);<br> <br>  if (player.isLive) {<br>    return &lt;Text&gt;LIVE&lt;/Text&gt;;<br>  }<br> <br>  return (<br>    &lt;View&gt;<br>      &lt;Slider<br>        minimumValue={0}<br>        maximumValue={Math.max(time.duration, 1)}<br>        value={time.currentTime}<br>        onSlidingComplete={(value) =&gt; player.seek(value)}<br>      /&gt;<br>      &lt;Text&gt;<br>        {formatTime(time.currentTime, time.duration)} / {formatTime(time.duration, time.duration)}<br>      &lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>When duration is 0, the media is not loaded yet or it is a live stream, so I check isLive to show LIVE instead of the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zPbRlWv-BA6YsO1k.png" /><figcaption>mm:ss and hh:mm:ss</figcaption></figure><p><strong>Limitations</strong><br>libvlc 3 can send only a user agent and a referrer as HTTP headers, so for Authorization please use signed URLs. Background audio and lock screen controls are planned for 1.1 (<a href="https://github.com/amerllica/rn-vlc-plyr/issues/2">issue #2</a>). Picture-in-Picture and casting are not supported.</p><p><strong>Conclusion</strong><br>Install it, play your weirdest MKV file with it and tell me what happened. If you have any issue, open it on GitHub or leave a comment here and I definitely will answer. And if you fixed something, fork it and send a PR, I will be so happy.</p><p><strong>HINT:</strong> The first subtitle render builds a font cache, and on a fresh install it can take more than 15 seconds. Don’t panic, it is not frozen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38e2a4a3590b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Tag Manager in Expo apps, without touching the native folders]]></title>
            <link>https://medium.com/@amerllica/google-tag-manager-in-expo-apps-without-touching-the-native-folders-e22241509c70?source=rss-bc9f9d803d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/e22241509c70</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[google-tag-manager]]></category>
            <dc:creator><![CDATA[Amer Lotfi Orimi]]></dc:creator>
            <pubDate>Fri, 09 Oct 2026 15:36:48 GMT</pubDate>
            <atom:updated>2026-10-13T14:33:24.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSxflPlCblYLe-cmJgx3BA.jpeg" /><figcaption>Expo and GTM</figcaption></figure><p><strong>Abstract</strong><br>In this article, I will explain why I wrote expo-google-tag-manager, a small Expo config plugin, what problem it solves for Expo developers and how you can install it and send your first event to Google Tag Manager in a few minutes.</p><p><strong>Introduction</strong><br>A few weeks ago a marketing team asked the tech team for Google Tag Manager in their React Native app. They wanted to change their tags and send events to new places without waiting for a new release from the tech team. Fair request. The app was an Expo project with Continuous Native Generation, so the ios and android folders are not in git, expo prebuild makes them again every time.</p><p>The developrs of the tech team searched npm and GitHub for an Expo way of doing it and found nothing that works with the current GTM SDK. All the guides said “open Xcode, drag the container folder into the project, choose folder reference”. It is a good guide for a bare React Native app, but for an Expo app it means your change is gone after the next prebuild --clean. So I wrote a plugin and published it.</p><p><strong>TL;DR:</strong> If you don’t have time for my story, the code is on <a href="https://github.com/amerllica/expo-google-tag-manager">GitHub</a> and the package is on <a href="https://www.npmjs.com/package/expo-google-tag-manager">npm</a>.</p><p><strong>A short history</strong><br>GTM on mobile is older than most of us think. The first SDKs (the ones Google now calls “Legacy”) had their own data layer, you pushed values into it and opened a container from code. In React Native, the popular way to use them was react-native-google-analytics-bridge, it had a GoogleTagManager part and many apps used it. Later, I wrote a library called <a href="https://github.com/amerllica/react-native-google-tag-manager">react-native-google-tag-manager</a> that did this job for React Native apps. It was a wrapper around the native iOS and Android parts that Google itself provided. But that way got deprecated, everything moved to Firebase, and since then React Native apps use <a href="https://github.com/invertase/react-native-firebase">react-native-firebase</a> for GTM.</p><p>Then in May 2016, at Google I/O, Google announced a new Tag Manager SDK that is built on Firebase. The idea changed totally. You don’t push anything into GTM anymore, your app logs Firebase Analytics events and GTM listens to them on the device and fires the tags. In November 2018, after Google stopped the old Google Analytics for mobile apps, the maintainer of the bridge library deprecated it and told everybody to move to Firebase with <a href="https://github.com/invertase/react-native-firebase">react-native-firebase</a>.</p><p>So the JavaScript side got solved by React Native Firebase. But the GTM part stayed a native job: a pod, a Gradle dependency, and the container JSON file in the right native folder. Nobody wrapped it for Expo, and this was the hole I fell into.</p><p><strong>The idea</strong><br>Actually, when you read the GTM for Firebase docs carefully, you see there is no runtime API worth wrapping. GTM needs only three things:</p><p>1. the native SDK inside the app<br>2. your container JSON file inside the app bundle, in a special folder<br>3. optionally, a URL scheme for the preview mode</p><p>All of them are native setup, and native setup in an Expo project is exactly the job of a config plugin. So the plugin does these three things during expo prebuild and nothing more. No JavaScript API, no extra bridge. You log events with React Native Firebase like before.</p><p>What you get from it in an Expo project:</p><ul><li>ios and android stay out of git, you never edit them by hand.</li><li>prebuild --clean is safe, the plugin puts everything back each time.</li><li>If you rename a container or remove one, the old file doesn’t stay behind, because the plugin owns the container and containers folders and replaces their content on every prebuild.</li><li>It checks your container files during prebuild. If the file is missing, or its name is not the GTM id, or it is not valid JSON, the prebuild fails with a clear message instead of a silent app that sends nothing.</li></ul><p><strong>Before you start</strong><br>Please check these first, the plugin depends on them:</p><ul><li>An Expo project with expo prebuild or a development build. Expo Go is not supported, it can&#39;t load native code.</li><li>@react-native-firebase/app and @react-native-firebase/analytics, installed and configured with your GoogleService-Info.plist and google-services.json. GTM listens to Firebase, so Firebase must work before anything else.</li><li>Static frameworks on iOS through expo-build-properties. React Native Firebase already asks for it, so maybe you have it.</li><li>One container per platform. GTM makes separate containers for iOS and Android.</li></ul><p><strong>Let’s set it up</strong><br><em>Follow these steps one by one</em>:</p><p>1. Install the packages. I use yarn expo install because it picks the Firebase and build-properties versions that fit your Expo SDK, so you don&#39;t have to guess them:</p><pre>yarn expo install expo-google-tag-manager @react-native-firebase/app @react-native-firebase/analytics expo-build-properties</pre><p>2. Export your containers. Open <a href="https://tagmanager.google.com/">tagmanager.google.com</a>, choose the iOS container, go to <strong>Versions</strong>, open the version you want and click <strong>Actions</strong>, then <strong>Download</strong>. Do the same for the Android one. Put both files in a gtm folder next to your app.json. Keep the names GTM gives you, like GTM-ABC1234.json, the plugin needs the file name to be the container id. And commit them, they are part of the app now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9OESmlhVIpWSwFwQJ_tNQ.jpeg" /><figcaption>What the plugin does in prebuild</figcaption></figure><p>3. Add the plugin to app.json. Here is the config from our app, only the ids are changed:</p><pre>{<br>  &quot;expo&quot;: {<br>    &quot;ios&quot;: { &quot;bundleIdentifier&quot;: &quot;com.mycompany.exchange&quot; },<br>    &quot;android&quot;: { &quot;package&quot;: &quot;com.mycompany.exchange&quot; },<br>    &quot;plugins&quot;: [<br>      &quot;@react-native-firebase/app&quot;,<br>      [&quot;expo-build-properties&quot;, { &quot;ios&quot;: { &quot;useFrameworks&quot;: &quot;static&quot; } }],<br>      [<br>        &quot;expo-google-tag-manager&quot;,<br>        {<br>          &quot;ios&quot;: { &quot;container&quot;: &quot;./gtm/GTM-ABC1234.json&quot; },<br>          &quot;android&quot;: { &quot;container&quot;: &quot;./gtm/GTM-XYZ9876.json&quot; },<br>          &quot;enablePreview&quot;: true<br>        }<br>      ]<br>    ]<br>  }<br>}</pre><p>The options are very simple:</p><ul><li><em>ios.container</em> and <em>android.container</em>: path of the container file from the project root. You need at least one of them.</li><li><em>enablePreview</em>: adds the GTM preview URL scheme on iOS and TagManagerPreviewActivity on Android. For it, bundleIdentifier and package must be in your config. It is false by default.</li></ul><p>4. Make the native projects again:</p><pre>yarn expo prebuild --clean</pre><p>After this, the files are in ios/&lt;YourApp&gt;/container/ (a blue folder in Xcode) and android/app/src/main/assets/containers/. You don&#39;t need to touch them. But remember, every time you download a new container version from GTM, run this step again, otherwise the app keeps the old container inside.</p><p>5. Log an event. This part has nothing from my plugin, it is pure React Native Firebase. For example on the order screen of our app, when the user submits a buy order:</p><pre>import { getAnalytics, logEvent } from &#39;@react-native-firebase/analytics&#39;;<br> <br>export const trackOrderSubmitted = async (pair: string, side: &#39;buy&#39; | &#39;sell&#39;, amount: number) =&gt; {<br>  await logEvent(getAnalytics(), &#39;order_submitted&#39;, {<br>    pair,<br>    side,<br>    amount,<br>  });<br>};</pre><p>Now in GTM, the marketing team can make a trigger on order_submitted and send it wherever they want. When they publish a new container version, the app picks it up and you don&#39;t release anything.</p><p>6. DONE. Run the app with yarn expo run:ios or yarn expo run:android.</p><p><strong>Preview mode</strong><br>This part saved me a lot of time while testing. In GTM click <strong>Preview</strong> on the container, it shows you a link and a QR code. Close the app, then open the link on the device. On a simulator or emulator you can open it from the terminal:</p><pre>xcrun simctl openurl booted &quot;&lt;preview link&gt;&quot;<br>adb shell am start -a android.intent.action.VIEW -d &quot;&lt;preview link&gt;&quot;</pre><p>The app opens with the preview container, and you can fire your events and see whether the tags run. On Android, the below command shows the GTM logs in Logcat, it is very helpful:</p><pre>adb shell setprop log.tag.GoogleTagManager VERBOSE</pre><p><strong>What it doesn’t do</strong><br>There is no push() and no data layer, because GTM for Firebase doesn&#39;t have them. Custom JavaScript tags and variables are not supported, and the Legacy SDKs are not supported at all. If you need one of them, this plugin is not for you, and I think you need to look at your GTM setup again.</p><p><strong>HINT:</strong> Every time you download a new container version and replace the file, run yarn expo prebuild again, otherwise the app keeps the old file inside.</p><p>The package is very young, so if you find a bug or something doesn’t work on your project, open an issue on GitHub or write it in the comments, I read all of them. PRs are welcome too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e22241509c70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Freedom to Prosper: Why Economic Liberalisation Is Iran’s Path to Stability]]></title>
            <link>https://medium.com/@amerllica/freedom-to-prosper-why-economic-liberalisation-is-irans-path-to-stability-49202429551a?source=rss-bc9f9d803d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/49202429551a</guid>
            <dc:creator><![CDATA[Amer Lotfi Orimi]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 17:21:34 GMT</pubDate>
            <atom:updated>2025-10-18T17:21:34.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9adrGeHQd-foYEaaj8pQQ.png" /><figcaption>Economic Liberalisation</figcaption></figure><p><strong><em>Abstract</em></strong></p><p>For decades, Iran has been trapped in an economic paradox, a resource-rich nation suffering from chronic stagnation, inflation, and brain drain. The core issue isn’t merely sanctions or mismanagement. I believe it’s the lack of economic freedom. Political constraints have turned the economy into a closed system where innovation, competition, and entrepreneurship are stifled. Without a shift toward a freer market and open governance, Iran’s economy will remain structurally incapable of renewal.</p><p><strong><em>Introduction</em>: The link between economic freedom and political health.</strong></p><p>Economic freedom isn’t about deregulation for the rich. It’s about empowering individuals to create value without political permission. History shows that when citizens have the liberty to work, trade, and own property securely, societies tend to become more stable and just. Markets that breathe freely also cultivate civic responsibility and innovation. Two elements are essential for long-term political legitimacy.</p><p><strong>Iran’s Current Dilemma</strong></p><p>Iran’s economy operates under heavy state ownership and ideological control. From oil revenues to manufacturing, the government and quasi-state entities dominate nearly every major industry. This centralisation has led to inefficiency, corruption, and dependency on political patronage.<br> Meanwhile, inflation erodes savings, and restrictive trade policies isolate local businesses from global competition. Even talented youth, Iran’s most valuable asset, face limited opportunities, leading many to emigrate in search of merit-based economies.</p><p><strong>What Economic Liberalisation Really Means</strong></p><p>Economic liberalisation doesn’t mean abandoning social justice. Actually, it means replacing political privilege with <em>equal opportunity</em>. It involves:</p><ul><li><strong>Privatisation</strong> that’s transparent and competitive, not crony-driven.</li><li><strong>The rule of law</strong> protects contracts and property rights, not political connections.</li><li><strong>Open trade</strong> that integrates Iran with regional and global markets.</li><li><strong>Decentralisation</strong> that gives power back to local economies, startups, and individuals.</li></ul><p>A freer economy is not chaotic. It’s self-correcting intelligently. Prices, competition, and innovation naturally guide production more efficiently than bureaucracy ever could.</p><p><strong>Lessons from Other Nations</strong></p><p>Vietnam’s transformation from a closed socialist economy in the 1980s to a thriving export hub is a powerful example. Turkey’s partial liberalisation in the 2000s expanded its middle class and modernised its industries. Even Eastern European nations that embraced market reforms after the Cold War found pathways to prosperity despite political complexities.</p><p>More recently, <strong>Argentina </strong>under<strong> Javier Milei</strong> has become a living experiment in the return to classical economic liberalism. After decades of inflation, debt, and government overreach, Milei’s administration has moved aggressively to <em>shrink the state</em>, <em>deregulate markets</em>, and <em>restore monetary discipline</em>. While controversial, his reforms signal a global shift back toward trusting the free market over political management, a reminder that prosperity begins where bureaucracy ends.</p><p>Iran can learn from these models without copying them. By crafting a distinctly Iranian version of economic freedom rooted in transparency, entrepreneurship, and global cooperation.</p><p><strong>A Roadmap for Iran</strong></p><ol><li><strong>End political monopolies on the economy.</strong> Open markets to private competition.</li><li><strong>Reform the banking system.</strong> Allow independent institutions, digital finance, and private investment flows.</li><li><strong>Reduce subsidies gradually.</strong> Replace them with direct social safety nets that empower individuals rather than industries.</li><li><strong>Encourage foreign partnerships.</strong> Let global capital bring not just money, but accountability and standards.</li><li><strong>Protect small businesses.</strong> Simplify licensing and taxation to let entrepreneurship flourish.</li></ol><p><strong><em>Conclusion</em>: Freedom as the Foundation of Dignity</strong></p><p>For Iran, economic reform isn’t just about prosperity. It’s about dignity. A nation that trusts its people to trade, build, and innovate freely will find a political strength naturally follows. The future of Iran doesn’t lie in more control, but in more confidence. Confidence in the creativity and resilience of its own citizens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49202429551a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero runtime dynamic CSS, using var()]]></title>
            <link>https://medium.com/@amerllica/zero-runtime-dynamic-css-using-var-45ab1f294c41?source=rss-bc9f9d803d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/45ab1f294c41</guid>
            <dc:creator><![CDATA[Amer Lotfi Orimi]]></dc:creator>
            <pubDate>Sun, 20 Apr 2025 13:34:45 GMT</pubDate>
            <atom:updated>2025-04-20T13:34:45.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwBrezj4ONzXrIBI9tlSew.jpeg" /><figcaption>Dull-E drawing for this article’s title</figcaption></figure><p>CSS custom properties (aka <strong>CSS variables</strong>) unlock a sweet spot between “all‑in‑CSS” and heavyweight runtime styling libraries.<br> By sprinkling just a single dynamically‑generated &lt;style&gt; tag, you can pass <strong>live values</strong> from JavaScript to an otherwise <strong>100 % static, tree‑shakable, cache‑friendly CSS bundle</strong>.</p><p>Below is the entire recipe — short, lovely, and ready for your next Medium post.</p><h3><strong>The one‑liner trick</strong></h3><pre>&lt;style&gt;<br>  .scope {<br>    --magic: ${dynamicValue};<br>  }<br>&lt;/style&gt;</pre><p>dynamicValue is any JavaScript expression (props, window size, user theme, …). Everything else—layouts, animations, media queries—stays in regular .scss, .less or .css files.</p><h3>A snack‑size React example</h3><p>Imagine we’ve got a ReactJs component:</p><pre>const Card = ({ gap = 24 }) =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;style&gt;{`<br>        .card-scope { --gap: ${gap}px; }<br>      `}&lt;/style&gt;<br>      &lt;article className=&quot;card-scope card&quot;&gt;<br>        &lt;h2&gt;card title&lt;/h2&gt;<br>        &lt;p&gt;Zero‑runtime styling&lt;/p&gt;<br>      &lt;/article&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>And the styles are like the following:</p><pre>.card {<br>  display: grid;<br>  gap: var(--gap);<br>  padding: var(--gap);<br>  background: white;<br>  border-radius: 1rem;<br>  transition: gap 200ms;<br>}</pre><p><strong><em>Build step:</em></strong> your SCSS compiles once, hashes, and can live forever on a CDN.<br><strong><em>Runtime:</em></strong> only the number inside --gap changes—no expensive style re‑evaluation or flashing <strong><em>className</em></strong> recalculations.</p><h3>Why you’ll love it</h3><ul><li><strong>Zero extra kilobytes</strong> — no styled‑components, no emotion, no runtime CSS‑in‑JS.</li><li><strong>Instant theming</strong> — flip a variable, and every rule that references it updates.</li><li><strong>SSR ready</strong> — inject the &lt;style&gt; on the server to avoid FOUC (Flash of Unstyled Content).</li><li><strong>Works everywhere</strong> — supported in every evergreen browser.</li></ul><h3>Next Steps</h3><ol><li>Wrap the snippet above in a tiny helper hook (useCssVar) for reuse.</li><li>Use media queries inside SCSS (@media (prefers-color-scheme: dark) { … }) while keeping the variable as the single dynamic part.</li><li>Profit — your UI now scales without a styling runtime VAT.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45ab1f294c41" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Laravel/Lumen CI/CD with Github Actions on cPanel shared hosting; WITHOUT SSH]]></title>
            <link>https://medium.com/@amerllica/laravel-lumen-ci-cd-with-github-actions-on-cpanel-shared-hosting-without-ssh-6aaeae409a8f?source=rss-bc9f9d803d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/6aaeae409a8f</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[cpanel]]></category>
            <dc:creator><![CDATA[Amer Lotfi Orimi]]></dc:creator>
            <pubDate>Thu, 10 Aug 2023 23:06:20 GMT</pubDate>
            <atom:updated>2025-04-04T10:44:06.959Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anG3Q6yAhPqmEp0AYQ4pQw.png" /><figcaption>An art by ChatGPT</figcaption></figure><p><strong>Abstract<br></strong>In this article, I will explain how to deploy a Laravel or Lumen project on shared hosting (cPanel) using Github Actions when there is no access to SSH.</p><p><strong>Introduction<br></strong>All of us know shared hosting is much cheaper than VPS and Because of some reason, some hosting centres don’t like to open their SSH access, but still, they’ve got FTP access, and by using Github Actions and FTP it will be possible to implement CI/CD. In the following, you will see easy steps.</p><p><strong>Let’s kick-off<br></strong><em>Please follow the steps one by one</em>:</p><p>1. Login with your cPanel and bring the tools list. Scroll to see the Advance part and click on theTerminal.</p><figure><img alt="cPanel terminal" src="https://cdn-images-1.medium.com/max/759/1*7LAa7bU-4rcbrFsTIjr1Jg.png" /></figure><p>2. Now it’s time to configure the host environment, Please note that the CPANEL_USERNAME is the cPanel username that you own. So change it and then run the following commands inside the terminal.</p><pre>echo &#39;alias composer=&quot;php -d allow_url_fopen=On /home/CPANEL_USERNAME/composer.phar&quot;&#39; &gt;&gt; ~/.bashrc<br>source ~/.bashrc</pre><p>3. Then download composer and install it, Once the first line gets finished then try to install it by running the second one:</p><pre>curl -k -O https://getcomposer.org/installer<br>php -d allow_url_fopen=On installer</pre><p>4. Upload your codes into your desired folder, (cPanel standard: public_html) and by using the terminal go to the project&#39;s root and try to run Laravel’s starting commands (or your own additional). For me, it was like the following:</p><pre>composer install<br>php artisan key:generate<br>php artisan migrate<br>chmod -R 775 storage<br>php artisan db:seed</pre><p>5. It is obvious anyone should create a DB and its user with full privilege and put them in the .env.example or .env file. So I assumed the reader of this article already knows about handling the DB.</p><p>6. Create a yaml file inside the .github/workflows folder. No matter its name, the file should be inside the above path at the project&#39;s root. I like to name it as cicd.yml</p><pre>name: Laravel/Lumen CI/CD<br>on:<br>  push:<br>    branches: [ main ]<br>  pull_request:<br>    branches: [ main ]<br><br>jobs:<br>  web-deploy:<br>    name: Deploying<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: shivammathur/setup-php@15c43e89cdef867065b0213be354c2841860869e<br>        with:<br>          php-version: &#39;8.1.21&#39;<br>      - uses: actions/checkout@v2.3.2<br>      - name: Copy .env<br>        run: php -r &quot;file_exists(&#39;.env&#39;) || copy(&#39;.env.example&#39;, &#39;.env&#39;);&quot;<br>      - name: Install Dependencies<br>        run: composer update --ignore-platform-reqs<br>      - name: Generate key<br>        run: php artisan key:generate<br>      - name: Directory Permissions<br>        run: chmod -R 775 storage<br>      - name: 📂 Sync files<br>        uses: SamKirkland/FTP-Deploy-Action@4.0.0<br>        with:<br>          server: ${{ secrets.SERVER }}<br>          username: ${{ secrets.USERNAME }}<br>          password: ${{ secrets.PASSWORD }}<br>          server-dir: ./api.minimarketapp.ir/</pre><p>7. Definitely, anyone doesn’t like to put server access into the source code. so there is a feature on Github that a developer can pass the critical variables and call them inside the yml file. To do this open the repository setting, then click on the last item ofSecurity part, the Secrets and variables will show you a menu. Open the Actions and insert SERVER, USERNAME and PASSWORD:</p><figure><img alt="Github Actions Secret keys settings" src="https://cdn-images-1.medium.com/max/1024/1*YPC6JCl4x0ho_61a5Z1-iQ.png" /></figure><p>8. DONE. Now by pushing or merging new codes into the main branch, the CI/CD will work.</p><p><strong>HINT:</strong> The first time, it will take too much time, but it will be done quickly the following times.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6aaeae409a8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An introduction to a React Native painting app]]></title>
            <link>https://medium.com/@amerllica/an-introduction-to-a-react-native-painting-app-28b28e62fefa?source=rss-bc9f9d803d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b28e62fefa</guid>
            <category><![CDATA[painting]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-native-skia]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amer Lotfi Orimi]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 19:13:47 GMT</pubDate>
            <atom:updated>2023-06-07T19:13:47.706Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Abstract<br></strong>In this article, I will explain my confront experience with a painting app. By explaining what I have seen and what got resulted, I will give a complete example of how a performant React Native painting app could be implemented by using <a href="https://shopify.github.io/react-native-skia/">React Native Skia</a> library.</p><p><strong>Introduction<br></strong>Implementing this painting was a task in my previous job, and during development, I encountered many libraries and solutions, but none of them was exactly what I wanted. I had also sought and found many examples, but none used a default image (wireframe) above the painting boom. By the following diagrams, it would be easier for you to understand better:</p><p>What were the others:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*Uj0kcHBfi3iOipGfiDcjmw.png" /><figcaption>The simple drawing layers</figcaption></figure><p>What was my task:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*QVqyFYsrRVYWofbJfBQUZA.png" /><figcaption>A drawing layers with a wireframe</figcaption></figure><p>As you can see in the second diagram, the pencil is on the wireframe image, and the pencil’s effects (lines) would be under the wireframe, and it was the tough part of that task.</p><p><strong>TL; DR;</strong> If you like popping in code, <a href="https://github.com/amerllica/react-native-painting-example">here you go</a>.</p><p><strong>The main solution</strong><br>Without any useless additional information and explanation, the main solution for these kinds of requirements is usingreact-native-skia. I had found several painting examples or implementations of React Native, but all of them were very poorly performing, and definitely, those were not reliable for production. <a href="https://www.obytes.com/blog/create-drawing-app">This article</a> is very good for understanding SVG in React Native and how it works, and how a developer can deal with SVG’s properties alongside using gesture handlers.</p><p><strong>Dealing with Skia<br></strong>I read many articles and samples, and I noticed that the only solution would be utilizing react-native-skia. Alongside this, I found <a href="https://blog.notesnook.com/drawing-app-with-react-native-skia/">an article</a> which would be a very helpful sample of react-native-skia . But still, my primary requirement remained. I needed a wireframe in the painting boom, but all of the samples were implemented by a blank white boom.</p><p><strong>Talking with William Candillon<br></strong>In the middle of development by reading source codes of react-native-skia I found several solutions to cover my primary problem, but in some cases, it hadn’t been working much as I wanted, so I had to talk with the contributors react-native-skia about some changes or ask some questions, and I opened <a href="https://github.com/Shopify/react-native-skia/issues/763">an issue</a> and <a href="https://github.com/Shopify/react-native-skia/pull/764">a PR</a>. Luckily, Undet the PR, William Candillon, the creator react-native-skia talked with me and by his guide, I understood even though he couldn’t help me ☹️. I just had a deep dive into the source code to find my solution.</p><p><strong>What is react-native-skia<br></strong>If you take a look at <a href="https://skia.org/">skia.org</a>, you can understand it’s a 2D graphics library which serves as the graphics engine for Google Chrome and ChromeOS, Android, and Flutter, and it was written in C/C++ and William by using NDK used inside Android and iOS and by using React Native modules used its functionalities in React Native environment.</p><p><strong>After all<br></strong>Yeah, after much research and source code reading and talking with contributors, I found that I can use Canvas components, Canvas of react-native-skia not for SVG. And also the Path component for <em>pencil</em> and <em>lines</em>. So my results became the following codes:</p><pre>&lt;Canvas ref={drawRef} style={styles.paintBoom} onTouch={touchHandler}&gt;<br>  &lt;Group&gt;<br>    &lt;Fill color={palette.white} /&gt;<br>    {lines?.map((line, index) =&gt; (<br>      &lt;Path<br>        key={`line_${line.path.toSVGString()}_${index}`}<br>        style=&quot;stroke&quot;<br>        strokeJoin=&quot;round&quot;<br>        strokeCap=&quot;round&quot;<br>        path={line.path}<br>        paint={line.paint}<br>        strokeWidth={line.paint.getStrokeWidth()}<br>        color={line.paint.getColor()}<br>      /&gt;<br>    ))}<br>    &lt;PaintingBodyPen path={path} /&gt;<br>    {!!image &amp;&amp; (<br>      &lt;Image<br>        x={0}<br>        y={0}<br>        image={image}<br>        width={drawWidth}<br>        height={drawHeight}<br>        fit=&quot;contain&quot;<br>      /&gt;<br>    )}<br>  &lt;/Group&gt;<br>&lt;/Canvas&gt;</pre><p>As you see, Canvas with its prop onTouch can handle the <em>pencil</em>’s functionalities, and its effects will be painted by paintingBodyPen the component.<br>The Fill the component plays the background role, and the loop render is the <em>lines</em> portion. At last, the Image component is that wireframe I was worried about.</p><p><strong>Explaining the props<br></strong>I have to explain some props to clarify their usage of them:</p><ul><li><em>ref</em>: This ref object came from the top level of context, and I passed to use some Canvas functionalities like exporting the drawn things as an image</li><li><em>onTouch</em>: It’s a handler function that expects the result of <em>useTouchHandler, </em>and it has three steps: <em>start, active </em>and <em>end. </em>If you look at the codes, it’s easy to understand.</li><li><em>onStart</em>: Inside the start step codes, try to get the <em>color </em>and <em>strokeWidth</em> from the store and set it in the <em>path</em> and <em>paint</em> that they were built by <em>useValue:</em></li></ul><pre>const path = useValue(Skia.Path.Make());<br>const paint = useValue(Skia.Paint());</pre><ul><li><em>onActive</em>: Ignore the shouldPaint condition, it tries to prevent painting when the colour palette or stroke menu gets opened. Inside <em>onActive,</em> it tries to calculate the current position of the <em>pencil</em> and register it inside the <em>path</em> object.</li><li><em>onEnd</em>: In this level, it’s time to add the drew line to the store and the history, reset what the user has drawn and prepare the <em>path </em>and the <em>painted</em> object for the next touch handling. After updating the store, the new line would be added to the boom, and the user cannot feel the converting the <em>pencil</em>’s line to one member of drawn lines.</li></ul><p><strong>Store and the rest of the tools<br></strong>I used <a href="https://github.com/pmndrs/zustand">Zustand</a> store management because it can work out of the ReactJs tree, and this feature made my implementation so performant. The other stuff, like getting permission and saving the drew image as a JPG file into a gallery, is something else that is not my topic, so if you’re interested, you can look at the code.</p><p><strong>Result<br></strong>There is no need to explain more. Watch it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*vik1LngbzooPYaSwoiahYQ.gif" /></figure><p><strong>Acknowledgements<br></strong>Thanks to everyone who helped me with this module and article. Significantly my dear friend <a href="https://medium.com/u/58271e57d92b">Saeed Padyab</a> spend a couple of hours reviewing this article to make it more straightforward, better and more legible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b28e62fefa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Application implementation based on React.js, Complete Example]]></title>
            <link>https://medium.com/@amerllica/web-application-implementation-based-on-react-js-complete-example-ae77a23b4270?source=rss-bc9f9d803d88------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae77a23b4270</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Amer Lotfi Orimi]]></dc:creator>
            <pubDate>Thu, 23 Aug 2018 17:01:10 GMT</pubDate>
            <atom:updated>2023-03-04T20:00:04.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3xOzOFchb8jYQgAdvNY_Q.jpeg" /><figcaption>A perfect React application on the cutting edge of technology</figcaption></figure><p><strong>Introduction</strong></p><p>Every developer can search on the web and find something related to a web application based on React and see some examples of implementations. some concepts like:</p><ul><li>Server-Side Rendering</li><li>Using React Router</li><li>Using CSS Modules</li><li>Using PostCSS</li><li>Webpack configuration</li><li>Express</li><li>Configuration for separating Development and Production environment</li><li>Powerful tools for big-scale application deployment</li><li>Application scaling</li><li>Progressive Web Application</li><li>…</li></ul><p>They are too many and very complicated that sometimes, a crowd of numbers of these technologies causes not to implement them correctly.<br>Sometimes we see websites of large companies like <a href="https://www.pinterest.com/">Pinterest</a>, <a href="https://www.instagram.com/">Instagram</a>, or <a href="https://www.facebook.com/">Facebook</a>, and this question arises to us <em>How do they act and how do they use all techniques without any conflict with a large number of developers</em>?</p><blockquote>In this article, I wanna show you, straightforward vision or example to a good platform, complete and able to transform to a large scale. I explain it step by step.</blockquote><p>In the end, you have a complete repository where you can build a good react application that contains trend techniques and technologies. Surely, your exportation will look like a good example in this field but this doesn’t mean you can not make it better than it is now.</p><p><strong>TL;DR!: </strong>If you are getting bored reading whole the article, and you want to see the results now, see and use <a href="https://github.com/amerllica/-react-server-render-example">this repository</a>.</p><blockquote>I wish, if you have ideas or vision to make it better, <strong>Fork </strong>it on Github and <strong>PR </strong>it. Andrew and I fully welcome this.</blockquote><p><strong>What we wanna build</strong></p><p>If you seek for React App on the internet, you can find many implementations that they have SSR, React Helmet and many other things. but many of them were written based on Development targets, not Production mode.</p><p>In this article, I wanna implement an awesome Development area where you can do your jobs as fast as you can and also, you can Have a Production area with efficient standards and technologies.</p><p><strong>Tools and Technologies in this article</strong></p><ul><li>React</li><li>React Router 4</li><li>React Helmet</li><li>CSS Modules</li><li>PostCSS</li><li>Webpack 3</li><li>Babel</li><li>Express</li><li>PM2</li></ul><p><strong>Basic requirement</strong></p><p>In fact, you should install Node, I Prefer the long-term support version (LTS) if you don’t have it, so, download and install it from <a href="https://nodejs.org/en/">Node Official Website</a>.</p><p><strong>Now What?</strong></p><p>The next step is making a folder for the application that we wanna create it. By folding the project files you can regulate your application and make it scalable. The best practices for folding are so different, in this article I used mine which is like the best of the best, but you can use your folding style.</p><p>Now, I name my project folder react-example and then based on your OS, open your command prompt area or terminal. I assume you open it. then go to the react-example folder by using your terminal and then input the below command:</p><pre>npm init</pre><p>This command alongside running asks you some questions. answer them but do not concern about it. These questions and answers are for making the package.json file and you can easily edit it.</p><p>Now input these commands in your terminal:</p><pre>npm install --save react@16.3.2 react-dom@16.3.2</pre><p>Actually, with the above command, you installed two important dependencies of this article. A folder is made beside the package.json file that name is node_modules which these dependencies and others are kept there. Don’t care about them now. Those numbers are the version of the packages for this article. <strong><em>Seriously </em></strong>use these versions because they are compatible with each other and maybe when you are reading this article the earlier versions were released.</p><p>Now next step, type the below command:</p><pre>npm install --save-dev babel-loader@7.0.0 babel-core@6.24.1 webpack@3.11.0</pre><p>These are dependencies for the Development area, the --save-dev install them but separate them from --save dependencies. for clarity, you can open and see thepackage.json file.</p><p>Now, it is time to install babel, the question is <em>What is it?</em></p><p>With a straightforward explanation, you’re going to code very very awesome based on cutting-edge technologies, But this doesn’t mean when you export your project and prepare it for deployment, all of the browsers are awesome like you. Maybe users use ancient browsers, So, you should take care of them.<br>Babel allows you to be like a hero, but in the end, when Webpack will build your project, it exports codes that all kind of browsers understands, both young and old of them, So, now paste the below command in your terminal:</p><pre>npm install --save-dev babel-preset-es2015@6.24.1 babel-preset-react@6.24.1 babel-preset-env@1.5.1 babel-preset-stage-0@6.24.1</pre><p>These are babel&#39;s plug-ins and dependencies, don’t not attention to them now, but later, when you need something, definitely, you will seek and find these kinds of plug-ins. for using these plug-ins you must create a file with a .babelrc name and write inside it these codes:</p><pre>{   <br>   &quot;presets&quot;: [<br>      &quot;env&quot;,<br>      &quot;es2015&quot;,<br>      &quot;react&quot;,<br>      &quot;stage-0&quot;<br>   ]<br>}</pre><p>All lines of the above codes have their own meaning. for example es2015 means, let us use ES6 syntax and after building the project you will get just ES5.1 codes. or react cause the project system to understand JSX syntax and after building you just see createElement. I won’t explain much more, you can search about these presets and plug-ins or ask about them in the comment.</p><p><strong>Webpack configuration</strong></p><p>Until now, All files and configs are basic and we put all of them on the root of the project folder, but now we settle configs inside some folders to regulate the project. This kind of folding cause the project will be regular and flexible to change and will be scalable.</p><p>Just like I said, we have two kinds of environment, the Development, and the Production, for this target make a folder and name that webpack. inside it make a file and name it webpack.development.config.js and write its content as below:</p><pre>const path = require(&#39;path&#39;);<br>const ExtractTextPlugin = require(&#39;extract-text-webpack-plugin&#39;);</pre><pre>const distDir = path.join(__dirname, &#39;../dist&#39;);<br>const srcDir = path.join(__dirname, &#39;../src&#39;);</pre><pre>module.exports = [<br>    {<br>        name: &#39;client&#39;,<br>        target: &#39;web&#39;,<br>        entry: `${srcDir}/client.jsx`,<br>        output: {<br>            path: path.join(__dirname, &#39;dist&#39;),<br>            filename: &#39;client.js&#39;,<br>            publicPath: &#39;/dist/&#39;,<br>        },<br>        resolve: {<br>            extensions: [&#39;.js&#39;, &#39;.jsx&#39;]<br>        },<br>        devtool: &#39;source-map&#39;,<br>        module: {<br>            rules: [<br>                {<br>                    test: /\.(js|jsx)$/,<br>                    exclude: /(node_modules[\\\/])/,<br>                    use: [<br>                        {<br>                            loader: &#39;babel-loader&#39;,<br>                        }<br>                    ]<br>                },<br>                {<br>                    test: /\.pcss$/,<br>                    use: ExtractTextPlugin.extract({<br>                        fallback: &#39;style-loader&#39;,<br>                        use: [<br>                            {<br>                                loader: &#39;css-loader&#39;,<br>                                options: {<br>                                    modules: true,<br>                                    importLoaders: 1,<br>                                    localIdentName: &#39;[local]&#39;,<br>                                    sourceMap: true,<br>                                }<br>                            },<br>                            {<br>                                loader: &#39;postcss-loader&#39;,<br>                                options: {<br>                                    config: {<br>                                        path: `${__dirname}/../postcss/postcss.config.js`,<br>                                    }<br>                                }<br>                            }<br>                        ]<br>                    })<br>                },<br>            ],<br>        },<br>        plugins: [<br>            new ExtractTextPlugin({<br>                filename: &#39;styles.css&#39;,<br>                allChunks: true<br>            })<br>        ]<br>    },<br>    {<br>        name: &#39;server&#39;,<br>        target: &#39;node&#39;,<br>        entry: `${srcDir}/server.jsx`,<br>        output: {<br>            path: path.join(__dirname, &#39;dist&#39;),<br>            filename: &#39;server.js&#39;,<br>            libraryTarget: &#39;commonjs2&#39;,<br>            publicPath: &#39;/dist/&#39;,<br>        },<br>        resolve: {<br>            extensions: [&#39;.js&#39;, &#39;.jsx&#39;]<br>        },<br>        module: {<br>            rules: [<br>                {<br>                    test: /\.(js|jsx)$/,<br>                    exclude: /(node_modules[\\\/])/,<br>                    use: [<br>                        {<br>                            loader: &#39;babel-loader&#39;,<br>                        }<br>                    ]<br>                },<br>                {<br>                    test: /\.pcss$/,<br>                    use: [<br>                        {<br>                            loader: &#39;isomorphic-style-loader&#39;,<br>                        },<br>                        {<br>                            loader: &#39;css-loader&#39;,<br>                            options: {<br>                                modules: true,<br>                                importLoaders: 1,<br>                                localIdentName: &#39;[local]&#39;,<br>                                sourceMap: false<br>                            }<br>                        },<br>                        {<br>                            loader: &#39;postcss-loader&#39;,<br>                            options: {<br>                                config: {<br>                                    path: `${__dirname}/../postcss/postcss.config.js`,<br>                                }<br>                            }<br>                        }<br>                    ]<br>                }<br>            ],<br>        },<br>    }<br>];</pre><p>As you see, in this file we distinguish <em>client </em>and <em>server </em>and set some configs for each side. somethings are similar and some things are not. This article is too long now and for more explanation ask your question about configs in the comments.</p><p><strong>PostCSS configuration</strong></p><p>Good, it is essential to be said that this Preprocessor is so different from its friends, like SCSS. You must also install its plug-ins in addition to the installation. With plug-ins, it will become stronger. And, If anywhere you feel or see some jobs exist that PostCSS cannot leverage it, you can search and find a plug-in to settle the problem. I chose enough plug-ins, So let’s install them:</p><pre>npm install --save-dev autoprefixer@8.3.0 css-loader@0.28.4 css-mqpacker@6.0.2 isomorphic-style-loader@4.0.0 postcss@6.0.21 postcss-apply@0.10.0 postcss-cssnext@3.1.0 postcss-custom-properties@7.0.0 postcss-extend@1.0.5 postcss-loader@2.1.4 postcss-nested@3.0.0 postcss-nested-ancestors@2.0.0 postcss-partial-import@4.1.0 postcss-scss@1.0.5 style-loader@0.21.0 extract-text-webpack-plugin@3.0.2</pre><p>In the root of the project folder, make another folder and name it postcss, and make a file inside it as postcss.config.js and put the below configuration in it. maybe you ask <em>Why you don’t use SCSS or Less. </em>If you search a little about its benefits, undoubtedly you believe this awesome preprocessor. One of its benefits is autoprefixer that vanish your need to mixins. Just with a little config, you can change the support level of browsers:</p><pre>module.exports = {<br>    ident: &#39;postcss&#39;,<br>    syntax: &#39;postcss-scss&#39;,<br>    map: {<br>        &#39;inline&#39;: true,<br>    },<br>    plugins: {<br>        &#39;postcss-partial-import&#39;: {<br>            &#39;prefix&#39;: &#39;_&#39;,<br>            &#39;extension&#39;: &#39;.pcss&#39;,<br>            &#39;glob&#39;: false,<br>            &#39;path&#39;: [&#39;./../src/styles&#39;]<br>        },<br>        &#39;postcss-nested-ancestors&#39;: {},<br>        &#39;postcss-apply&#39;: {},<br>        &#39;postcss-custom-properties&#39;: {},<br>        &#39;postcss-nested&#39;: {},<br>        &#39;postcss-cssnext&#39;: {<br>            &#39;features&#39;: {<br>                &#39;nesting&#39;: false<br>            },<br>            &#39;warnForDuplicates&#39;: false<br>        },<br>        &#39;postcss-extend&#39;: {},<br>        &#39;css-mqpacker&#39;: {<br>            &#39;sort&#39;: true<br>        },<br>        &#39;autoprefixer&#39;: {<br>            &#39;browsers&#39;: [&#39;last 15 versions&#39;]<br>        },<br>    }<br>};</pre><p><strong>Now The App</strong></p><p>It is so obvious that our application has several pages and should something exists that manage the route of these pages, here I introduce my dear friend, the React Router, Pay attention please, I wanna use the 4th version, so install it with the special below command:</p><pre>npm install --save react-router-dom@4.2.2</pre><p>And then make a folder in the root of the project folder and name it src then make a file and name it as client.jsx and put the below command in it:</p><pre>import React from &#39;react&#39;;<br>import {hydrate} from &#39;react-dom&#39;;<br>import {BrowserRouter} from &#39;react-router-dom&#39;;<br>import App from &#39;./app/App&#39;;</pre><pre>hydrate((<br>    &lt;BrowserRouter&gt;<br>        &lt;App/&gt;<br>    &lt;/BrowserRouter&gt;<br>), document.getElementById(&#39;root&#39;));</pre><p>Then make another file alongside the above file and name it as server.jsx and paste the below codes inside it:</p><pre>import React from &#39;react&#39;;<br>import ReactDOMServer from &#39;react-dom/server&#39;;<br>import {StaticRouter} from &#39;react-router-dom&#39;;<br>import {Helmet} from &quot;react-helmet&quot;;<br>import Template from &#39;./app/template&#39;;<br>import App from &#39;./app/App&#39;;</pre><pre>export default function serverRenderer({clientStats, serverStats}) {<br>    return (req, res, next) =&gt; {<br>        const context = {};<br>        const markup = ReactDOMServer.renderToString(<br>            &lt;StaticRouter location={req.url} context={context}&gt;<br>                &lt;App/&gt;<br>            &lt;/StaticRouter&gt;<br>        );<br>        const helmet = Helmet.renderStatic();</pre><pre>res.status(200).send(Template({<br>            markup: markup,<br>            helmet: helmet,<br>        }));<br>    };<br>};</pre><p>And now make two folders alongside client.jsx and server.jsx files, and name them as app and styles. First is for our main application files and second for its CSS style files.</p><p><strong>Application files</strong></p><p>Inside of app folder make a file and name it as template.jsx and put the main HTML template in it that React wanna inject its markups.</p><pre>export default ({ markup, helmet }) =&gt; {<br>   return `&lt;!DOCTYPE html&gt;<br>         &lt;html ${helmet.htmlAttributes.toString()}&gt;<br>            &lt;head&gt;<br>               ${helmet.title.toString()}<br>               ${helmet.meta.toString()}<br>               ${helmet.link.toString()}              <br>            &lt;/head&gt;<br>            &lt;body ${helmet.bodyAttributes.toString()}&gt;<br>               &lt;div id=&quot;root&quot;&gt;${markup}&lt;/div&gt;<br>               &lt;script src=&quot;/dist/client.js&quot; async&gt;&lt;/script&gt;<br>            &lt;/body&gt;<br>         &lt;/html&gt;`;<br>};</pre><p>Then make a App.jsx file and it is the main file of this project, The main file that contains every part of our React Application. I put some simple codes inside it, but you can fold and make larger applications:</p><pre>import React, {Component} from &#39;react&#39;;</pre><pre>export default class App extends Component {<br>    constructor(props) {<br>        super(props);<br>    }</pre><pre>render() {<br>        return (<br>            &lt;div&gt;                <br>                &lt;h1&gt;Hello World!&lt;/h1&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><p>A little ahead, I’ll return and add some more codes, but now it has enough code to be understood, After watching our simple Hello World! inside browser come back and make it more complete.</p><p>Just add a simple thing, React-Helmetit’s awesome and has much good SEO efficiency. In fact, this awesome component fills head tag dynamically and put many options for managing pages. For installing React-Helmet use the below command inside your terminal:</p><pre>npm install --save react-helmet@5.2.0</pre><p>Just install it now. When we come back App.jsx for completion you will be aware of its benefits.</p><p><strong>Styles Files</strong></p><p>Inside styles folder make a file and name it styles.pcss. And alongside it make a folder and name it partials, then inside partials folder make a partial file and name it as _partial.pcss and put the below codes inside every file:</p><pre>// styles.pcss<br>@import &quot;partials/partial&quot;;</pre><pre>.component {<br>   @extend %box;<br>   color: #2f95ff;<br>}</pre><pre>.text {<br>   display: flex;<br>   @extend %box;<br>}</pre><pre>.test {<br>   display: flex;<br>}</pre><pre>.active {<br>   color: red;<br>}</pre><p>And</p><pre>// partials/_partial.pcss<br>%box {<br>  box-shadow: 0 0 10px 1px #ff6fc3;<br>}</pre><p><strong>Development Server Configuration</strong></p><p>The server of our Development area is express.js. In fact, we use some middleware that when we change something inside every file of the project, for example, PostCSS files, the build system will be aware and rebuild all files again and again automatically.</p><p>First should install dependencies packages:</p><pre>npm i --save-dev express@4.15.3 webpack-dev-middleware@2.0.6 webpack-hot-middleware@2.22.1 webpack-hot-server-middleware@0.5.0</pre><p>Then inside of root make a folder and name it express, and put Development configuration in it, for this please make a file and name it as development.js and write this file like below:</p><pre>const express = require(&#39;express&#39;);<br>const app = express();<br>const webpack = require(&#39;webpack&#39;);<br>const config = require(&#39;./../webpack/webpack.development.config.js&#39;);<br>const compiler = webpack(config);<br>const webpackDevMiddleware = require(&#39;webpack-dev-middleware&#39;);<br>const webpackHotMiddleware = require(&#39;webpack-hot-middleware&#39;);<br>const webpackHotServerMiddleware = require(&#39;webpack-hot-server-middleware&#39;);</pre><pre>app.use(webpackDevMiddleware(compiler, {<br>    serverSideRender: true,<br>    publicPath: &quot;/dist/&quot;,<br>}));<br>app.use(webpackHotMiddleware(compiler.compilers.find(compiler =&gt; compiler.name === &#39;client&#39;)));<br>app.use(webpackHotServerMiddleware(compiler));</pre><pre>const PORT = process.env.PORT || 3000;</pre><pre>app.listen(PORT, error =&gt; {<br>    if (error) {</pre><pre>return console.error(error);</pre><pre>} else {</pre><pre>console.log(`Development Express server running at <a href="http://localhost:${PORT}`">http://localhost:${PORT}`</a>);<br>    }<br>});</pre><p><strong>Let’s See What We build</strong></p><p>It’s time to test and see what we build until now, for this action it is needed to run the below command inside your terminal:</p><pre>node ./express/development.js</pre><p>If you are working on Windows OS, maybe you see NODE_ENV error, don’t worry and visit <a href="https://stackoverflow.com/questions/11928013/node-env-is-not-recognized-as-an-internal-or-external-command-operable-comman/48966524#48966524">this address</a>. I wrote what you should do there, If it has no error you should see the below <em>log </em>inside your terminal area:</p><pre>Development Express server running at http://localhost:3000</pre><p>If you see the above <em>log</em> inside your terminal, you reached halfway down our road. Now open <a href="http://localhost:3000/">http://localhost:3000</a> in your browser, and enjoy your Masterpiece.</p><p><strong>React Router Configuration</strong></p><p>Everything is amazing till now, we bind many items alongside each other truly and All of them work as well as a Swiss watch. I insist, if you have any issues please leave a comment and I definitely will answer.</p><p>If you remember, we just installed React Router and didn’t import it to the application, now time to return to App.jsx, now edit this file with the following code:</p><pre>import React, {Component} from &#39;react&#39;;<br>import Helmet from &quot;react-helmet&quot;;<br>import {Switch, Route} from &#39;react-router-dom&#39;;<br>import {Link, NavLink} from &#39;react-router-dom&#39;;<br>import styles from &#39;../styles/styles.pcss&#39;;</pre><pre>class Menu extends Component {<br>    render() {<br>        return (<br>            &lt;div&gt;<br>                &lt;ul&gt;<br>                    &lt;li&gt;<br>                        &lt;NavLink exact to={&#39;/&#39;} activeClassName={styles.active}&gt;Homepage&lt;/NavLink&gt;<br>                    &lt;/li&gt;<br>                    &lt;li&gt;<br>                        &lt;NavLink activeClassName={styles.active} to={&#39;/about&#39;}&gt;About&lt;/NavLink&gt;<br>                    &lt;/li&gt;<br>                    &lt;li&gt;<br>                        &lt;NavLink activeClassName={styles.active} to={&#39;/contact&#39;}&gt;Contact&lt;/NavLink&gt;<br>                    &lt;/li&gt;<br>                &lt;/ul&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><pre>class Homepage extends Component {</pre><pre>render() {<br>        return (<br>            &lt;div className={styles.component}&gt;<br>                &lt;Helmet title=&quot;Welcome to our Homepage&quot;/&gt;<br>                &lt;Menu/&gt;<br>                &lt;h1&gt;Homepage&lt;/h1&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><pre>class About extends Component {<br>    render() {<br>        return (<br>            &lt;div&gt;<br>                &lt;Helmet title=&quot;About us&quot;/&gt;<br>                &lt;Menu/&gt;<br>                &lt;h1&gt;About&lt;/h1&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><pre>class Contact extends Component {<br>    render() {<br>        return (<br>            &lt;div&gt;<br>                &lt;Helmet title=&quot;Contact us&quot;/&gt;<br>                &lt;Menu/&gt;<br>                &lt;h1&gt;Contact&lt;/h1&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><pre>export default class App extends Component {</pre><pre>render() {<br>        return (<br>            &lt;div&gt;<br>                &lt;Helmet<br>                    htmlAttributes={{lang: &quot;en&quot;, amp: undefined}} // amp takes no value<br>                    titleTemplate=&quot;%s | React App&quot;<br>                    titleAttributes={{itemprop: &quot;name&quot;, lang: &quot;en&quot;}}<br>                    meta={[<br>                        {name: &quot;description&quot;, content: &quot;Server side rendering example&quot;},<br>                        {name: &quot;viewport&quot;, content: &quot;width=device-width, initial-scale=1&quot;},<br>                    ]}<br>                    link={[{rel: &quot;stylesheet&quot;, href: &quot;/dist/styles.css&quot;}]}<br>                /&gt;<br>                &lt;Switch&gt;<br>                    &lt;Route exact path=&#39;/&#39; component={Homepage}/&gt;<br>                    &lt;Route path=&#39;/about&#39; component={About}/&gt;<br>                    &lt;Route path=&#39;/contact&#39; component={Contact}/&gt;<br>                &lt;/Switch&gt;<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><p>Sounds good, let me explain this new content, we have three components, Homepage, About and Contact That they play the role of our three pages.</p><p>After these three pages, we make a Menu component for showing the menu in each component or actually each page.</p><p><strong><em>Here is a point</em></strong>, we are not supposed to use class names like in the past. We are going to use CSS-Modules, so, we should add the styles root file like a JavaScript object:</p><pre>import styles from &#39;../styles/styles.pcss&#39;;</pre><p>And use it in a class name like a JavaScript object:</p><pre>&lt;div className={styles.container}&gt;<br>    &lt;div className={styles[&#39;container-top&#39;]}<br>        example<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>I think it is so obvious, in the PostCSS files leave any class names or namespacing methodologies, like BEM, and inside JSX use that name like a child of styles object instead of a direct name.<br>In this kind of use case when you prepare the deployment version hence the Production version, the class names will be transformed into hash names and you can make them small to 5 characters. Definitely, your built CSS file will be very small and compact.</p><p>The other thing that I like, is React Helmet, that you can see in the above codes obviously. Each component React Helmet exists separately, In the root component, it exists too for general head settings. These settings are very straightforward so I refuse to explain them here.</p><p>Now, let’s see what we build again, so run the Development command again:</p><pre>node ./express/development.js</pre><p>It’s like a miracle, yeah, you build a skeleton of a web application based on React.js that has many awesome technologies. when you click on each menu item the related page renders from the server and it is dynamic on your browser, but is it done?</p><p>Both yes and no, YES: Because we built an awesome Development area, NO: Because we don’t know how to prepare it for the Production area and deployment.</p><p><strong>Preparing for deployment on the Production environment</strong></p><p>So far, we’ve done everything for Development, but now we settle on different configurations for Production so we should consider these three goals:</p><ol><li>Bundling and compressing all files in our application and vanishing debuggers and console.logs and transpiling them to ES5.1</li><li>Extracting styles.css in a separate file and compressing and omitting all comments</li><li>Building stat.json file that in fact, is stuff pieces of webpack on the server actions, which express needs them.</li></ol><p>Going to Production configuration with the following commands:</p><pre>npm install --save-dev clean-webpack-plugin@0.1.19 stats-webpack-plugin@0.6.0 optimize-css-assets-webpack-plugin@3.2.0</pre><p>Now create another file in webpack a folder that name is webpack.production.config.js. its content is:</p><pre>const path = require(&#39;path&#39;);<br>const webpack = require(&#39;webpack&#39;);<br>const ExtractTextPlugin = require(&#39;extract-text-webpack-plugin&#39;);<br>const StatsPlugin = require(&#39;stats-webpack-plugin&#39;);<br>const OptimizeCssAssetsPlugin = require(&#39;optimize-css-assets-webpack-plugin&#39;);<br>const CleanWebpackPlugin = require(&#39;clean-webpack-plugin&#39;);</pre><pre>const distDir = path.join(__dirname, &#39;../dist&#39;);<br>const srcDir = path.join(__dirname, &#39;../src&#39;);</pre><pre>module.exports = [<br>    {<br>        name: &#39;client&#39;,<br>        target: &#39;web&#39;,<br>        entry: `${srcDir}/client.jsx`,<br>        output: {<br>            path: distDir,<br>            filename: &#39;client.js&#39;,<br>            publicPath: distDir,<br>        },<br>        resolve: {<br>            extensions: [&#39;.js&#39;, &#39;.jsx&#39;]<br>        },<br>        module: {<br>            rules: [<br>                {<br>                    test: /\.(js|jsx)$/,<br>                    exclude: /(node_modules[\\\/])/,<br>                    use: [<br>                        {<br>                            loader: &#39;babel-loader&#39;,<br>                        }<br>                    ]<br>                },<br>                {<br>                    test: /\.pcss$/,<br>                    use: ExtractTextPlugin.extract({<br>                        fallback: &#39;style-loader&#39;,<br>                        use: [<br>                            {<br>                                loader: &#39;css-loader&#39;,<br>                                options: {<br>                                    modules: true,<br>                                    importLoaders: 1,<br>                                    localIdentName: &#39;[hash:base64:10]&#39;,<br>                                    sourceMap: false,<br>                                }<br>                            },<br>                            {<br>                                loader: &#39;postcss-loader&#39;,<br>                                options: {<br>                                    config: {<br>                                        path: `${__dirname}/../postcss/postcss.config.js`,<br>                                    }<br>                                }<br>                            }<br>                        ]<br>                    })<br>                }<br>            ],<br>        },<br>        plugins: [<br>            new ExtractTextPlugin({<br>                filename: &#39;styles.css&#39;,<br>                allChunks: true<br>            }),<br>            new webpack.DefinePlugin({<br>                &#39;process.env&#39;: {<br>                    NODE_ENV: &#39;&quot;production&quot;&#39;<br>                }<br>            }),<br>            new CleanWebpackPlugin(distDir),<br>            new webpack.optimize.UglifyJsPlugin({<br>                compress: {<br>                    warnings: false,<br>                    screw_ie8: true,<br>                    drop_console: true,<br>                    drop_debugger: true<br>                }<br>            }),<br>            new webpack.optimize.OccurrenceOrderPlugin(),<br>        ]<br>    },<br>    {<br>        name: &#39;server&#39;,<br>        target: &#39;node&#39;,<br>        entry: `${srcDir}/server.jsx`,<br>        output: {<br>            path: distDir,<br>            filename: &#39;server.js&#39;,<br>            libraryTarget: &#39;commonjs2&#39;,<br>            publicPath: distDir,<br>        },<br>        resolve: {<br>            extensions: [&#39;.js&#39;, &#39;.jsx&#39;]<br>        },<br>        module: {<br>            rules: [<br>                {<br>                    test: /\.(js|jsx)$/,<br>                    exclude: /(node_modules[\\\/])/,<br>                    use: [<br>                        {<br>                            loader: &#39;babel-loader&#39;,<br>                        }<br>                    ]<br>                },<br>                {<br>                    test: /\.pcss$/,<br>                    use: [<br>                        {<br>                            loader: &#39;isomorphic-style-loader&#39;,<br>                        },<br>                        {<br>                            loader: &#39;css-loader&#39;,<br>                            options: {<br>                                modules: true,<br>                                importLoaders: 1,<br>                                localIdentName: &#39;[hash:base64:10]&#39;,<br>                                sourceMap: false<br>                            }<br>                        },<br>                        {<br>                            loader: &#39;postcss-loader&#39;,<br>                            options: {<br>                                config: {<br>                                    path: `${__dirname}/../postcss/postcss.config.js`,<br>                                }<br>                            }<br>                        }<br>                    ]<br>                }<br>            ],<br>        },<br>        plugins: [<br>            new OptimizeCssAssetsPlugin({<br>                cssProcessorOptions: {discardComments: {removeAll: true}}<br>            }),<br>            new StatsPlugin(&#39;stats.json&#39;, {<br>                chunkModules: true,<br>                modules: true,<br>                chunks: true,<br>                exclude: [/node_modules[\\\/]react/],<br>            }),<br>        ]<br>    }<br>];</pre><p>And create another file in express folder and name it production.js and fill it by using the below codes:</p><pre>const express = require(&#39;express&#39;);<br>const path = require(&#39;path&#39;);<br>const app = express();<br>const ClientStatsPath = path.join(__dirname, &#39;./../dist/stats.json&#39;);<br>const ServerRendererPath = path.join(__dirname, &#39;./../dist/server.js&#39;);<br>const ServerRenderer = require(ServerRendererPath).default;<br>const Stats = require(ClientStatsPath);</pre><pre>app.use(&#39;/dist&#39;, express.static(path.join(__dirname, &#39;../dist&#39;)));<br>app.use(ServerRenderer(Stats));</pre><pre>const PORT = process.env.PORT || 3000;</pre><pre>app.listen(PORT, error =&gt; {<br>    if (error) {</pre><pre>return console.error(error);</pre><pre>} else {</pre><pre>console.log(`Production Express server running at <a href="http://localhost:${PORT}`">http://localhost:${PORT}`</a>);<br>    }<br>});</pre><p>So now, with the below commands, we can build some files that are needed for the Production environment:</p><pre>NODE_ENV=production webpack -p --config ./webpack/webpack.production.config.js --progress --profile --colors</pre><p>You can see some files are generated inside a new folder that name is dist. you can see the semi-production environment that all visitors will see by using the following command:</p><pre>NODE_ENV=production node ./express/production.js</pre><p>If on your Google Chrome the browser you had installed the React Developer Tools and Wappalyzer extensions, you can see the React logo, especially you can see the React Developer Tools turns to <em>blue </em>color<em> </em>and it is not <em>red </em>color yet<em>.</em></p><p><strong><em>Blue </em></strong>means it is on production build and <strong><em>red </em></strong>means it is under construction of development build.</p><p>Congratulations! this article is so simple but a little complex, when you are here, it means you are perfect. It takes some time to find all the things. But at last, you will make your custom project with many add on other things like eslint, Redux, Redux-Saga or testing Jest and many other things.</p><h3><strong>Running on Real Server</strong></h3><p>When all the above stuff is prepared, you should tell your DevOps specialist that installs pm2 on the Production server, because a large scale React application with a crowd of visitors never runs with the above command. the pm2 should install with this command:</p><pre>npm install pm2 -g</pre><p>And at last for running should use this command:</p><pre>NODE_ENV=production pm2 start ./express/production.js</pre><p>You can use pm2 on your own PC for a test, it is no different between pm2 and node commands in your browser but the DevOps specialist knows about their difference like load balance, managing caching and etc. If you like to know more about pm2 you can read <a href="http://pm2.keymetrics.io/docs/usage/cluster-mode/">its Docs</a>.</p><p><strong>Conclusion</strong></p><p>For easy development, I put some commands in the scripts section of the package.json file. you can access them in the <a href="https://github.com/DigitalKwarts/react-server-render-example">GitHub Repository</a> or see the below codes:</p><pre>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;,<br>  &quot;dev&quot;: &quot;NODE_ENV=development node ./express/development.js&quot;,<br>  &quot;build&quot;: &quot;NODE_ENV=production webpack -p --config ./webpack/webpack.production.config.js --progress --profile --colors&quot;,<br>  &quot;prod&quot;: &quot;NODE_ENV=production webpack -p --config ./webpack/webpack.production.config.js --progress --profile --colors &amp;&amp; node ./express/production.js&quot;,<br>  &quot;pm2&quot;: &quot;NODE_ENV=production pm2 start ./express/production.js&quot;<br>}</pre><p>And the last point, it is right that I used npm in all of this article, for example, you can use npm run dev for running development, but the npm is so slow, when each changing is happen in files, the system will build your new development files about 27 to 30 seconds! later, and it is annoying for development. Then you can see your changes with the browser Hard Reload. It’s so boring.<br>For this issue, I suggest you use yarn. You can start to develop with yarn dev command, it is unbelievable, and it longs about 500 milliseconds to build new development files.</p><p><strong>Hope this article helps you to build your </strong><strong>React.js application</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae77a23b4270" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>