<?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 Yan Ivan Evdokimov on Medium]]></title>
        <description><![CDATA[Stories by Yan Ivan Evdokimov on Medium]]></description>
        <link>https://medium.com/@jansivans?source=rss-cb2814e79a8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xZi5-nlacNhV60PO2x6hXA.png</url>
            <title>Stories by Yan Ivan Evdokimov on Medium</title>
            <link>https://medium.com/@jansivans?source=rss-cb2814e79a8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 04:25:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jansivans/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[Building Telegram Mini App with Drayman Framework]]></title>
            <link>https://itnext.io/building-telegram-mini-app-with-drayman-framework-5104df9572e8?source=rss-cb2814e79a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5104df9572e8</guid>
            <category><![CDATA[drayman]]></category>
            <category><![CDATA[telegram-messenger]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Yan Ivan Evdokimov]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 10:22:52 GMT</pubDate>
            <atom:updated>2023-11-02T10:22:52.816Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Elg931joGpuJDv3aLVE1fQ.png" /></figure><p>In this tutorial, we’ll create a Telegram mini app that will allow users to match with movies. We’ll use <a href="https://www.drayman.io/">Drayman framework</a> to create this app and go trough some major features of Telegram mini apps.</p><p>You can find the final code of this app here: <a href="https://github.com/jansivans/tg-movie-matcher-app">tg-movie-matcher-app</a>.</p><p>If you want to check final result, share <a href="http://t.me/movie_matcher_bot/app">t.me/movie_matcher_bot/app</a> link to your friend in Telegram, launch mini app and start movie matching!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*qzKeM1llkFSeUHr0.gif" /></figure><h3>Initialization with Drayman Framework</h3><p>Drayman Framework was chosen for the Telegram Mini App development because of its fast setup and unified full-stack development — combining server and client side inside components. It is also very easy to use and has a lot of features that are useful for Telegram Mini Apps.</p><p>Let’s start by initializing and starting new Drayman project:</p><pre>npx @drayman/framework-init@latest tg-movie-matcher-app<br>cd tg-movie-matcher-app<br>npm start</pre><p>“Drayman started at <a href="http://localhost:3033/">http://localhost:3033</a>&quot; text will be printed in the console. Open this URL in your browser and you’ll see Drayman welcome page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kged6GhFQ1N5gn7M.png" /></figure><h3>Installing Necessary Packages</h3><p>Let’s install all packages we’ll need for this app:</p><ul><li>telegraf - Telegram bot API wrapper, we&#39;ll use it to work with Telegram API.</li><li>@lottiefiles/lottie-player - Lottie animation player, we&#39;ll use it to play animated stickers.</li><li>chroma-js - color manipulation library, we&#39;ll use it to generate correct color for movie rating badge.</li><li>drayman-swipi-cards - Drayman component for swiping cards.</li><li>js-confetti - confetti animation library, we&#39;ll use it to show confetti animation when user matches with a movie.</li><li>nanoid - library to generate unique IDs, we&#39;ll use it to generate unique IDs for user connections.</li><li>node-themoviedb - library to work with <a href="https://www.themoviedb.org/">The Movie Database</a> API, we&#39;ll use it to get movies data.</li></ul><pre>npm install telegraf@4.14.0 @lottiefiles/lottie-player@2.0.2 chroma-js@2.4.2 drayman-swipi-cards@2.0.9 js-confetti@0.11.0 nanoid@3.3.4 node-themoviedb@0.2.8 --save-exact</pre><h3>Modifying index.html, adding styles.css and assets</h3><p>Some packages we’ve installed require scripts to be added to index.html file. Also you&#39;ll need to add telegram-web-app.js script to enable Telegram mini app mode. Here is the final index.html file:</p><pre>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot; /&gt;<br>  &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot; /&gt;<br>  &lt;title&gt;Movie Matcher Telegram Mini App&lt;/title&gt;<br>  &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>  &lt;script src=&quot;https://telegram.org/js/telegram-web-app.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;/drayman-framework-client.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;/node_modules/drayman-swipi-cards/dist/swipi-cards/swipi-cards.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;/node_modules/js-confetti/dist/js-confetti.browser.js&quot;&gt;&lt;/script&gt;<br>  &lt;script src=&quot;/node_modules/@lottiefiles/lottie-player/dist/lottie-player.js&quot;&gt;&lt;/script&gt;<br>  &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot; /&gt;<br>&lt;/head&gt;</pre><p>As you can see, we’ve also added styles.css file to index.html. Don&#39;t forget to create this file in public folder next to index.html file. Copy the code from this link: <a href="https://github.com/jansivans/tg-movie-matcher-app/blob/main/public/styles.css">styles.css</a> and paste it to your styles.css file.</p><p>Create stickers folder in public folder and copy all stickers from this link: <a href="https://github.com/jansivans/tg-movie-matcher-app/tree/main/public/stickers">stickers</a>.</p><h3>Retrieving API Tokens</h3><p>Now let’s retrieve required tokens for our app.</p><ul><li>Telegram token — BOT_TOKEN - create a new bot using /newbot command in <a href="https://t.me/botfather">BotFather</a> and copy the token.</li><li>The Movie Database API key — MOVIE_DB_API_KEY - create a new account on <a href="https://www.themoviedb.org/">The Movie Database</a> and copy the API key from <a href="https://www.themoviedb.org/settings/api">API page</a>.</li></ul><h3>Setting up ngrok for HTTPS Tunneling</h3><p>One of the Telegram requirements is that web app must be hosted on HTTPS, so we’ll use <a href="https://ngrok.com/">ngrok</a> to create a tunnel to our local server. Install it and after that, I suggest you to create a ngrok account to create a static domain. This way you’ll be able to use the same link to your app every time you start it. Here are official instructions on how to do it: <a href="https://ngrok.com/blog-post/free-static-domains-ngrok-users">free static domain for all ngrok users</a>.</p><p>After retrieving your domain, start ngrok tunnel:</p><pre>ngrok http --domain=[static-domain] 3033</pre><p>In result, you’ll see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P_mwm2TMrj1soU-l" /></figure><h3>Integrating with Telegram</h3><p>Copy this HTTPS link and using <a href="https://t.me/botfather">BotFather</a> create a new app with /newapp command. When asked for a link to the app, paste the link you&#39;ve copied from ngrok. As the short app name, you can simply type app. In result, you&#39;ll get a link to your app, something like this: t.me/movie_matcher_test_bot/app.</p><p>We can also add menu button to our bot to launch our app. To do this, go to <a href="https://t.me/botfather">BotFather</a> and select your bot. Then select Bot Settings and then Menu Button, Configure menu button. Send him a link you got from ngrok. After that, you&#39;ll be able to launch your app by clicking on the menu button in your bot. However, we haven&#39;t added Telegram bot API support to our app yet, so it won&#39;t work. Let&#39;s do it now.</p><h3>Adding Telegram Bot API Support</h3><p>Let’s integrate Telegram bot API support to our app now. Create a new <a href="https://www.drayman.io/docs/components-in-depth/helpers/the-server-object">Server</a> index.ts file in src folder and add the following code to it:</p><pre>import { Telegraf } from &quot;telegraf&quot;;<br>import { message } from &quot;telegraf/filters&quot;;<br>import express from &quot;express&quot;;<br>import MovieDB from &quot;node-themoviedb&quot;;<br><br>export const Server: DraymanServer = async ({ EventHub, app }) =&gt; {<br>  app.use(&quot;/node_modules&quot;, (req, res, next) =&gt;<br>    express.static(&quot;node_modules&quot;)(req, res, next)<br>  );<br>  const mdb = new MovieDB(process.env.MOVIE_DB_API_KEY);<br>  const tgToken = process.env.BOT_TOKEN;<br>  const bot = new Telegraf(tgToken);<br>  bot.launch();<br>  bot.on(message(), (ctx) =&gt; {<br>    return ctx.replyWithHTML(`🎬 &lt;b&gt;Welcome to Movie Matcher!&lt;/b&gt; 🎥<br><br>Choose your genres and years, and &lt;b&gt;swipe through&lt;/b&gt; our top movie picks. <br><br>To match with &lt;b&gt;friends&lt;/b&gt; share the &lt;b&gt;app link&lt;/b&gt; - t.me/movie_matcher_test_bot/app.<br><br>If you&#39;re in the mood for &lt;b&gt;solo&lt;/b&gt; discovery, use the &lt;b&gt;menu button&lt;/b&gt; <br><br>When everyone &lt;b&gt;swipes right&lt;/b&gt; on a movie, it&#39;s popcorn time! <br><br>Dive in and elevate your movie nights!<br>`);<br>  });<br>};</pre><p>In this code we’ve initialized <a href="https://telegraf.js.org/">Telegraf</a> bot API wrapper and <a href="https://www.themoviedb.org/">The Movie Database</a> client. We’ve also added a handler for any message that will be sent to our bot and replied with a welcome message. Please make sure that you use your own link to the app in the message.</p><p>Start our app, providing required tokens as environment variables:</p><pre>MOVIE_DB_API_KEY=&lt;your-movie-db-token&gt; BOT_TOKEN=&lt;your-telegram-token&gt; npm start</pre><p>Now open your bot in Telegram and you’ll see the welcome message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Uq5X9j4BrQr9RcT7.png" /></figure><p>Click “Start Matching” button you’ve added earlier and mini app will be launched:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9YtLeDkfNVYFftbF.png" /></figure><p>We have finished main setup of our app. You can use these instructions and code above as boilerplate for your own Telegram app. But we’ll continue and add more features to our Movie Matcher app.</p><h3>Defining the Movie Matcher app flow</h3><p>Before we start implementing our app, let’s define the flow of it.</p><ul><li>User <strong>opens</strong> the app.<br>- When user can’t be <a href="https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app">validated</a>, <strong>failed validation screen</strong> will be shown.<br>- When matching is in progress, user will see the <strong>matching screen</strong>.<br>- When matching is not in progress, user will see the <strong>setup screen</strong> where he can select genres and years and can see connected users. User can also click “Start” button.<br>- When user selectes genres or years (<strong>genres screen</strong>, <strong>years screen</strong>), “Back” button will appear and user will be able to go back to the <strong>setup screen</strong>.<br>- When user clicks “Start” button, and there movies with selected genres and years can be found, matching will start and user will see the <strong>matching screen</strong>.<br>- When user clicks “Start” button, and there are no movies with selected genres and years, user will see the <strong>no movies screen</strong>.<br>- When user disconnects from <strong>setup screen</strong>, connected users list will be updated.</li><li>User is in the <strong>matching screen</strong>.<br>- “Start” button will be hidden and “Back” button will appear.<br>- User can swipe left movie card to dislike the movie and swipe right to like the movie.<br>- When all users swipe right on the same movie, confetti animation will be shown, notifcation message will be sent from the bot and users will see the <strong>movie selected screen</strong>. <br>- When user made selection and there are no more movies to swipe, user will see the <strong>waiting for others screen</strong>.<br>- When all users made selection and haven’t matched with any movie, users will see the <strong>no movie selected screen</strong>.<br>- When user disconnects from <strong>matching screen</strong>, likes and dislikes will be recalculated according to the new number of users.<br>- When user clicks “Back” button, all users will be redirected to the <strong>setup screen</strong> and matching will be stopped.</li><li>Connected users list is created based on chat from which a link to the app was sent. When a user opens the app link within the same chat, he will be added to the list.</li></ul><h3>Setting up browser commands and events</h3><p>Inside index.html, change &lt;script&gt; tag to this:</p><pre>&lt;script&gt;<br>  const jsConfetti = new JSConfetti();<br>  initializeDraymanFramework({<br>    browserCommands: (emit) =&gt; ({<br>      getTelegramData: () =&gt; {<br>        window.Telegram.WebApp.ready();<br>        return {<br>          initData: window.Telegram.WebApp.initData,<br>          initDataUnsafe: window.Telegram.WebApp.initDataUnsafe,<br>          themeParams: window.Telegram.WebApp.themeParams,<br>          colorScheme: window.Telegram.WebApp.colorScheme,<br>          viewportHeight: window.Telegram.WebApp.viewportHeight,<br>        };<br>      },<br>      setMainButtonParams: (params) =&gt; {<br>        window.Telegram.WebApp.MainButton.setParams(params);<br>      },<br>      setBackButtonVisibility: ({ visible }) =&gt; {<br>        visible<br>          ? window.Telegram.WebApp.BackButton.show()<br>          : window.Telegram.WebApp.BackButton.hide();<br>      },<br>      explode: async () =&gt; {<br>        jsConfetti.addConfetti();<br>      },<br>      events: async ({<br>        onMainButtonClick,<br>        onViewportChanged,<br>        onBackButtonClick,<br>      }) =&gt; {<br>        Telegram.WebApp.onEvent(&quot;mainButtonClicked&quot;, () =&gt;<br>          emit(onMainButtonClick)<br>        );<br>        Telegram.WebApp.onEvent(&quot;backButtonClicked&quot;, () =&gt;<br>          emit(onBackButtonClick)<br>        );<br>        Telegram.WebApp.onEvent(&quot;viewportChanged&quot;, () =&gt;<br>          emit(<br>            onViewportChanged,<br>            { viewportHeight: window.Telegram.WebApp.viewportHeight },<br>            { debounce: 300 }<br>          )<br>        );<br>      },<br>    }),<br>  });<br>&lt;/script&gt;</pre><p>This code will initialize Drayman framework and set up browser commands and events. You can read about browser commands and events in Drayman framework docs <a href="https://www.drayman.io/docs/components-in-depth/helpers/the-browser-object">here</a>. Let’s go through each command and event we’ve added:</p><ul><li>getTelegramData - this command will return neccessary Telegram data that we&#39;ll use later to set up main component when it initializes.</li><li>setMainButtonParams - this command will set up main button parameters. We&#39;ll use it to change main button text and visibility.</li><li>setBackButtonVisibility - this command will set up back button visibility. We&#39;ll use it to show back button when user performs some actions.</li><li>explode - this command will trigger confetti animation. We&#39;ll use it to show confetti animation when users match with a movie.</li><li>events - this allows to listen for Telegram events and emit Drayman events. We&#39;ll use it to listen to main button click, back button click and viewport change events.</li></ul><h3>Validating user</h3><p>First thing user will load when connecting to the app is home.tsx component. It is already created in src/components folder when you initialized Drayman framework project. It is a good place where main logic and UI of the app should be placed. Let&#39;s begin modifying this component by adding user validation because Telegram requires that user is validated before app can be used.</p><p>Create utils.ts file and place it to src folder next to index.ts file. Add the following code to it:</p><pre>import crypto from &quot;crypto&quot;;<br><br>export function verifyInitData(telegramInitData: string): boolean {<br>  const urlParams = new URLSearchParams(telegramInitData);<br>  const hash = urlParams.get(&quot;hash&quot;);<br>  urlParams.delete(&quot;hash&quot;);<br>  urlParams.sort();<br>  let dataCheckString = &quot;&quot;;<br>  for (const [key, value] of urlParams.entries()) {<br>    dataCheckString += `${key}=${value}\n`;<br>  }<br>  dataCheckString = dataCheckString.slice(0, -1);<br>  const secret = crypto<br>    .createHmac(&quot;sha256&quot;, &quot;WebAppData&quot;)<br>    .update(process.env.BOT_TOKEN);<br>  const calculatedHash = crypto<br>    .createHmac(&quot;sha256&quot;, secret.digest())<br>    .update(dataCheckString)<br>    .digest(&quot;hex&quot;);<br><br>  return calculatedHash === hash;<br>}</pre><p>verifyInitData function will be used to verify user data according to <a href="https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app">Telegram requirements</a>. Let&#39;s use it in home.tsx component. Add the following code to home.tsx file:</p><pre>import { verifyInitData } from &quot;../utils&quot;;<br><br>export const component: DraymanComponent = async ({ Browser }) =&gt; {<br>  const data = await Browser.getTelegramData();<br><br>  if (!verifyInitData(data.initData)) {<br>    await Browser.setMainButtonParams({ is_visible: false });<br><br>    return () =&gt; {<br>      return &lt;h1&gt;Invalid data&lt;/h1&gt;;<br>    };<br>  }<br><br>  return () =&gt; {<br>    return &lt;h1&gt;Valid data&lt;/h1&gt;;<br>  };<br>};</pre><p>In this code we’ve added verifyInitData function to home.tsx file and used it to validate user data. If user data is invalid, we&#39;ll hide main button and show &quot;Invalid data&quot; text. Otherwise, we&#39;ll show &quot;Valid data&quot; text. We get initial data by calling Browser.getTelegramData command we defined earlier in &quot;Setting up browser commands and events&quot; section.</p><p>We can safely make validations here because in Drayman all components are server-side rendered and communication between browser (<a href="https://www.drayman.io/docs/components-in-depth/helpers/the-browser-object">Browser object</a>) and server (<a href="https://www.drayman.io/docs/components-in-depth/helpers/the-server-object">Server object</a>) is done in a secure way.</p><p>Returning textual info seems boring, so let’s add some stickers!</p><h3>Sticker animation component</h3><p>Create lottieAnimation.tsx file in src/components folder and add the following code to it:</p><pre>export const component: DraymanComponent&lt;{<br>  src: string;<br>  title?: string;<br>  overview?: string;<br>}&gt; = async ({ props }) =&gt; {<br>  return async () =&gt; {<br>    return (<br>      &lt;div class=&quot;lottie-animation&quot;&gt;<br>        &lt;lottie-player autoplay loop src={props.src}&gt;&lt;/lottie-player&gt;<br>        {!!props.title &amp;&amp; &lt;div class=&quot;title&quot;&gt;{props.title}&lt;/div&gt;}<br>        {!!props.overview &amp;&amp; &lt;div class=&quot;overview&quot;&gt;{props.overview}&lt;/div&gt;}<br>      &lt;/div&gt;<br>    );<br>  };<br>};</pre><p>This component will be used to show Lottie animation. We’ll use it to show stickers. Let’s modify home.tsx component to use this component:</p><pre>import { verifyInitData } from &quot;../utils&quot;;<br><br>export const component: DraymanComponent = async ({ Browser }) =&gt; {<br>  const data = await Browser.getTelegramData();<br><br>  if (!verifyInitData(data.initData)) {<br>    await Browser.setMainButtonParams({ is_visible: false });<br><br>    return () =&gt; {<br>      return (<br>        &lt;lottieAnimation<br>          src=&quot;stickers/not_found.json&quot;<br>          title=&quot;Oops, Something Went Wrong!&quot;<br>          overview=&quot;We couldn&#39;t verify your identity.&quot;<br>        /&gt;<br>      );<br>    };<br>  }<br><br>  return () =&gt; {<br>    return &lt;h1&gt;Valid data&lt;/h1&gt;;<br>  };<br>};</pre><p>Let’s test it. Open your bot in Telegram and click “Start Matching” button. You’ll see the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bIg7jsBYiwQ1O93c.png" /></figure><p>To test what happens when user data is invalid, change verifyInitData(data.initData) to verifyInitData(data.initData + 1) and you&#39;ll see the following screen (don&#39;t forget to return it back to verifyInitData(data.initData) after testing):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*joIaPzHIWEPi7KHR.png" /></figure><h3>Setting up server logic</h3><p>We will now program logic defined before in “Defining the Movie Matcher app flow” section. Copy this <a href="https://github.com/jansivans/tg-movie-matcher-app/blob/main/src/index.ts">index.ts</a> and replace your index.ts file with it. Modify your utils.ts code with <a href="https://github.com/jansivans/tg-movie-matcher-app/blob/main/src/utils.ts">this code</a>.</p><p>Let’s go through the code we’ve added to index.ts file. Main logic of this script is around methods a server exposes to all components:</p><ul><li>enterStage - will be called when user enters a stage (opens app). If there are no stages with specific chat_instance, new stage will be created. If there are stages with specific chat_instance, user will be added to the stage with the same chat_instance. After this method is called, stageUpdated event will be emitted to all components within the same chat_instance group.</li><li>exitStage - will be called when user exits a stage (disconnects from app). If there are no users left in the stage, stage will be deleted. If there are some users left in the stage and they are in movie selection state, movie selection gets recalculated using updateMovieSelectionState function. We will go trough this function later. After this method is called, stageUpdated event will be emitted to all components within the same chat_instance group.</li><li>restartStage - will be called when user restarts a stage (clicks &quot;Back&quot; button). It simply resets stage preserving users and movie options. After this method is called, stageUpdated event will be emitted to all components within the same chat_instance group.</li><li>changeMovieOption - will be called when user changes movie option (selects genres or years). After this method is called, stageUpdated event will be emitted to all components within the same chat_instance group.</li><li>startMovieSelection - will be called when user starts movie selection (clicks &quot;Start&quot; button). It will search for movies using movie API and selected years and genres and switch to movie selection scene. After this method is called,stageUpdated event to all components within the same chat_instance group.</li><li>rateMovie - will be called when user rates a movie (swipes left or right). It will call updateMovieSelectionState function which determines whether movieSelected or movieNotSelected. If so, stageUpdated event to all components within the same chat_instance group.</li></ul><p>There is also updateMovieSelectionState function which counts likes and dislikes. If it determines that movie is selected (all users matched on one movie), it sends users a notification message and emits movieSelected event. If it determines that movie is not selected (all users made their selection and no movie was matched), it emits movieNotSelected event.</p><h3>Matching main component to server logic</h3><p>Now as we have server logic, let’s match main component to it. Copy this <a href="https://github.com/jansivans/tg-movie-matcher-app/blob/main/src/components/home.tsx">home.tsx</a> and replace your home.tsx file with it. Let&#39;s go through the code we&#39;ve added to home.tsx file.</p><ul><li>We receive stage state from server by using EventHub.on(&#39;stageUpdated&#39;) event handler. Inside this handler:<br>- If user is on <strong>setup screen</strong>, component calls browser to show main button and sets main button text to “Start”. It aslo hides back button if user was selecting genres or years.<br>- If user is on <strong>matching screen</strong>, component calls browser to hide main button and show back button.<br>- If user is on <strong>movie selected screen</strong>, component calls browser to show back button and calls explode browser command to show confetti animation.<br>- If user is on <strong>no movie selected screen</strong>, component calls browser to show back button.</li><li>When user initializes component (ComponentInstance.onInit), a server call enterStage method is called.</li><li>When user destroys component (ComponentInstance.onDestroy), a server call exitStage method is called.</li><li>All events from browser are also handled:<br>- When user clicks main button, startMovieSelection method is called.<br>- When user clicks back button and user is not in <strong>setup screen</strong>, restartStage method is called.<br>- When user changes viewport height, viewportHeight internal variable is updated (we will see how it is used later).</li></ul><p>Based on state the component is in, it renders different screens. But now we can’t launch our app because we haven’t added some necessary components yet. Let’s do it now.</p><h3>Options button component</h3><p>Add optionsButton.tsx file to src/components folder and add the following code to it:</p><pre>export const component: DraymanComponent&lt;{<br>  buttonLabel: string;<br>  selectedLabel: string;<br>  onSelect: () =&gt; Promise&lt;void&gt;;<br>}&gt; = async ({ props }) =&gt; {<br>  return async () =&gt; {<br>    return (<br>      &lt;div<br>        class=&quot;select clickable&quot;<br>        onclick={async () =&gt; await props.onSelect()}<br>      &gt;<br>        &lt;div&gt;{props.buttonLabel}&lt;/div&gt;<br>        &lt;div class=&quot;separator&quot;&gt;&lt;/div&gt;<br>        &lt;div&gt;{props.selectedLabel} ›&lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  };<br>};</pre><p>This component will be used to show options button. We’ll use it to show genres and years buttons. It is crafted to match Telegram UI style and matches user’s theme color:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*5ZiAqIl_i4Pw4q8_.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*nseQAYEFtbxMrXXV.png" /></figure><h3>Options menu component</h3><p>Add optionsMenu.tsx file to src/components folder and add the following code to it:</p><pre>export const component: DraymanComponent&lt;{<br>  header: string;<br>  options: any[];<br>  selectedOption: any;<br>  viewportHeight: number;<br>  onSelect: (data: { value: any }) =&gt; Promise&lt;void&gt;;<br>}&gt; = async ({ props }) =&gt; {<br>  return async () =&gt; {<br>    return (<br>      &lt;div<br>        class=&quot;options-menu right-to-left-appear&quot;<br>        style={{ height: `${props.viewportHeight - 20}px` }}<br>      &gt;<br>        &lt;div class=&quot;option-header&quot;&gt;{props.header}&lt;/div&gt;<br>        &lt;div class=&quot;select-wrapper&quot;&gt;<br>          {props.options.map((option) =&gt; {<br>            return (<br>              &lt;div<br>                class=&quot;select clickable&quot;<br>                onClick={async () =&gt; await props.onSelect({ value: option })}<br>              &gt;<br>                &lt;div&gt;{option.name}&lt;/div&gt;<br>                &lt;div class=&quot;separator&quot;&gt;&lt;/div&gt;<br>                &lt;div&gt;{props.selectedOption.id === option.id &amp;&amp; `✓`}&lt;/div&gt;<br>              &lt;/div&gt;<br>            );<br>          })}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  };<br>};</pre><p>This component will be used to show options menu. It is crafted to match Telegram UI style and matches user’s theme color:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mUJruNTX_tuLM-p6.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*zfmX7IV0RIfw2ggp.png" /></figure><h3>Movie card component</h3><p>Add movieCard.tsx file to src/components folder and add the following code to it:</p><pre>import chroma from &quot;chroma-js&quot;;<br>import { genres } from &quot;../utils&quot;;<br><br>export const component: DraymanComponent&lt;{<br>  movie: any;<br>  viewportHeight: number;<br>}&gt; = async ({ props }) =&gt; {<br>  const ratingScale = chroma.scale([&quot;#e64d44&quot;, &quot;#32b545&quot;]).domain([0, 10]);<br><br>  return async () =&gt; {<br>    return (<br>      &lt;div class=&quot;wrapper&quot;&gt;<br>        &lt;div<br>          class=&quot;fade-image&quot;<br>          style={{<br>            &quot;--dynamic-bg-image&quot;: `url(https://medium.com/&#39;https://image.tmdb.org/t/p/w1280/${props.movie.backdrop_path}&#39;)`,<br>          }}<br>        &gt;<br>          {!!props.movie.vote_count &amp;&amp; (<br>            &lt;div<br>              class=&quot;rating-circle&quot;<br>              style={{<br>                background: ratingScale(props.movie.vote_average).hex(),<br>              }}<br>            &gt;<br>              {props.movie.vote_average}<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>        &lt;div class=&quot;title&quot;&gt;{props.movie.title}&lt;/div&gt;<br>        &lt;div class=&quot;genre&quot;&gt;{`${props.movie.genre_ids<br>          .map((x) =&gt; genres.find((xx) =&gt; xx.id == x).name)<br>          .join(&quot;, &quot;)} | ${props.movie.release_date.slice(0, 4)}`}&lt;/div&gt;<br>        &lt;div<br>          class=&quot;overview&quot;<br>          style={{ height: `${props.viewportHeight - 340}px` }}<br>        &gt;<br>          {props.viewportHeight - 340 &gt; 100 &amp;&amp; (<br>            &lt;div class=&quot;content&quot;&gt;{props.movie.overview}&lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  };<br>};</pre><p>This component will be used to show movie card. It is crafted to match Telegram UI style and matches user’s theme color:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*QlFqsiUAnQ4jgpsr.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*xiua1PL3U35d9MMu.png" /></figure><p>Movie card component has rating badge which is colored using chroma-js library based on movie rating.</p><h3>Final look at the main component</h3><p>Now we have everything set up. Let’s check how our main component looks like.</p><h4>Setup screen and year/genre selection screens</h4><p>Main screen where user can select genres and years and see connected users. It matches Telegram UI style and matches user’s theme color. It also has transition animation when user navigates between screens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*nBW0-JK0ZUpHCvp2.gif" /></figure><h4>Matching screen and movie selected screen</h4><p>Matching screen is a screen where user can swipe movie cards. If all users swipe right on the same movie, confetti animation will be shown, notifcation message will be sent from the bot and users will see the <strong>movie selected screen</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/0*v2peIYc5-RkGeQXH.gif" /></figure><h4>Waiting for others screen</h4><p>When user made selection and there are no more movies to swipe and other users haven’t made their selection yet, user will see the <strong>waiting for others screen</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8FT0tsM16OHyhVRn.png" /></figure><h4>No movie selected screen</h4><p>When all users made selection and haven’t matched with any movie, users will see the <strong>no movie selected screen</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fn9QL3g_7kKQ4v4F.png" /></figure><h4>No movies screen</h4><p>When user clicks “Start” button, and there are no movies with selected genres and years, user will see the <strong>no movies screen</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lRh0GDqiG266IiXl.png" /></figure><h4>Invalid data screen</h4><p>When user can’t be <a href="https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app">validated</a>, <strong>failed validation screen</strong> will be shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fLLmv_eIz4f_hT-W.png" /></figure><h3>Reacting to viewport height change</h3><p>Some of components are using viewport height which is received from Telegram API. You can see method which returns viewport height in index.html file:</p><pre>Telegram.WebApp.onEvent(&quot;viewportChanged&quot;, () =&gt;<br>  emit(<br>    onViewportChanged,<br>    { viewportHeight: window.Telegram.WebApp.viewportHeight },<br>    { debounce: 300 }<br>  )<br>);</pre><p>It is then received in home.tsx file:</p><pre>onViewportChanged: async (data) =&gt; {<br>  viewportHeight = data.viewportHeight;<br>  await forceUpdate();<br>};</pre><p>Then, it is passed to some components as a prop and height of elements is calculated based on it. This way we can make our app responsive to viewport height change and also hide or show some elements based on viewport height:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/0*xsfFbPj7G5zbQOoa.gif" /></figure><h3>Reacting to theme change</h3><p>Because all component styles are built aroun <a href="https://core.telegram.org/bots/webapps#themeparams">Telegram CSS variables</a>, our app will automatically change its style when user changes theme:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*KxG-zsm79Vu8soYW.gif" /></figure><h3>Multiplayer usage</h3><p>If a link to the app (in our case it is t.me/movie_matcher_test_bot/app) is sent to a chat, all users who open this link within the same chat will be added to the same group. This way, users can match with each other. If a user opens the app link in a different chat, he will be added to a different group. This way, users can match with different people in different chats:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*GhKSpKOlVscnrXeF.gif" /></figure><h3>Publishing the app</h3><p>The easiest way to publish you app is to use <a href="https://render.com/">render</a>. While they offer a free plan, it’s not ideal for Telegram apps since it suspends them after periods of inactivity. However, their first paid plan is just $7/month, which is suitable for hosting small Telegram apps without significant traffic.</p><p>Some tips of publishing your app on render:</p><ul><li>Don’t forget to add BOT_TOKEN and MOVIE_DB_API_KEY environment variables. Also you&#39;ll need to add PORT environment variable and set it to 3033:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BoktHzGTGYhBsrRH.png" /></figure><ul><li>You’ll also need to use npm install as build command and npm run start as start command:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wN3UUSMfjsFRRIp7.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5104df9572e8" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/building-telegram-mini-app-with-drayman-framework-5104df9572e8">Building Telegram Mini App with Drayman Framework</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a real-time Todo app with Drayman, MongoDB and Tailwind CSS]]></title>
            <link>https://itnext.io/building-a-real-time-todo-app-with-drayman-mongodb-and-tailwind-css-25d57ed5cfda?source=rss-cb2814e79a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/25d57ed5cfda</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[drayman]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[webdev]]></category>
            <dc:creator><![CDATA[Yan Ivan Evdokimov]]></dc:creator>
            <pubDate>Tue, 31 Aug 2021 06:14:26 GMT</pubDate>
            <atom:updated>2021-08-31T07:04:18.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vxGDp1PE4m2deQRAeHuuTQ.png" /></figure><p>In this guide we will build a real-time Todo app with <a href="http://www.drayman.io/">Drayman</a>, <a href="https://www.mongodb.com/">MongoDB</a> and <a href="https://tailwindcss.com/">Tailwind CSS</a>.</p><p>If you are using regular tools, you would need to create a server with endpoints, a client app using some modern framework or just vanilla JavaScript. With Drayman, however, it will be just a single script with 100 lines of code.</p><p>If you are new to Drayman, you can go to our <a href="http://www.drayman.io/">official docs</a> to check out how it works or to read other guides.</p><h3>Prerequisites</h3><p>This guide assumes that you:</p><ul><li>have <a href="http://www.drayman.io/docs/introduction/getting-started">installed Drayman project locally</a> or you are using it through <a href="http://new.drayman.io/">new.drayman.io</a>;</li><li>have MongoDB installed with <a href="https://docs.mongodb.com/manual/changeStreams/">Change Stream</a> functionality enabled. For this guide you can create a free cloud MongoDB database <a href="https://www.mongodb.com/try">here</a>. This way you get Change Stream functionality enabled by default.</li></ul><p>When Drayman project is ready and you have MongoDB up and running, we can start developing our Todo app by adding Tailwind CSS.</p><h3>Setting up Tailwind CSS</h3><p>First, you’ll need to install autoprefixer and tailwindcss:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25f6c3b4874a13aba2c0628b884dbe49/href">https://medium.com/media/25f6c3b4874a13aba2c0628b884dbe49/href</a></iframe><p>Next, generate tailwind.config.js and postcss.config.js files with this command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a94cf30324f736e84eefab2534bf72a0/href">https://medium.com/media/a94cf30324f736e84eefab2534bf72a0/href</a></iframe><p>Now modify tailwind.config.js file to exclude non-used CSS classes on compile:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/563fbac2cfcd844c2e3e096548fae5fd/href">https://medium.com/media/563fbac2cfcd844c2e3e096548fae5fd/href</a></iframe><p>Create your main CSS file at src/styles.css and append this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1d876259f19ef1e0ef4080ef415f380/href">https://medium.com/media/c1d876259f19ef1e0ef4080ef415f380/href</a></iframe><p>The final step is to modify public/index.html file to include the generated CSS file. Drayman will generate it to the public/styles.css file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89fde78005c6aeba1307687825ebad49/href">https://medium.com/media/89fde78005c6aeba1307687825ebad49/href</a></iframe><h3>Creating a Todo app</h3><p>We will start by adding basic UI using Tailwind CSS classes and then improve our solution to include real-time functionality and MongoDB support.</p><h3>Adding basic UI</h3><p>Paste this code inside src/components.home.tsx:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2041870908d5e2841af4b9da8cc3894f/href">https://medium.com/media/2041870908d5e2841af4b9da8cc3894f/href</a></iframe><p>If Tailwind CSS was successfully initialized, you should see this result in your browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*a0XH73UI2GbzHdIy.png" /></figure><h3>Adding MongoDB support</h3><p>For this guide we will use <a href="https://docs.mongodb.com/manual/changeStreams/">Change Stream</a> functionality of MongoDB to make our Todo list work in real-time. This way if something gets changed in the database, our application will reflect these changes. Let’s modify our src/components/home.tsx component and see in detail what is happening inside our script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa13026980c9433f8aa71598190a8d86/href">https://medium.com/media/fa13026980c9433f8aa71598190a8d86/href</a></iframe><p>First, we have added a connection to our database (don’t forget to change YOUR_MONGODB_CONNECTION_STRING to your actual connection string). Then we made the initial fetch of our Todo list by converting it to an array - let todos = await todoListCollection.find().toArray();.</p><p>Then we added real-time functionality by watching for changes to database todoListCollection.watch():</p><ul><li>on insert a Todo will be pushed to todos array;</li><li>on update a specific Todo from todos array will be updated;</li><li>on delete a specific Todo from todos array will be deleted.</li></ul><p>The component will reflect all these changes because we also call the <a href="http://www.drayman.io/docs/components-in-depth/helpers/force-update">forceUpdate</a> function — if any change gets caught, the component will re-render itself.</p><p>Finally, we are using the <a href="http://www.drayman.io/docs/components-in-depth/helpers/the-component-instance-object">onDestroy</a> lifecycle method to close the connection to the database when a component instance gets destroyed.</p><p>We also have made changes to our UI by mapping through todos array and rendering each Todo and changing CSS classes dynamically when a Todo is done.</p><p>As a result, any change made inside the database (I am using <a href="https://tableplus.com/">TablePlus</a> for this), gets reflected inside our component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*s7oxiW-L1rGqmSOp.gif" /></figure><p>Our final step will be to make the input field and buttons work as expected.</p><h3>Adding functionality to UI elements</h3><p>We will start by modifying the &lt;input&gt; element:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/434d0a26319c1881736af9b13dbd24ca/href">https://medium.com/media/434d0a26319c1881736af9b13dbd24ca/href</a></iframe><p>The variable newTodo was introduced. When the user types in something, the oninput event gets triggered that saves the input value to the newTodo variable thus providing a single source of truth - the input&#39;s value will always be inside newTodo.</p><p>Let’s now modify the &lt;button&gt;Save&lt;/button&gt; element:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/533258f23c1e5d1a0b2e81b46dfbfef2/href">https://medium.com/media/533258f23c1e5d1a0b2e81b46dfbfef2/href</a></iframe><p>We have modified class and disabled attributes to appear disabled when there is no input by the user (newTodo is empty). When the user clicks a button, onclick gets triggered and a new Todo gets inserted into the database. We also don&#39;t need to call forceUpdate here because it already was managed before when watching for database changes. Now we can input something, click the button and the result will appear in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*q-XXqoc5cufRjMkj.gif" /></figure><p>Our final step will be to modify todos list mapping:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44336fc03c2bcdd69c5b1d66b9a7d18d/href">https://medium.com/media/44336fc03c2bcdd69c5b1d66b9a7d18d/href</a></iframe><p>Here we have added the onclick event handler for &lt;div&gt; to mark a Todo done or undone and the onclick event handler for &lt;button&gt;Delete&lt;/button&gt; to delete a Todo from the database when it is clicked.</p><p>Our component is now complete and you can open a page with this component in multiple tabs to check real-time functionality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*1i4RXuo4A_yqicMC.gif" /></figure><h3>Final component script</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc033bfaf2988ffbd3423b65899c392b/href">https://medium.com/media/fc033bfaf2988ffbd3423b65899c392b/href</a></iframe><h3>Conclusion</h3><p>We have created a real-time Todo app with Drayman, MongoDB and Tailwind CSS in just 100 lines of code, inside a single script.</p><p>If this felt interesting to you, visit the <a href="http://www.drayman.io/">official docs</a> to deep-dive into Drayman framework!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25d57ed5cfda" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/building-a-real-time-todo-app-with-drayman-mongodb-and-tailwind-css-25d57ed5cfda">Building a real-time Todo app with Drayman, MongoDB and Tailwind CSS</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Drayman]]></title>
            <link>https://itnext.io/getting-started-with-drayman-ce355ecfe22a?source=rss-cb2814e79a8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce355ecfe22a</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[drayman]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Yan Ivan Evdokimov]]></dc:creator>
            <pubDate>Wed, 18 Aug 2021 04:36:32 GMT</pubDate>
            <atom:updated>2021-08-24T15:03:29.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klb0_C9cOQRnOk3dfwiK-g.png" /></figure><p><a href="http://www.drayman.io/">Drayman</a> is a server-side component framework that allows you to use any available HTML element, web component or custom Drayman third-party component together with server-side code in a single script.</p><p>With Drayman, the browser only renders what the user should see — all logic and calculations happen server-side and UI is written using JSX syntax.</p><p>The best way to show Drayman capabilities is to create something with it. So let’s get started.</p><h3>File viewer component</h3><p>Let’s build a component that allows the user to select a file from the file system and view it’s contents.</p><p>First, you need to install Drayman. It can be done by running these commands:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b682af4106a98aaa304cd4334bb6214d/href">https://medium.com/media/b682af4106a98aaa304cd4334bb6214d/href</a></iframe><p>The website will be available at <a href="http://localhost:3033/">http://localhost:3033</a>.</p><p>If you don’t want install anything, you can always try Drayman inside CodeSandbox by visiting <a href="http://new.drayman.io/">new.drayman.io</a>.</p><h4>Initial component template</h4><p>Go to src/components/home.tsx and replace its contents with this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe70f5b2713cdf45090aa15fcce6c735/href">https://medium.com/media/fe70f5b2713cdf45090aa15fcce6c735/href</a></iframe><p>You will see an initial skeleton of our component. Further &lt;select&gt; will be used to show available files and &lt;pre&gt; will show contents of the selected file.</p><h4>Filling select with options</h4><p>Because Drayman runs a component server-side, we can use any Node.js library. In our case we will use the fs module.</p><p>Let’s read file names from the project root directory and fill &lt;select&gt; options with them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8759b2376930ac28d4bacfc16064e10/href">https://medium.com/media/e8759b2376930ac28d4bacfc16064e10/href</a></iframe><p>Right now our component is only showing some elements without any interactivity. Our next step will be to add it.</p><h4>Reacting to user actions</h4><p>We need to remember which file the user has selected to show its contents. It can be done by using the onchange event attribute and attaching a function that will be <a href="http://www.drayman.io/docs/components-in-depth/handling-events">executed server-side</a>. We also need to add the value attribute to each option so that select would know which option was selected.</p><p>Let’s also add the fs.readFile function inside the &lt;pre&gt; tag so that Drayman would read file contents during re-render. We won&#39;t show the pre until a file is actually selected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1289f7f2990194a74d3734ef64bcda9c/href">https://medium.com/media/1289f7f2990194a74d3734ef64bcda9c/href</a></iframe><p>If you make a selection from the dropdown, you will see that nothing happens on the page — file contents don’t appear. That is because with Drayman you must strictly tell when a component needs to be re-rendered. It can be done by using a special <a href="http://www.drayman.io/docs/components-in-depth/helpers/introduction">helper function</a> forceUpdate.</p><p>Import it and add to the onchange event after the selected file was saved:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e785c68a330eab4d719afc61e89d04db/href">https://medium.com/media/e785c68a330eab4d719afc61e89d04db/href</a></iframe><p>Now our component is complete and file contents are shown on select:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-eujpP1gvvJpR3LAopNXMA.gif" /></figure><h3>Conclusion</h3><p>We have built a component that combines server-side logic and client-side view in a single script.</p><p>If this felt interesting to you, visit the <a href="http://www.drayman.io/">official docs</a> to deep-dive into Drayman framework!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce355ecfe22a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/getting-started-with-drayman-ce355ecfe22a">Getting started with Drayman</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>