<?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 Joe Robertson on Medium]]></title>
        <description><![CDATA[Stories by Joe Robertson on Medium]]></description>
        <link>https://medium.com/@joe.robertson_mx?source=rss-70162395082c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tBrWyC0BmDXZB1NgVsKg2A.png</url>
            <title>Stories by Joe Robertson on Medium</title>
            <link>https://medium.com/@joe.robertson_mx?source=rss-70162395082c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:35:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joe.robertson_mx/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[Build widgets in Mendix with React Part 4— ArcGIS Maps]]></title>
            <link>https://medium.com/mendix/build-widgets-in-mendix-with-react-part-4-arcgis-maps-1eb44777f0c3?source=rss-70162395082c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1eb44777f0c3</guid>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mendix]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Joe Robertson]]></dc:creator>
            <pubDate>Thu, 20 Oct 2022 10:44:33 GMT</pubDate>
            <atom:updated>2022-10-20T10:44:33.038Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this blog, we are going to be building some maps into our widget, using the ArcGIS Javascript API, and a little history lesson along the way.</h4><figure><img alt="Build widgets in Mendix with React Part 4- ArcGIS Maps (Banner Image)" src="https://cdn-images-1.medium.com/max/1024/1*6ki5siWavxdiUqJG8BrwCA.png" /><figcaption>Build widgets in Mendix with React Part 4 — ArcGIS Maps</figcaption></figure><h4>Mendix is the number one low-code platform, and one of its key strengths is the extensibility it provides. You can use React to incorporate cool third-party libraries and extend your application.</h4><p>This is blog 4 in a multi-part series, the previous blogs can be found here:</p><ul><li><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff">Build widgets in Mendix with React — Part 1 — Colour Counter</a></li><li><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-2-timer-b65c720b34e3">Build Widgets in Mendix with React Part 2 — Timer</a></li><li><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-3-kanban-2598aa71444d">Build Widgets in Mendix with React Part 3 — Kanban</a></li></ul><h4>What are we building</h4><p>Recently, <a href="https://medium.com/u/b43844a7f8d5">Ivo Sturm</a> wrote a blog about converting an existing ArcGIS widget from Dojo to React.</p><p>I thought it would be interesting to <strong>build a simple version of the ArcGIS map widget from scratch</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNlK3NwAnJIkRtq7JcZbEA.png" /></figure><h4>Get started</h4><p>As with all of the pluggable widget blogs up to this point, we begin by <strong>scaffolding our widget</strong> by running yo @mendix/widget arcGISMap and <a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff">setting up a test Mendix project</a>.</p><p>Let’s start by <strong>installing the npm package</strong> for the ArcGIS Javascript API</p><pre>npm install @arcgis/core </pre><p>ArcGIS is an online geographic information system that allows you to display maps and add layers to display a whole range of information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYOeglXLJ6-H30lKfSNiPQ.png" /></figure><p>In order to access the full service <a href="https://developers.arcgis.com/documentation/mapping-apis-and-services/get-started/">you need to register and create an access token</a> but we can press on without one for our simple example.</p><h4>Getting started</h4><p>Reviewing the <a href="https://developers.arcgis.com/javascript/latest/display-a-map/#create-a-map-view">documentation</a> we can update our code to have two files:</p><p><strong>A parent</strong></p><pre>import { ReactElement, createElement } from &quot;react&quot;;<br>import { MapComponent } from &quot;./components/Map&quot;;<br>import { ArcGISMapBlogContainerProps } from &quot;../typings/ArcGISMapBlogProps&quot;;<br>import &quot;./ui/ArcGISMapBlog.css&quot;;</pre><pre>export function ArcGISMapBlog(props: ArcGISMapBlogContainerProps): ReactElement {<br>    return &lt;MapComponent basemap={props.basemap} /&gt;;<br>}</pre><p><strong>And a child</strong></p><pre>import { ReactElement, createElement, useEffect, useRef } from &quot;react&quot;;<br>import Map from &quot;<a href="http://twitter.com/arcgis/core">@arcgis/core</a>/Map&quot;;<br>import MapView from &quot;<a href="http://twitter.com/arcgis/core">@arcgis/core</a>/views/MapView&quot;;<br>import Legend from &quot;<a href="http://twitter.com/arcgis/core">@arcgis/core</a>/widgets/Legend&quot;;</pre><pre>export interface MapProps {<br>    basemap: string;<br>}</pre><pre>export function MapComponent({ basemap }: MapProps): ReactElement {<br>    const mapDiv = useRef(null);</pre><pre>useEffect(() =&gt; {<br>        if (mapDiv.current) {<br>            MountMap(basemap);<br>        }<br>    }, [basemap]);</pre><pre>const MountMap = (basemap: string): MapView =&gt; {<br>        const legend = new Legend();<br>        const map = new Map({ basemap });<br>        const view = new MapView({<br>            map,<br>            center: [0.029, 51.256], // Longitude, latitude<br>            zoom: 10, // Zoom level<br>            container: mapDiv.current as unknown as HTMLDivElement <br>        });</pre><pre>        legend.view = view;<br>        view.ui.add(legend, &quot;bottom-right&quot;);<br>        return view;<br>    };</pre><pre>return &lt;div id=&quot;viewDiv&quot; ref={mapDiv} style={{height: &quot;500px&quot;}}/&gt;;<br>}</pre><p>Let’s <strong>also import the stylesheet from ArcGIS</strong> so that we can make our widget look nice, change your UI/{widgetName}.css to:</p><pre>@import &quot;https://js.arcgis.com/4.24/@arcgis/core/assets/esri/themes/dark/main.css&quot;;</pre><p>Now we build our widget with npm run build and… we get an error:</p><pre>[!] Error: Invalid value for option &quot;output.file&quot; - when building multiple chunks, the &quot;output.dir&quot; option must be used, not &quot;output.file&quot;. To inline dynamic imports, set the &quot;inlineDynamicImports&quot; option.</pre><p>So how do we fix this? In order to explain, we need to take a few steps back…</p><h4>A brief history of Javascript</h4><blockquote>This next section is a brief history of Javascript, to give context to the solution, if this is not of interest to you, feel free to skip and continue with the example</blockquote><p>In the beginning…</p><p>Javascript was invented by Brendan Eich in 1995, and for the first several years of its development, it was used primarily for isolated scripting tasks. As JS started to be used more in applications, it became more difficult to manage the code. JS was used in more complex ways often across multiple scripts, which inevitably led to function and name conflicts.</p><p>As such, the module concept was introduced, this meant that code could be written in a closed place for internal use without fear of conflicts elsewhere and also allowed developers to break large codebases down into small separate parts, making it much easier to write and maintain.</p><p>The first attempt to fix this was with <strong>Immediately Invoked Function Expressions (IIFE)</strong>, which essentially just wrapped each file in a function, keeping variables and functions within a file, in that scope instead of the global scope.</p><p>(function() {// Your code }) ();</p><p>There are still many problems with this approach, including a lack of dependency resolution and <a href="https://www.tutorialspoint.com/what-is-global-namespace-pollution-in-javascript#:~:text=Polluting%20Global%20namespace%20causes%20name,be%20using%20several%20javascript%20libraries">pollution of the global namespace</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*LEhYXTDHIIIY1mJy.jpg" /></figure><p>Over time 3 separate (and competing) module specs emerged:</p><ul><li><strong>CommonJS</strong> — still widely used in Node for server-side JS, and easily recognizable by it’s require() and module.exports syntax</li><li><strong>AMD</strong> — Asynchronous Module Definition, split from CommonJS early. The key difference is that AMD allows modules that are not dependent on each other to be loaded async (it’s all in the name!)</li><li><strong>UMD</strong> — Universal Module Definition, supports both of the other module specs as well as ‘old style’ “global” variable definition</li></ul><p>This is all very complicated…so some good news. Since 2015 and the release of ES6, <strong>modules have been supported within the Javascript language</strong>. This gives us the lovely and simpleimport and export syntax we have been using in our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*9ln2Fsb4h3Sa3afR.jpg" /></figure><p>So why the history lesson? Well, we need to be able to handle all of these module types when we write our code, and that is where bundlers come in.</p><h3>Bundlers</h3><p>Bundlers allow you to <strong>compile your code at build time</strong>, <strong>process your dependencies</strong>, and <strong>serve up a compatible concatenated file</strong>. Common solutions for this include <strong>Webpack</strong> (used in Mendix 8 widgets) and <strong>rollup</strong> (used in Mendix 9 widgets)</p><p>This lets you write your code modularly using modern ES6 features (and even Typescript if you fancy it) and then produce an optimized file (or set of files) to be served to the browser.</p><p>This is great, but some browsers don’t yet support ES6, so they won’t be able to do anything with these nicely compiled files. In order to fix this <strong>we can use a Transpiler</strong> such as <strong>Babel</strong> to serve it to the webpage in a format in which it can be read.</p><p>So back to our widgets…</p><p>The Pluggable Widget framework requires all of the tools you need to develop React components for Mendix apps. This includes:</p><ul><li><strong>npm</strong> — A package manager to easily install and manage third-party packages</li><li><strong>rollup</strong> — A bundler, which lets you write your code modularly and then bundle it together in small packages</li><li><strong>babel</strong> — A transpiler that converts the JS into a format that can be read by older browsers (and Studio Pro)</li></ul><p>So what’s our error mean?</p><pre>[!] Error: Invalid value for option &quot;output.file&quot; - when building multiple chunks, the &quot;output.dir&quot; option must be used, not &quot;output.file&quot;. To inline dynamic imports, set the &quot;inlineDynamicImports&quot; option.</pre><p>For each widget project, we use the rollup configuration provided by the @mendix/pluggable-widget-tools library.</p><blockquote>This can be found in:</blockquote><blockquote><strong>node_modules/@mendix/pluggable-widget-tools/configs.rollup.config.js.</strong></blockquote><p>In this configuration, we are <strong>telling our widget to spit out our compiled JS into a single file</strong>. Meanwhile, the <strong>ArcGIS npm library</strong> we are using provides <strong>dynamic imports in chunks</strong>, which by default <strong>rollup wants to spit out as separate files into a directory</strong>.</p><p>To fix this we just need do what it says in the error and <strong>set the inlineDynamicImports option</strong>, which will pull everything into one file. We could change the rollup.config.js file in the Pluggable Widgets library but this is a very bad idea as it is not maintainable, and creates very hard-to-read and debug code. Luckily <strong>Mendix has built-in functionality to set our own rollup config</strong>.</p><p>We need to <strong>create a file</strong> called r<strong>ollup.config.js</strong> in the root widget directory. We then add the following JS code to change how our widget is built:</p><pre>export default args =&gt; {<br>    const result = args.configDefaultConfig;<br>    console.warn (&#39;Custom roll up&#39;)<br>    return result.map((config) =&gt; {<br>                config.output.inlineDynamicImports = true<br>                console.warn (&quot;Set dynamic imports&quot;)<br>                return config;<br>    });<br>};</pre><p>So we run npm run build again, and get a new error:</p><pre>FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory</pre><p>Turns out the build process needs more memory. I can update this by running</p><pre>export NODE_OPTIONS=--max_old_space_size=5120</pre><p>If we rebuild then our widget now compiles.</p><p>Our bundler can help us create single files so that they can be easily read by the browser.</p><p>Rollup also does something else very clever, called <strong>Tree Shaking</strong>: this involves building an image of the <strong>dependency tree in your code</strong> and <strong>only including the code that is actually needed</strong>. This is particularly useful when using large libraries, and avoids loading large amounts of unused code into the browser. This tree shaking is one of the key factors Mendix made the switch from webpack to rollup between Mendix 8 and 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*VtrgoyahncJ234G8.gif" /></figure><p>Bundlers also come with a whole host of other features, in roll-up, these are in the form of plugins. The last thing I want to do in this blog is cover a really common use case for having to modify your rollup config for your widget</p><h3>Serving up the files your widget needs</h3><p>ArcGIS delivers the files needed to create your map via a <strong>content delivery network (CDN)</strong> . However there may be <strong>instances where you want to keep</strong> <strong>and manage these files within your widget</strong>, perhaps due to do firewall settings within your organization. Fortunately, the ArcGIS Javascript API makes this possible.</p><p>The first thing to do is to update our code, to <strong>tell the API</strong> that we will be <strong>managing our assets locally</strong>. To do this we simply update our container component to contain:</p><pre>import esriConfig from &quot;<a href="http://twitter.com/arcgis/core">@arcgis/core</a>/config.js&quot;;</pre><pre>export function ArcGISMapBlog(props: ArcGISMapBlogContainerProps): ReactElement {<br>    esriConfig.assetsPath = &quot;./widgets/mendix/arcgismapblog/assets&quot;;<br>    return &lt;MapComponent basemap={props.basemap} /&gt;;<br>}</pre><p>Next, we need to <strong>update</strong> our <strong>rollup</strong> to <strong>pick up the files we</strong> need from our node modules and <strong>put them in our widget</strong> mpk.</p><p>To do this we can <strong>use the rollup copy plugin</strong> (there are plugins for everything), first, we need to install it</p><pre>npm i rollup-plugin-copy —save-dev </pre><p>We use the —save-dev command because it is a dependency only required while developing. Then we update our rollup.config.js to:</p><pre>import copy from &quot;rollup-plugin-copy&quot;;<br>export default args =&gt; {<br>    const result = args.configDefaultConfig;<br>    console.warn (&#39;Custom roll up&#39;)<br>    return result.map((config) =&gt; {<br>                config.output.inlineDynamicImports = true<br>                console.warn (&quot;Set dynamic imports&quot;)<br>                const plugins = config.plugins || []<br>                config.plugins = [<br>                    ...plugins,<br>                    copy({<br>                        targets: { src:&quot;node_modules/@arcgis/core/assets&quot;, dest:&quot;dist/tmp/widgets/mendix/arcgismapblog&quot; }]</pre><pre>}),<br>                ]  <br>                return config;<br>    });<br>};</pre><p>This <strong>takes the ‘assets’</strong> folder from the ArcGIS npm package and <strong>drops it into our dist/tmp folder</strong> which is what is ultimately zipped to create our mpk. Then when we run our application the contents of the widget mpk are served up to <strong>./widgets/{yourOrganisationName}/{yourWidgetName}</strong>.</p><p>To see this in action let’s run the command to build our widget</p><pre>npm run build</pre><p>We can then re-run our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*5YGKygT3y96vxsbg4pW3Ww.png" /></figure><p>If we open our deployment directory we can see that the widget is serving up the assets folder, and if we check our page sources in our chrome dev tools, we can see that the ArcGIS web assembly file is served up to the browser to ensure our map works</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*hxC8T5MeFMaN925ucwO90A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-E3chfzm0lJkObjX.png" /></figure><p>We didn’t update our CSS to use local files. To do this we simply update our file to:</p><pre>@import &quot;../assets/esri/themes/dark/main.css&quot;;</pre><p>Simple….kind of….</p><p>If you are using the <strong>pluggable widget tools of 9.13.2 or below</strong> and you are using Windows, then your <strong>fonts will not be imported properly</strong>. The following code is required in your rollup.config.js to fix the imports:</p><pre>import postcssUrl from &quot;postcss-url&quot;;</pre><pre>const cssUrlTransform = asset =&gt; {<br>    const outWidgetDirForwardSlash = outWidgetDir.replace(/\\/g, &quot;/&quot;)<br>    return asset.url.startsWith(`${assetsDirName}/`) ? `${outWidgetDirForwardSlash}/${asset.url}` : asset.url;<br>}</pre><pre>export default args =&gt; {<br>    const result = args.configDefaultConfig;<br>    console.warn (&#39;Custom roll up&#39;)<br>    return result.map((config) =&gt; {<br>                config.output.inlineDynamicImports = true<br>                console.warn (&quot;Set dynamic imports&quot;)<br>                const plugins = config.plugins || []<br>                config.plugins = [<br>                    ...plugins,<br>                    postcssUrl (cssUrlTransform)</pre><pre>]  <br>                return config;<br>    });<br>};</pre><p>Then run npm install postcss-url --save-dev . Your widget will now render with icons.</p><p>And we are done!</p><p>The ArcGIS API is packed full of amazing features, I would encourage you to explore it. To see a great example of what it can do, check out Ivo Sturm’s widget:</p><p><a href="https://github.com/ivosturm/ArcGIS-React">GitHub - ivosturm/ArcGIS-React: A new and improved ArcGIS widget based on React</a></p><p>The repo for my ArcGIS widget can be found here:</p><p><a href="https://github.com/joe-robertson-mx/arcGISMapBlog">GitHub - joe-robertson-mx/arcGISMapBlog</a></p><p>In my next piece, we are going to use our understanding of rollup to run WebAssembly in our Mendix app, see you there!</p><p><em>From the Publisher -</em></p><p><em>If you enjoyed this article you can find more like it on our </em><a href="https://medium.com/mendix"><em>Medium page</em></a><em>. For great videos and live sessions, you can go to </em><a href="https://www.mendix.com/live/"><em>MxLive</em></a><em> or our community </em><a href="https://www.youtube.com/c/MendixCommunity/community"><em>Youtube pag</em></a><em>e.</em></p><p><em>For the makers looking to get started, you can sign up for a </em><a href="https://signup.mendix.com/link/signup/?source=direct"><em>free account</em></a><em>, and get instant access to learning with our </em><a href="https://academy.mendix.com/link/home"><em>Academy</em></a><em>.</em></p><p><em>Interested in getting more involved with our community? Join us in our </em><a href="https://join.slack.com/t/mendixcommunity/shared_invite/zt-hwhwkcxu-~59ywyjqHlUHXmrw5heqpQ"><em>Slack community channel</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1eb44777f0c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-4-arcgis-maps-1eb44777f0c3">Build widgets in Mendix with React Part 4— ArcGIS Maps</a> was originally published in <a href="https://medium.com/mendix">Mendix Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Widgets in Mendix with React Part 3 — Kanban]]></title>
            <link>https://medium.com/@joe.robertson_mx/build-widgets-in-mendix-with-react-part-3-kanban-2598aa71444d?source=rss-70162395082c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2598aa71444d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[mendix]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Joe Robertson]]></dc:creator>
            <pubDate>Tue, 09 Aug 2022 10:29:16 GMT</pubDate>
            <atom:updated>2022-08-09T10:29:16.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Widgets in Mendix with React Part 3 — Kanban</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfmauUuo3dObBxJ2Ksfazg.png" /><figcaption>Build Widgets in Mendix with React Part 3 — Kanban</figcaption></figure><h3>Mendix is the number one low code platform, which allows makers to develop applications considerably faster than traditional coding. The Mendix frontend is built using React and developers can extend their applications using Pluggable Widgets.</h3><p>In this blog we are going to learn about how to make permanent data changes in your application from your widget, combining widgets to create slick end-user experiences, custom hooks, and more…</p><p>This is the third blog in a multi-part series, blogs 1 &amp; 2 can be found here:</p><ul><li><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff">Build widgets in Mendix with React — Part 1 — Colour Counter</a></li><li><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-2-timer-b65c720b34e3">Build Widgets in Mendix with React Part 2 — Timer</a></li></ul><p>Before we start, a little disclaimer: For this build, we take advantage of some of the features of VS Code, instructions may vary if you prefer another IDE.</p><h3>What we are building</h3><p>Mendix has recently released <a href="https://docs.mendix.com/developerportal/collaborate/epics/"><strong>Epics</strong></a>, a new fully featured story management tool!</p><p>As part of this, there is a really nice component that allows you to drag and drop your stories. I thought it would be cool to try and build something similar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7r7rDhXyuQzlTtKggqyUw.gif" /></figure><p>There are a few things every Kanban board should be able to do:</p><ul><li>Allow users to set the Kanban stages</li><li>Be able to change the stage of an item by dragging</li><li>Be able to change the sort order of items in a section by dragging</li></ul><h3>Getting Started</h3><p>To start we scaffold the widget by running the widget generator to quickly scaffold a widget. Run the command:</p><p>yo @mendix/widget kanban</p><p>When configuring the widget properties, select the default options, while making sure to <strong>use Typescript</strong>.</p><p>Next, we are going to update the interface between our widget and the Mendix by updating Kanban.xml. To do this, we add a list of Datasource items to allow the user of the widget to specify what Mendix entities they want to use.</p><p>We have two options for actually rendering the items within the widget, we could use traditional JSX, or we can allow the user to build the design they want within Mendix. The second option has three main advantages:</p><ul><li>Prevents prescribing the structure the child data must be displayed in</li><li>Doesn’t hide code in harder-to-edit compiled widget files</li><li>Allows users to take advantage of the WYSIWG editor within Mendix</li></ul><h3>Rendering the List</h3><p>Option two wins! To implement this we can use the ‘<strong>widgets</strong>’ tag from the <strong>Pluggable Widgets API</strong>. The updated Kanban.xml now contains:</p><pre>&lt;property key=&quot;items&quot; type=&quot;datasource&quot; isList=&quot;true&quot; required=&quot;true&quot;&gt;<br>    &lt;caption&gt;Items&lt;/caption&gt;<br>    &lt;description&gt;List of items&lt;/description&gt;<br>&lt;/property&gt;<br>&lt;property key=&quot;widgetList&quot; type=&quot;widgets&quot; required=&quot;true&quot; dataSource=&quot;items&quot;&gt;<br>    &lt;caption&gt;Content&lt;/caption&gt;<br>    &lt;description&gt;Widgets using data source&lt;/description&gt;<br>&lt;/property&gt;</pre><p>Next, we can update our Kanban.TSX file to contain:</p><pre>export function Kanban({ widgetList, items }: KanbanContainerProps): ReactElement {<br>    return (<br>        &lt;div&gt;<br>              {items.items &amp;&amp; items.items.map(item =&gt; {<br>                   return widgetList.get(item);})}<br>        &lt;/div&gt;);<br>}</pre><p>There are a few things happening in the above code so I will break them down:</p><ul><li><strong>“widgetList ”</strong>is our widget interface into the Mendix model, if we right-click on “widgetList” and click ‘Go To Type Definition’ we can see our documentation for this type.</li></ul><pre>export declare interface ListWidgetValue {</pre><pre>    * Returns widgets configured by user in form of a react node <br>    rendered based on provided object item.*</pre><pre>    * @param item Instance of {@link ObjectItem} from the linked  <br>    data source.*/</pre><pre>    get: (item: ObjectItem) =&gt; ReactNode;</pre><pre>}</pre><p>This basically tells us, that there is one get function for our widget, which expects something called an ObjectItem in order to render a ReactNode</p><ul><li>“Items ”is our data source which we can access as a ListValue (a Mendix-defined type), if we right-click on “items” and click ‘Go To Type Definition’ we can see our documentation for this type. From this documentation I can see that I can access an array of ObjectItem, using the <em>.items</em> property</li></ul><p>We can then use the built-in function JS map to iterate through each element in the items list and use the ‘get’ function of the item to return the result.</p><ul><li>We then <strong>wrap our function</strong> in <strong>curly braces</strong> to show it is JavaScript and wrap it in a <strong>parent div</strong> in order to render each item</li><li>Lastly, we add a <strong>ternary expression</strong> to avoid calling the function in the event that there are no items in the list.</li></ul><h3>Testing</h3><p>To test our implementation we set up a test project in the ‘tests’ folder of our widget, just like we did in <a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff">Blog 1</a>.</p><p>We add an entity called <strong>Item </strong>with the string attribute <strong>Content</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*w5AqL7dtiQdHTU-5Hkhtww.png" /></figure><p>Then we add some microflows to <strong>create some $Items in the After Start Up Microflow.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8fNuISIhZApf5ZhfhlBPlg.png" /></figure><p>We can then build our widget from the terminal with npm run build .</p><p>When we return to our Mendix model and press F4, our widget is available to be placed on our homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-60b64rC6gZA0olWAS8AUA.png" /></figure><p>Here I’ve added a simple container with the class ‘<strong>card</strong>’ and a string displaying the content. And Voila! It renders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*QnM1vW2gNOQhPppEbfFJrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/0*72x68xmfATzJNaSU.jpg" /></figure><h3>Drag ‘N Drop</h3><p>Having a static list is a good start, but we need to be able to move those items around!</p><p>Let’s choose our react drag and drop library. We could build this ourselves (<a href="https://github.com/mendixlabs/app-services-components/tree/main/apps/web-widgets/drag-and-drop-widget">and some smart Mendix developers already did!</a>) but there is a <a href="https://flatlogic.com/blog/how-to-choose-the-best-react-drag-and-drop-top-15-free-libraries-to-set-up/">very broad selection of well-supported, highly used libraries</a>.</p><p>I’ve gone with <strong>react-beautiful-dnd</strong> as it has an <strong>easy-to-use</strong> API and is very <strong>feature-rich</strong>.</p><p>We then import our drag and drop library by navigating to our widget directory (./kanban) and running the command</p><p>npm i react-beautiful-dnd .</p><p>From reading the documentation there are three main areas we need for our widget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*WTbZWIGZYsyQya6d.gif" /><figcaption><a href="https://github.com/atlassian/react-beautiful-dnd">https://github.com/atlassian/react-beautiful-dnd</a></figcaption></figure><ul><li><a href="https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/api/drag-drop-context.md">&lt;DragDropContext /&gt;</a> - <em>Wraps the part of your application you want to have drag and drop enabled for</em></li><li><a href="https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/api/droppable.md">&lt;Droppable /&gt;</a> - <em>An area that can be dropped into.</em></li><li><a href="https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/api/draggable.md">&lt;Draggable /&gt;</a> - <em>What can be dragged around</em></li></ul><h4>Step 1 — Draggable</h4><p>So let’s start at the lowest level and convert our Items to be draggable.</p><p>First, let’s break our ItemList out into a separate function, but keep it within our component for ease of development for now (we can move it into a separate component later).</p><pre>export function Kanban({ widgetList, items }: KanbanContainerProps): ReactElement {</pre><pre>    const ItemList = (): ReactElement =&gt; {</pre><pre>        return (<br>             &lt;div&gt;<br>                   {items.items &amp;&amp; items.items.map(item =&gt; {<br>                        return widgetList.get(item);})}<br>             &lt;/div&gt;);</pre><pre>    }</pre><pre>    return (&lt;div&gt;&lt;ItemList /&gt;&lt;div&gt;)<br>}</pre><p>In order to make each list item draggable, we need to wrap the widget in a Draggable component, which<strong> expects a unique id</strong> for the draggable item — <strong>an index to order the items</strong>, and a child function to render the component.</p><p>Following the documentation from the react-beautiful-dnd library for the rest of the implementation, we end up with the following code.</p><pre>const ItemList = (): ReactElement =&gt; {<br>    return (<br>        &lt;div&gt;<br>            {items.items &amp;&amp;items.items.map((item, i) =&gt; {<br>                return (<br>                     &lt;Draggable <br>                          draggableId={item.id} <br>                          index={i} <br>                          key={item.id}<br>                     &gt;<br>                         {provided =&gt; (<br>                             &lt;div<br>                                 ref={provided.innerRef}<br>                                 {...provided.draggableProps<br>                                 {...provided.dragHandleProps}<br>                              &gt;<br>                                  {widgetList.get(item)}<br>                             &lt;/div&gt;)}<br>                     &lt;/Draggable&gt;);<br>               })}<br>         &lt;/div&gt;);<br>};</pre><p>What we have done here is wrap our widget component in a ‘draggable’ wrapper which allows us to pass down a reference and props.</p><p><em>References are a concept that we haven’t covered yet in these blogs and are a key part of React, they are essentially a way of accessing elements within your page, and in this instance are intended for keeping track of what is being dragged.</em></p><p><a href="https://reactjs.org/docs/refs-and-the-dom.html">Refs and the DOM - React</a></p><h4>Step 2— Droppable</h4><p>Now that we have our Draggable components we need to create the drag-drop canvas.</p><p>To do this we need to wrap our ItemList of Draggable components in a Droppable container using a pattern very similar to the one outlined above:</p><pre>&lt;Droppable droppableId=&quot;list&quot;&gt;<br>    {provided =&gt; (<br>        &lt;div ref={provided.innerRef} {...provided.droppableProps}<br>             &lt;ItemList /&gt;<br>        &lt;/div&gt;<br>    )}<br>&lt;/Droppable&gt;</pre><h4>Step 3— Context</h4><p>Lastly, we need to provide the drag-drop context in which the functionality exists:</p><pre>&lt;DragDropContext onDragEnd={onDragEnd}&gt;<br>    &lt;Droppable droppableId=&quot;list&quot;&gt;<br>        {provided =&gt; (<br>            &lt;div <br>                 ref={provided.innerRef} <br>                 {...provided.droppableProps}<br>             &gt;<br>                 &lt;ItemList /&gt;<br>             &lt;/div&gt;<br>         )}<br>    &lt;/Droppable&gt;<br>&lt;/DragDropContext&gt;</pre><p>The context expects a function to call once an item has been dragged. For now, let’s just log that the function has been called.</p><p>Our code currently should look something like this:</p><pre>export function Kanban({ widgetList, items }: KanbanContainerProps): ReactElement {<br>    const ItemList = (): ReactElement =&gt; {<br>        return (<br>            &lt;div&gt;<br>                {items.items &amp;&amp;<br>                    items.items.map((item, i) =&gt; {<br>                        return (<br>                            &lt;Draggable <br>                                draggableId={item.id} <br>                                index={i} <br>                                key={item.id}<br>                             &gt;<br>                                {provided =&gt; (<br>                                    &lt;div<br>                                        ref={provided.innerRef}<br>                                        {...provided.draggableProps}<br>                                       {...provided.dragHandleProps}<br>                                    &gt;<br>                                        {widgetList.get(item)}<br>                                    &lt;/div&gt;<br>                                )}<br>                            &lt;/Draggable&gt;<br>                        );<br>                    })}<br>            &lt;/div&gt;<br>        );<br>    };</pre><pre>function onDragEnd(result: DropResult): void {<br>        console.log(&quot;Dragged&quot;);<br>    }</pre><pre>return (<br>        &lt;DragDropContext onDragEnd={onDragEnd}&gt;<br>            &lt;Droppable droppableId=&quot;list&quot;&gt;<br>                {provided =&gt; (<br>                    &lt;div <br>                         ref={provided.innerRef}<br>                         {...provided.droppableProps}<br>                     &gt;<br>                        &lt;ItemList /&gt;<br>                    &lt;/div&gt;<br>                )}<br>            &lt;/Droppable&gt;<br>        &lt;/DragDropContext&gt;<br>    );<br>}</pre><p>If we run npm run build and rerun our Mendix app, we can now drag around our cards! Kind of…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWAv3YjJgF3GD0nItby1HA.gif" /></figure><p>We will revisit this problem later…the most important part is that we can drag our Items around.</p><h3>Multiple Columns</h3><p>So we can drag stuff up and down in one list, but what we really want to do is to be able to drag items between columns to determine the status.</p><p>We want our users of the widget to be able to specify how many columns they want.</p><p>To do this we can use <a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-property-types/#object">‘Objects’</a> in our Kanban.xml. We just need to wrap our existing properties in an object list like so:</p><pre>&lt;property key=&quot;myObject&quot; type=&quot;object&quot; isList=&quot;true&quot;&gt;<br>    &lt;caption&gt;Sections&lt;/caption&gt;<br>    &lt;description/&gt;<br>    &lt;properties&gt;<br>        &lt;propertyGroup caption=&quot;Object list group&quot;&gt;<br>            &lt;property key=&quot;sectionName&quot; type=&quot;string&quot; required=&quot;true&quot;&gt;<br>                &lt;caption&gt;Name&lt;/caption&gt;<br>                &lt;description&gt;Name&lt;/description&gt;<br>            &lt;/property&gt;<br>            &lt;property key=&quot;sectionItems&quot; type=&quot;datasource&quot; isList=&quot;true&quot; required=&quot;true&quot;&gt;<br>                &lt;caption&gt;Section Items&lt;/caption&gt;<br>                &lt;description&gt;List of items&lt;/description&gt;<br>            &lt;/property&gt;<br>            &lt;property key=&quot;widgetList&quot; type=&quot;widgets&quot; required=&quot;true&quot; dataSource=&quot;sectionItems&quot;&gt;<br>                &lt;caption&gt;Content&lt;/caption&gt;<br>                &lt;description&gt;Widgets using data source&lt;/description&gt;<br>            &lt;/property&gt;<br>        &lt;/propertyGroup&gt;<br>    &lt;/properties&gt;<br>&lt;/property&gt;</pre><p>The keen-eyed amongst you will also notice that I added a name to allow us to keep track of our columns.</p><p>If you open Mendix we can check out our lovely new interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MclU_rrUsfg874bvE29I0g.gif" /></figure><p>Cool, but now we have to render our columns, let’s head back to our widget…</p><p>This is actually quite simple.</p><p>First, let’s update our JSX to render a column for each object:</p><pre>&lt;DragDropContext onDragEnd={onDragEndObj}&gt;<br>    {myObject.map((obj, i) =&gt; {<br>        return (<br>            &lt;Droppable droppableId=&quot;list&quot;&gt;<br>                  {provided =&gt; (<br>                      &lt;div ref={provided.innerRef}<br>                               {...provided.droppableProps}<br>                       &gt;<br>                          &lt;ItemList /&gt;<br>                      &lt;/div&gt;<br>                   )}<br>            &lt;/Droppable&gt;<br>          );<br>    })}<br>&lt;/DragDropContext&gt;</pre><p>We should also make the <strong>droppableId </strong>unique and pass some props to our ItemList.</p><pre>&lt;DragDropContext onDragEnd={onDragEndObj}&gt;<br>    {myObject.map((obj, i) =&gt; {<br>        return (<br>            &lt;Droppable key={i} droppableId={i.toString()}&gt;<br>                  {provided =&gt; (<br>                      &lt;div ref={provided.innerRef}<br>                               {...provided.droppableProps}<br>                       &gt;<br>                          &lt;ItemList <br>                             items={obj.sectionItems} <br>                             widgetList={obj.widgetList}<br>                           /&gt;<br>                      &lt;/div&gt;<br>                   )}<br>            &lt;/Droppable&gt;<br>          );<br>    })}<br>&lt;/DragDropContext&gt;</pre><p>This means we also need to update our item list to accept the new props, and whilst we are here we might as well refactor it into something a little easier to read — I end up with two new files in my component folder:</p><p>Draggable.TSX</p><pre>import { ReactElement, createElement } from &quot;react&quot;;<br>import { Draggable } from &quot;react-beautiful-dnd&quot;;<br>import { ObjectItem, ListWidgetValue } from &quot;mendix&quot;;</pre><pre>export interface DraggableProps {<br>    item: ObjectItem;<br>    i: number;<br>    widgetList: ListWidgetValue;<br>}</pre><pre>export function DraggableItem({ item, i, widgetList }: DraggableProps): ReactElement {<br>    return (<br>        &lt;Draggable draggableId={item.id} index={i} key={item.id}&gt;<br>            {provided =&gt; (<br>                &lt;div ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}&gt;<br>                    {widgetList.get(item)}<br>                &lt;/div&gt;<br>            )}<br>        &lt;/Draggable&gt;<br>    );<br>}</pre><p>And ItemList.TSX</p><pre>import { ReactElement, createElement } from &quot;react&quot;;<br>import { ListValue, ListWidgetValue } from &quot;mendix&quot;;<br>import { DraggableItem } from &quot;./Draggable&quot;;</pre><pre>export interface ItemListProps {<br>    items: ListValue;<br>    widgetList: ListWidgetValue;<br>}</pre><pre>export const ItemList = ({ items, widgetList }: ItemListProps): ReactElement =&gt; {<br>    return (<br>        items &amp;&amp; (<br>            &lt;div&gt;<br>                {items.items &amp;&amp;<br>                    items.items.map((item, i) =&gt; {<br>                        return &lt;DraggableItem item={item} key={i} i={i} widgetList={widgetList} /&gt;;<br>                    })}<br>            &lt;/div&gt;<br>        )<br>    );<br>};</pre><h4>Styling</h4><p>We need to add some style to our Kanban board, to turn it from an ugly duckling into a beautiful swan.</p><p>We will do this in two main ways:</p><ul><li>Making use of CSS classes and <a href="https://reactjs.org/docs/dom-elements.html">the ‘className’ prop</a> every dom element has</li><li>Leveraging in-line styles to make use of properties calculated in our code (i.e. column width)</li></ul><p>First, let’s update our Kanban.css file to</p><pre>.kanban-col {<br>    margin: 15px;<br>    padding: 10px;<br>    background: #9bedff;<br>    border-radius: 15px;<br>}</pre><pre>.kanban-col h6 {<br>    text-align: center;<br>}</pre><p>We can then use a few additional dom elements, our classes, and styles and end up with:</p><pre>import { ItemList } from &quot;./components/ItemList&quot;;<br>import { KanbanContainerProps } from &quot;../typings/KanbanProps&quot;;</pre><pre>import &quot;./ui/Kanban.css&quot;;</pre><pre>export function Kanban({ myObject }: KanbanContainerProps): ReactElement {</pre><pre>function onDragEnd(result: DropResult): void {<br>        console.log(&quot;dragged&quot;);<br>    }</pre><pre>return (<br>    &lt;div style={{ display: &quot;flex&quot; }}&gt;<br>        &lt;DragDropContext onDragEnd={onDragEnd}&gt;<br>            {myObject.map((obj, i) =&gt; {<br>                return (<br>                    &lt;Droppable key={i} droppableId={i.toString()}&gt;<br>                        {provided =&gt; (<br>                            &lt;div <br>                                className=&quot;kanban-col&quot; <br>                                style={{width:`${100/<br>                                        myObject.length}%` }}<br>                                ref={provided.innerRef} <br>                                  {...provided.droppableProps} <br>                            &gt;<br>                                &lt;h6&gt;{obj.sectionName}&lt;/h6&gt;<br>                                    &lt;ItemList <br>                                       items={obj.sectionItems} <br>                                       widgetList={obj.widgetList} <br>                                     /&gt;<br>                                     {provided.placeholder}<br>                            &lt;/div&gt;<br>                        )}<br>                    &lt;/Droppable&gt;<br>                );<br>            })}<br>        &lt;/DragDropContext&gt;<br>    &lt;/div&gt;<br>    );<br>}</pre><p>Hold on…..what is that? ${100/myObject.length}%</p><p>This is a<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals"> <strong>template literal</strong></a> that allows you to quickly build strings in JS, by writing strings in `` and wrapping expressions in ${}.</p><p>But back to the widget…we now have user-defined columns, with Items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vH2RgSYQP1QdWeSZh4BaLA.png" /></figure><h3>Drag N Drop Action</h3><p>Now we want our Drag and Drop to actually do something…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*vNsfnw9DfHV-BwW_.jpg" /></figure><p>To do this we are going to make use of the Pluggable Widget action API in combination with a data source.</p><p>So, first things first let’s add two new properties to our object in our Kanban.xml</p><pre>&lt;property key=&quot;action&quot; type=&quot;action&quot; dataSource=&quot;allItems&quot; required=&quot;true&quot;&gt;<br>      &lt;caption&gt;Section Items&lt;/caption&gt;<br>      &lt;description&gt;List of items&lt;/description&gt;<br>&lt;/property&gt;<br>&lt;property key=&quot;allItems&quot; type=&quot;datasource&quot; isList=&quot;true&quot; required=&quot;true&quot;&gt;<br>      &lt;caption&gt;All Items&lt;/caption&gt;<br>      &lt;description&gt;List of items&lt;/description&gt;<br>&lt;/property&gt;</pre><p>By linking our action to a data source we can execute the action with a parameter from Mendix. This will allow us to change attributes on our items.</p><p>Now we can update our “<strong>onDragEnd ”</strong>function to execute the action.</p><p>By reading the documentation for react-beautiful-dnd we can see that onDragEnd receives a result object which allows us to access the draggableId and droppableID. We can use these to work out what Item is being dragged and where it is being dragged to (and therefore what action we need to call).</p><p>The first thing to do is destructure our result and find the correct object:</p><pre>const { source, destination } = result;<br>const destObj = myObject[parseInt(destination.droppableId, 10)];</pre><p>Here we are parsing the droppableId (which we set to the index of the objects), and using it to retrieve the object from the <strong>myObject </strong>array.</p><p>Once we have the correct object we can get a representation of the item being dragged, by finding it in the list of <strong>allItems</strong>.</p><pre>const destObjItem = destObj.allItems.items!.find(item =&gt; {<br>            return item.id === result.draggableId;<br>        });</pre><p><em>Note we need to specify allItems for every object because actions can only be called on items that belong to the same object.</em></p><p>We can then execute an action on the object :</p><pre>const actionOnObj = destObj.action!.get(destObjItem!);<br>        if (actionOnObj.canExecute) {<br>            actionOnObj.execute();<br>        }</pre><p>We splash in a few checks to make sure the item was dragged to a list, and our final function should look like this:</p><pre>function onDragEnd(result: DropResult): void {<br>        const { source, destination } = result;<br>        if (!destination) {<br>            return;<br>        }<br>        const destObj = myObject[parseInt(destination.droppableId, <br>        10)];<br>        const destObjItem = destObj.allItems.items!.find(item =&gt; {<br>            return item.id === result.draggableId;<br>        });<br>        const actionOnObj = destObj.action!.get(destObjItem!);<br>        if (actionOnObj.canExecute) {<br>            actionOnObj.execute();<br>        }<br>    }</pre><p>So this has set us up nicely to have a working drag-and-drop Kanban board, we just need to do a couple of things in Studio Pro. First, let’s add a Status attribute with our various statuses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*V59Bw7TTY45k0s2ENwdhDQ.png" /></figure><p>Then let’s add a nanoflow for each status we want to set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*SyWXEbjt-GajLoqXIu-vCw.png" /></figure><p>Now let’s configure each of our sections by setting the items to be all the items with the relevant status, and the correct on-drop action, and add a link to all of the items in the database for AllItems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*jbnHZ7cIVsF2sQo2l7ZinQ.png" /></figure><p>And we have drag and drop!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ybx6Tb6ItByAuRajoary2g.gif" /></figure><h3>Sorting</h3><p>We are almost there, we just have one more thing to do which is to introduce sorting. For this, we are going to use a useful pattern for getting data out of Pluggable Widgets.</p><blockquote><em>Ideally, we would manage this entirely using values on the ‘Item’ but there is currently a limitation with the Pluggable Widget API, where attributes for objects that are part of lists cannot be directly changed. This limitation is on the roadmap to be removed. In the meantime we can take the following approach:</em></blockquote><p>Let’s start by storing the sort order in the Mendix entity: Item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*fEES0FbdZgFGcMu3dFLG4A.png" /></figure><p>Whilst we are at it, I will update my ASU to repopulate the database every time with Items with a Sort value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsbJ9KqWg_sNyNHFFbSWuA.png" /></figure><p>So back to our widget, let’s update the Kanban.xml to have a new ‘Sorting’ property group, which we can use to store the previous and updated sort index when we drag an item.</p><pre>&lt;propertyGroup caption=&quot;Sorting&quot;&gt;<br>&lt;property key=&quot;newSort&quot; type=&quot;attribute&quot; required=&quot;true&quot;&gt;<br>    &lt;caption&gt;New Sort&lt;/caption&gt;<br>    &lt;description&gt;Sort value storage&lt;/description&gt;<br>    &lt;attributeTypes&gt;<br>            &lt;attributeType name=&quot;Integer&quot;/&gt;<br>    &lt;/attributeTypes&gt;<br>&lt;/property&gt;<br>&lt;property key=&quot;prevSort&quot; type=&quot;attribute&quot; required=&quot;true&quot;&gt;<br>    &lt;caption&gt;Previous Sort&lt;/caption&gt;<br>    &lt;description&gt;Sort Value Storage&lt;/description&gt;<br>    &lt;attributeTypes&gt;<br>            &lt;attributeType name=&quot;Integer&quot;/&gt;<br>    &lt;/attributeTypes&gt;                <br>&lt;/property&gt;<br>&lt;/propertyGroup&gt;</pre><p>We can then update our onDrag function to pass out these properties to our Mendix model:</p><pre>function onDragEnd(result: DropResult): void {<br>        const { source, destination } = result;<br>        if (!destination) {<br>            return;<br>        }<br>        const destObj = myObject[parseInt(destination.droppableId, <br>        10)];<br>        const destObjItem = destObj.allItems.items!.find(item =&gt; {<br>            return item.id === result.draggableId;<br>        });</pre><pre>        prevSort.setValue(new Big (source.index))<br>        newSort.setValue(new Big (destination.index))</pre><pre>        const actionOnObj = destObj.action!.get(destObjItem!);<br>        if (actionOnObj.canExecute) {<br>            actionOnObj.execute();<br>        }<br>    }</pre><p>If we return to our Mendix model we can use these values to build out our sorting logic.</p><p>Let’s set up an Entity to hold our previous and new sort values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*XWId4dK7URIrz_myn3fkLA.png" /></figure><p>Then let’s wrap our widget in a data view that provides this entity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*88LpOAKufAGxlnjgmaHPqQ.png" /></figure><p>We can then configure our widget to pass the sort values into the entity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*b_OFrRShj53cyA8jqJRasQ.png" /></figure><p>Given we have wrapped our widget in the data view, we can now add our KanbanHelper as a parameter to our actions which are executed onDrag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*Syh6l6yyd4MsqsDxjs_4IQ.png" /></figure><p>We do 3 main things in each of our onDrag nanoflows:</p><ul><li><strong>Store </strong>the <strong>starting status</strong> of the Item (this determines whether the Item has changed column, for sorting calculations)</li><li><strong>Update the Item</strong> to the new Status and the <strong>newSort </strong>value</li><li>Implement <strong>sorting logic</strong> to the rest of the Items</li></ul><p>For the Sorting logic we can build it out in a Sub nanoflow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-0qbJv1HzGMpWkxnpxD0Q.png" /></figure><blockquote><em>I won’t go into the details of how this was put together here, but </em><strong><em>the nanoflow can be found in the resources section of the </em></strong><a href="https://github.com/joe-robertson-mx/kanban-widget/tree/master/resources"><strong><em>Github repo</em></strong></a><strong><em>.</em></strong></blockquote><p>Then when we run our application and test it one last time…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cLkWqd5kOrS6snVCXhCjog.gif" /></figure><h3>Summary</h3><p>Now we have an all-singing, all-dancing Kanban board! We used the react-beautiful-dnd library, the composable nature of Mendix widgets, and a few simple(ish) nanoflows to build a fully functional, user-definable Kanban board.</p><p>The end state of this widget can be found here:</p><p><a href="https://github.com/joe-robertson-mx/kanban-widget">GitHub - joe-robertson-mx/kanban-widget</a></p><p>If you were able to implement this Kanban board and want to show off what you built, share it in the comments below.</p><p><strong>Up next</strong> we are going to take a look at implementing <strong>maps</strong> in our Pluggable Widgets, and in the process explore how to use complex external libraries, and include custom files in our build.</p><h4>Read more</h4><ul><li><a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets/">Pluggable Widgets API</a></li><li><a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-property-types/">Property Types</a></li><li><a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-client-apis/">Client APIs Available to Pluggable Widgets</a></li></ul><p><em>From the Publisher -</em></p><p><em>If you enjoyed this article you can find more like it on our </em><a href="https://medium.com/mendix"><em>Medium page</em></a><em>. For great videos and live sessions, you can go to </em><a href="https://www.mendix.com/live/"><em>MxLive</em></a><em> or our community </em><a href="https://www.youtube.com/c/MendixCommunity/community"><em>Youtube pag</em></a><em>e.</em></p><p><em>For the makers looking to get started, you can sign up for a </em><a href="https://signup.mendix.com/link/signup/?source=direct"><em>free account</em></a><em>, and get instant access to learning with our </em><a href="https://academy.mendix.com/link/home"><em>Academy</em></a><em>.</em></p><p><em>Interested in getting more involved with our community? Join us in our </em><a href="https://join.slack.com/t/mendixcommunity/shared_invite/zt-hwhwkcxu-~59ywyjqHlUHXmrw5heqpQ"><em>Slack community channel</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2598aa71444d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Widgets in Mendix with React Part 2 — Timer]]></title>
            <link>https://medium.com/mendix/build-widgets-in-mendix-with-react-part-2-timer-b65c720b34e3?source=rss-70162395082c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b65c720b34e3</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[mendix]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[low-code]]></category>
            <dc:creator><![CDATA[Joe Robertson]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 09:56:08 GMT</pubDate>
            <atom:updated>2022-07-19T09:56:08.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Widgets in Mendix with React Part 2 — Timer</h3><figure><img alt="Build Widgets in Mendix with React Part 2 — Timer (Banner Image)" src="https://cdn-images-1.medium.com/max/1024/1*7LvQku6jNBZlA0RtCyMECQ.png" /><figcaption>Build Widgets in Mendix with React Part 2 — Timer</figcaption></figure><h3>The Mendix Platform enables Developers to extend their apps using React, through the Pluggable Widgets framework. This framework allows developers to leverage powerful libraries and extend the UI by building React components that can then be used in the Mendix Studio Pro.</h3><p>In this blog, we are going to <strong>learn about Typescript</strong> and I am going to show you how to <strong>use attributes from your Mendix model in your widget</strong>, how to <strong>leverage the browser API</strong> and we will even touch on <strong>conditional rendering in React</strong>.</p><p>This is the second blog in a multipart series, blog 1 can be found here:</p><p><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff">Build widgets in Mendix with React — Part 1 — Colour Counter</a></p><h3>When to use Pluggable Widgets</h3><p>There are a few litmus checks I use when deciding whether to create a new Pluggable Widget:</p><ul><li>Does it need a UI component? — if you need to use Javascript but there is no UI component, a <a href="https://docs.mendix.com/howto/extensibility/write-javascript-actions">JS action</a> might be better suited to your use case</li><li>Is it available in the <a href="https://marketplace.mendix.com/">Mendix Marketplace</a>?</li><li>Does it use the Browser API or an NPM package?</li></ul><h3>What we are building</h3><p>This time we’re going to be building <strong>a timer for refreshing a page at a fixed interval</strong>. “Why don’t I just do that with JavaScript?” I hear you ask. That’s because we’re also going to have a visual component that <strong>tells you how long it will be until the next refresh</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*pweD_bj34Aze0x3H.jpg" /></figure><p>This was based on a real use case, where a dashboard was displayed on a shop floor and needed to be updated every 30 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVPpMt1iVgIlgegQeh1d2A.gif" /></figure><h3>Getting Started</h3><p>For this widget we will be using <a href="https://www.typescriptlang.org/"><strong>Typescript</strong></a>, the strongly typed wrapper around Javascript, as although it initially makes code slightly harder to write, the <strong>inbuilt linting</strong> and<strong> extensive documentation</strong> are very useful when creating Pluggable Widgets. These elements of Typescript also make it much <strong>easier to collaborate in large teams</strong> and <strong>integrate with complex APIs</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1we3_zYN7rxJ6j-uozuCGQ.png" /></figure><p>We begin by scaffolding our widget, as in <a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff">Blog 1</a> but this time select Typescript as our programming language.</p><blockquote><strong>A quick note on functional components vs class components in React</strong></blockquote><blockquote><strong>Throughout these blogs we will use functional components</strong>, however, you may also<strong> come across React written using class components</strong>. This is because, <strong>until the </strong><a href="https://reactjs.org/docs/hooks-intro.html"><strong>release of hooks</strong></a><strong> in React 16.8</strong>, <strong>class components were the only way to manage state</strong>, and functional components were mainly a presentation layer for the frontend. Now the React community is <strong>moving towards using functional components</strong> as they are <strong>syntactically simpler</strong> and more <strong>lightweight</strong>.</blockquote><p><a href="https://medium.com/geekculture/is-there-any-reason-to-still-use-react-class-components-9b6a1e6aa9ef">Is There Any Reason to Still Use React Class Components?</a></p><h3>Dev time</h3><p><em>For an explanation of the Pluggable Widget folder structure and how to set up your development environment see my </em><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff"><em>previous blog</em></a><em>.</em></p><p><strong>One thing first</strong></p><p>To speed up the development process we are going to remove our editor preview file. This file creates the preview for our widget in Design mode in Studio Pro, or Studio, and we’re not worried about that for this guide. It would just be one more thing to update. So let’s go ahead and remove the file: <strong>Timer.editorPreview.tsx.</strong></p><h4><strong>The Brief</strong></h4><p>We can break down what we are trying to achieve with our widget into 3 main sections:</p><ul><li><strong>Step 1: </strong>Set the timer to an initial value defined in Mendix</li><li><strong>Step 2: </strong>Decrease the timer in 1s intervals</li><li><strong>Step 3: </strong>Execute an action</li></ul><h3><strong>Step 1</strong></h3><h4><strong>Set the timer to an initial value defined in Mendix</strong></h4><p>Let’s start by creating the interface between our Mendix model and the widget. We could use a simple Integer but by using an attribute we have more flexibility to dynamically change the timer value at runtime.</p><p>We update our Timer.xml to contain:</p><pre>&lt;property key=&quot;timeAtt&quot; type=&quot;attribute&quot; required=&quot;true<br>    &lt;caption&gt;Time attribute&lt;/caption&gt;<br>    &lt;description&gt;The number of seconds on refresh&lt;/description&gt;<br>    &lt;attributeTypes&gt;<br>         &lt;attributeType name=&quot;Integer&quot;/&gt;<br>    &lt;/attributeTypes&gt;<br>&lt;/property&gt;</pre><p>While we are at it we should also rename the child component to TimeText, and the interface to TimeTextProps. When we save the file and run the command :npm run build, we will see errors, this is good!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/0*Gf8OXusIcYEz6eDU.jpg" /></figure><p>It shows that the sampleText property has been replaced by the timeAtt. Let’s update our Timer file with timeAtt in place of the default sampleText.</p><p>If we highlight the timeAtt in our Timer.tsx file, we can see that it is of type EditableValue&lt;Big&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*FEnLSWKOawB3xHWc.jpg" /></figure><p><a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-client-apis/#editable-value">EditableValue</a> is the <a href="https://www.typescriptlang.org/docs/handbook/2/generics.html">generic type</a> that Mendix uses to represent all attributes, and it allows us to read and write the values within the Mendix model.</p><p>The ‘<strong>&lt;&gt;’</strong> part, is determined by the attribute type. For integer or decimal attributes we use the Big.js library. This is to ensure that the numbers used in your application are not constrained by default JavaScript number limitations.</p><h4><strong>Using State</strong></h4><p>So far we have created a link between Mendix and the widget, through the props of the container component. Now we need to pass down an easily readable value to our TimeText component, to display on the page. To do this we will process our EditableValue&lt;Big&gt; and store a simple integer in the <strong>state</strong> of our container component.</p><p>We use <strong>state</strong> here rather than <strong>props</strong> because we are going to change our timer value over time and <a href="https://www.freecodecamp.org/news/how-to-update-a-components-prop-in-react-js-oh-yes-it-s-possible-f9d26f1c4c6d"><strong>props should never be directly changed</strong></a>:</p><p>Let’s start by importing <strong>useState</strong> from ‘React’ and initialising a <strong>state</strong> called <strong>time</strong> with the following:</p><p>const [time, setTime] = useState&lt;number&gt;();</p><p>This gives us a state variable (<strong>time</strong>) and a setState function to change that state(like props, the state must never be directly mutated, and instead can be changed via this function).</p><h4><strong>Using useEffect</strong></h4><p>Next, we need to <strong>pass our attribute value into our state</strong>. The easiest way to do this is by passing a value into our useState:</p><p>const [time, setTime] = useState&lt;number&gt;(timeAtt.value.toNumber());</p><p>But because our value could be empty, we are not going to do that. Instead, we will use another central concept of React ‘useEffect’.</p><blockquote>So what is useEffect? Essentially it executes a function after every render. We can use it to set our time like this:</blockquote><pre>export function Timer({timeAtt}: TimerContainerProps):ReactElement {<br>const [time, setTime] = useState&lt;number&gt;();</pre><pre>    useEffect(() =&gt; {<br>         if (timeAtt.value) {<br>             setTime(timeAtt.value.toNumber());<br>         }<br>     }, []);<br>    <br>    return &lt;TimeText sampleText={sampleText ? sampleText:&quot;World&quot;}/&gt;;<br>}</pre><p>We can then pass this down to the child component, TimeText by updating the props to accept our new time state:</p><pre>return &lt;TimeText value={time}/&gt;;</pre><p>And that’s our Timer component updated!</p><p>Now we just need to make a few minor changes to our TimeText component to <strong>accept the new props</strong>. Because we are using Typescript we have an <strong>interface</strong> for our component. This defines how any code using this component can interact with it. So, let’s update our display component to:</p><pre>export interface TimeTextProps {<br>    value: number | undefined;<br>}</pre><pre>export function TimeText({ value }: TimeTextProps): ReactElement {<br>    return &lt;div&gt;{value} seconds&lt;/div&gt;;<br>}</pre><blockquote><em>Interfaces might seem unnecessary here, and for a small widget like this they probably are, but for </em><strong><em>when projects get larger they are incredibly useful</em></strong><em>.</em></blockquote><p>To test, we can open Mendix Studio Pro and press F4 to synchronize the updates to or widget. We then need to set up our page so that a number attribute can be passed to the timer widget.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vhvDbOjDHxTsirp3.jpg" /></figure><p>We <strong>click Run</strong> and…. our page just says ‘seconds’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*g5zkxs3DZFZkgIDz" /></figure><p>Don’t worry <strong>this is expected due to how Mendix loads attributes</strong>. The <strong>attribute values are loaded asynchronously</strong>, this is what makes the Mendix front end so fast but means that we need an extra couple of lines of code to get our widget working.</p><h4><strong>Using useEffect, but correctly</strong></h4><p>We left the second parameter of useEffect empty, <strong>this means the useEffect function runs once when the component first mounts</strong>, at which point <strong>our attribute value is not ready</strong>.</p><p><em>If you want to check this put an </em><em>console.log(`Render ${timeAtt.value}`) above the if statement and check the browser console (‘Ctrl + Shift + i’ from the browser).</em></p><p>So instead we want the useEffect function to run whenever the timeAtt is updated, to do this we simply add the timeAtt to the second parameter to useEffect.</p><pre>export function Timer({timeAtt}: TimerContainerProps):ReactElement {<br>const [time, setTime] = useState&lt;number&gt;();</pre><pre>useEffect(() =&gt; {<br>         if (timeAtt.value) {<br>             setTime(timeAtt.value.toNumber());<br>         }<br>     }, [timeAtt]);<br>    <br>    return &lt;TimeText value={time}/&gt;;<br>}</pre><p>If you rerun the application from Mendix you will see your timer value appear, and if you check the console log you will see that the widget rendered twice, once when the value was undefined and once with the number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*H5FhnWUL2QLN-AycdlYh0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*l60wNyYxrxQ_tTb2KYDXpA.png" /></figure><p>SUCCESS! That’s part 1 done!</p><h3><strong>Step 2</strong></h3><h4><strong>Decrease the timer in 1s intervals</strong></h4><p>Cool. So we have a number displayed on a screen but there’s not much use in that, <strong>we want our timer to count down</strong>. To do that we are going to <strong>use the browser Javascript API,</strong> specifically <a href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout">window.setTimeout()</a>, which <strong>executes a function after a fixed amount of time</strong>.</p><p>By combining this with our old friend useEffect, we can create a countdown. If we make our useEffect function dependent on our time state and wait 1 second to change our <strong>time </strong>state by 1 second, we essentially create a loop.</p><pre>export function Timer({timeAtt}: TimerContainerProps):ReactElement {<br>const [time, setTime] = useState&lt;number&gt;();</pre><pre>useEffect(() =&gt; {<br>         if (timeAtt.value) {<br>             setTime(timeAtt.value.toNumber());<br>         }<br>     }, [timeAtt]);</pre><pre>useEffect(() =&gt; {<br>        if (time !== undefined) {<br>             window.setTimeout(() =&gt; setTime(time - 1), 1000);<br>        }<br>    }, [time]);<br>    <br>    return &lt;TimeText value={time}/&gt;;<br>}</pre><p>However this count will keep going forever, so we need to add one more condition to get it to stop.</p><pre>useEffect(() =&gt; {<br>        if (time !== undefined) {<br>            if (time &gt; 0) {<br>                window.setTimeout(() =&gt; setTime(time - 1), 1000);<br>            }<br>        }<br>    }, [time]);</pre><p>If we reload our widget we can see that we have our countdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2gucJEs6lOfX5JGm.gif" /></figure><blockquote><em>A reminder that if you are using </em><em>npm run start and watching for changes on your widget </em><strong><em>you need to clear cache and refresh</em></strong><em> (in Chrome open browser tools and right click the refresh button)</em></blockquote><h3><strong>Step 3</strong></h3><h4><strong>Execute an action</strong></h4><p>We now need something to happen when the countdown hits 0!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*tH_WI7UTPXR9QTGp.gif" /></figure><p>Luckily Mendix provides a very easy-to-use API to integrate with the Model and execute an action. First, we update the Timer.xml to contain:</p><pre>&lt;property key=&quot;action&quot; type=&quot;action&quot; required=&quot;true&quot;&gt;<br> &lt;caption&gt;Action&lt;/caption&gt;<br>      &lt;description&gt;Action to trigger when the time elapses&lt;/description&gt;<br>&lt;/property&gt;</pre><p>We can then add a function to execute the action on our Timer.tsx, and update our useEffect function to execute the action at 0.</p><p>Our final Timer.tsx should look like this:</p><pre>export function Timer({ timeAtt, action }: TimerContainerProps): ReactElement {<br>    const [time, setTime] = useState&lt;number&gt;();</pre><pre>useEffect(() =&gt; {<br>        if (time !== undefined) {<br>            if (time &gt; 0) {<br>                window.setTimeout(() =&gt; setTime(time - 1), 1000);<br>            } else {<br>                execAction();<br>            }<br>        }<br>    }, [time]);</pre><pre>useEffect(() =&gt; {<br>        if (timeAtt.value) {<br>            setTime(timeAtt.value.toNumber());<br>        }<br>    }, [timeAtt]);</pre><pre>const execAction = () =&gt; {<br>        if (action &amp;&amp; action.canExecute) {<br>            action.execute();<br>        }<br>    };</pre><pre>return &lt;TimeText value={time} /&gt;;<br>}</pre><p>We can test this new code in our Mendix app by pressing F4 and choosing an action to be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*MCQySl6B2RIzNb7Y8qpxYQ.png" /></figure><p>By choosing to call a microflow that refreshes the page, we get our repeating timer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*zPnWZ38CmHFMDsTT.jpeg" /></figure><h4><strong>One last thing</strong></h4><p>When our component first loads there was a brief period where the time value passed to the TimeText component is undefined. This is not a major problem, as it just leads to the widget rendering ‘ seconds’, but it is best practice to give some indication that the value is loading.</p><p>To do that we will use a common pattern in React for conditional rendering.</p><p>We can use an if statement to check whether the value is not yet defined and display loading like so:</p><pre>export function TimeText({ value }: TimeTextProps): ReactElement {<br> if (value === undefined) {<br>  return &lt;div&gt;Loading&lt;/div&gt;;<br> } else {<br>  return &lt;div&gt;{value}&lt;/div&gt;;<br> }<br>}</pre><p>But this is very wordy. <strong>We can use </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator"><strong>ternary operators from ES6</strong></a> to shorten this to:</p><pre>export function TimeText({ value }: TimeTextProps): ReactElement {<br>    return value ? &lt;div&gt;{value} seconds&lt;/div&gt; : &lt;div&gt;Loading&lt;/div&gt;;}</pre><p>And VOILA!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVPpMt1iVgIlgegQeh1d2A.gif" /></figure><h3><strong>Summary</strong></h3><p>Congratulations, you built a Pluggable Widget!</p><p>In this build we covered the Pluggable Widget API, how to get data from your Mendix model and change it; covered using Typescript to better understand how to integrate with our Mendix app, revisited key React concepts, and learnt how to execute actions from your Mendix model in a widget.</p><p>The end state of this widget can be found here:</p><p><a href="https://github.com/joe-robertson-mx/timer">GitHub - joe-robertson-mx/timer</a></p><p>Up next we will build a Kanban Board using Mendix and Pluggable Widgets to learn more about how widgets can be combined to create slick end-user experiences, and how to make changes that persist in your Mendix database.</p><p>If you have any cool widgets you have built and would like to share, challenges you are running into in development or have things you would like to see built as part of this series, please <strong>drop a comment below</strong>!</p><h4>Read more</h4><ul><li><a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets/">Pluggable Widgets API</a></li><li><a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets/#widget-definition">Pluggable Widgets API</a></li><li><a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-property-types/">Property Types</a></li><li><a href="https://docs.mendix.com/apidocs-mxsdk/apidocs/pluggable-widgets-client-apis/">Client APIs Available to Pluggable Widgets</a></li></ul><p><em>From the Publisher -</em></p><p><em>If you enjoyed this article you can find more like it on our </em><a href="https://medium.com/mendix"><em>Medium page</em></a><em>. For great videos and live sessions, you can go to </em><a href="https://www.mendix.com/live/"><em>MxLive</em></a><em> or our community </em><a href="https://www.youtube.com/c/MendixCommunity/community"><em>Youtube pag</em></a><em>e.</em></p><p><em>For the makers looking to get started, you can sign up for a </em><a href="https://signup.mendix.com/link/signup/?source=direct"><em>free account</em></a><em>, and get instant access to learning with our </em><a href="https://academy.mendix.com/link/home"><em>Academy</em></a><em>.</em></p><p><em>Interested in getting more involved with our community? Join us in our </em><a href="https://join.slack.com/t/mendixcommunity/shared_invite/zt-hwhwkcxu-~59ywyjqHlUHXmrw5heqpQ"><em>Slack community channel</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b65c720b34e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-2-timer-b65c720b34e3">Build Widgets in Mendix with React Part 2 — Timer</a> was originally published in <a href="https://medium.com/mendix">Mendix Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build widgets in Mendix with React — Part 1 — Colour Counter]]></title>
            <link>https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff?source=rss-70162395082c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1e400c3cdff</guid>
            <category><![CDATA[mendix]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[how-to]]></category>
            <dc:creator><![CDATA[Joe Robertson]]></dc:creator>
            <pubDate>Tue, 21 Jun 2022 10:46:57 GMT</pubDate>
            <atom:updated>2022-06-23T10:36:25.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build widgets in Mendix with React — Part 1 — Colour Counter</h3><figure><img alt="Build widgets in Mendix with React — Part 1 — Color Counter (Banner Image)" src="https://cdn-images-1.medium.com/max/1024/1*uLAjaHAcMEKQD83Glnq7fA.png" /><figcaption>Build widgets in Mendix with React — Part 1 — Color Counter</figcaption></figure><h3>Mendix is a low code platform that lets makers deliver value faster and build applications easily. With Mendix the frontend can be customized using React and the Pluggable Widget framework.</h3><p>This blog is the first in a series of build-along widgets to get familiar with building your own Pluggable Widgets for Mendix. The blogs will cover increasingly sophisticated concepts and will cover a range of use cases including getting familiar with Typescript and the Pluggable widgets API, running Machine Learning models in your browser, and building a basic WebAssembly game.</p><h3>Where to begin</h3><p>If you haven’t already you should check out the worked example to create your first Pluggable Widget:</p><ul><li><a href="https://docs.mendix.com/howto/extensibility/create-a-pluggable-widget-one/">Build a Pluggable Web Widget: Part 1</a></li><li><a href="https://docs.mendix.com/howto/extensibility/create-a-pluggable-widget-two/">Build a Pluggable Web Widget: Part 2 (Advanced)</a></li></ul><p>Pluggable widgets use the React Javascript framework, we will touch on some React concepts in this series, but this is by no means a comprehensive introduction to React. so if you need an introduction or a refresher, I highly recommend the following course (you may even spot the inspiration for this widget).</p><p><a href="https://scrimba.com/learn/learnreact">React Tutorial: Learn React JS - Free 11-Hour Course</a></p><h3>Purpose of this blog</h3><p>In this blog we will cover:</p><ul><li>Pluggable widget project structure</li><li>Testing setup and development</li><li>React Concepts Introduction</li><li>Leveraging external Libraries</li></ul><h3>What we are building</h3><p>We are going to build a counter that can be increased or decreased with the click of a button, with a random color change on click.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*cd4KoGdRJbVdnEr0.gif" /></figure><p>The end state of the project can be found here:</p><p><a href="https://github.com/joe-robertson-mx/colourCount">GitHub - joe-robertson-mx/colourCount</a></p><h3>Getting Started</h3><p>To begin with, we scaffold our widget using the Mendix Widget generator yo @mendix/widget color count. This gives us our HelloWorld implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I6tHaCHzMKFLcygY.jpg" /></figure><p><strong>Folder structure:</strong></p><p>Our widget folder has the following structure:</p><blockquote>-dist — where our built and bundled code will be output</blockquote><blockquote>-node-modules — our node dependencies</blockquote><blockquote>-src -our src code folder</blockquote><blockquote>-components — each component folder jsx file</blockquote><blockquote>-ui — css for styling the widget</blockquote><blockquote>-package.xml — describes the widget structure</blockquote><blockquote>-colourCount.editorConfig.ts — config for preview in design mode in Studio Pro and Studio</blockquote><blockquote>-colourCount.editorPreview.jsx — component that provides preview in Studio Pro and Studio</blockquote><blockquote>-colourCount.tsx — the entry point for the widget</blockquote><blockquote>-colourcount.xml — the markup which describes the interface between the widget and Mendix</blockquote><blockquote>-package.json — describes our npm project and widget dependencies</blockquote><blockquote>-prettier.config.js — to allow us to modify the prettier rules for our code</blockquote><p><strong>Testing &amp; Development Setup</strong></p><p>To facilitate testing, we create a new blank Mendix Project in the version we are targeting for our widget, in ./colourCount/tests/testProject</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6uPAcXyr1HbtkzCO.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*jltmnMR-7RWdLhOG.jpg" /></figure><p><strong>Get it running</strong></p><p>Once that’s done, let’s run our build script and test our widget.</p><p>Navigate to your widget root directory from your terminal, then enter</p><pre>npm run build </pre><p>This will create a widget package in our dist/ folder and in the widgets folder of our test app.</p><p>To see that widget in action we just need to open our test application in Studio Pro and Press F4 to synchronize our file directory. We can then add our widget to a page the same way as we would any other widget.</p><p>To configure our widget and to verify that parameters are being passed through from the modeler to the widget in the front end we can add some text to pass through.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/0*Neh0M0YTm_5GikIS.jpg" /></figure><p>When we run the application we can see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*BjAIKbWcNUcFnH6H.jpg" /></figure><p>This deployment and testing process for our widget works, but it is a little slow. In order to accelerate the process, we can start the widget server by running</p><pre>npm run start</pre><p>This will watch our code for changes, and in order to see them reflected, we just need to clear the cache and force a reload.</p><p>This can be done in Chrome by opening the Chrome Developer Tools (Ctrl + Shift +i), right clicking the refresh button and selecting ‘Empty cache and hard reload’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*Jrtbr5vihX-tu3XT6a8u6g.png" /></figure><h3>Writing Code</h3><p>Time to code!</p><p><strong>A couple of minor changes before we start</strong></p><p>Let’s start with our react code, first let’s rename our components to something more sensible: Count.</p><p>First, we rename the components in the HelloWorld.jsx.</p><pre>import { createElement } from &quot;react&quot;;<br>import { Count } from &quot;./components/Count&quot;;<br>import &quot;./ui/ColourCount.css&quot;;</pre><pre>export function ColourCount({ sampleText }) {<br>   return &lt;Count sampleText={sampleText ? sampleText : &quot;World&quot;} /&gt;<br>}</pre><p>It is also best practice to rename the file to match the component within ColourCount.</p><p>We need to rename the CSS file at src/ui to ColourCount.css - so that it imports correctly. We also have to update the child component, to do this we first rename the HelloWorldSample.jsx to Count.jsx and update the name of the component within to Count.</p><pre>export function Count({ sampleText }: HelloWorldSampleProps) {<br>    return &lt;div className=&quot;widget-hello-world&quot;&gt;<br>              Hello {sampleText}<br>           &lt;/div&gt;;<br> }</pre><p>To speed up the development process we are going to change our editorPreview file so that it has no dependency on the rest of the code by updating it like this</p><pre>import { ReactElement, createElement } from &quot;react&quot;;</pre><pre>export function preview() {<br>    return &lt;div /&gt;;<br>}</pre><pre>export function getPreviewCss() {<br>    return require(&quot;./ui/ColourCount.css&quot;);<br>}</pre><p>Before we start updating our components let’s rename our child component to something more sensible: ‘Count’. To do this we need to update the ColourCount parent component to reference the Count component contained in the components/Count file.</p><p>Our widget build can be broken down into 3 parts:</p><ul><li>Update the Mendix Widget interface to accept a number for the starting value of the counter</li><li>Create the logic to change this number</li><li>Add the random color change to the number</li></ul><p><strong>Update Mendix Widget Interface</strong></p><p>The interface between the Mendix model and your widget is defined in the ColourCounter.xml markup. We need to update ours to accept a number value, by changing the ‘<strong>sampletext</strong>’ <em>property</em> to the following:</p><pre>&lt;property key=&quot;initialValue&quot; type=&quot;integer&quot; required=&quot;true&quot; defaultValue=&quot;5&quot;&gt;<br>    &lt;caption&gt;Initial Value&lt;/caption&gt;<br>    &lt;description&gt;The initial value of the counter&lt;/description&gt;&lt;/property&gt;</pre><p>If we open our Mendix model, press F4 and update the widget. When opening the widget you will see our new interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*1c0WN4jKT3BFiJoU.png" /></figure><p>However, this is not yet connected to our component.</p><p>In order to do this we need to replace <strong>sampleText</strong> with <strong>initialValue</strong> in the ColourCount file:</p><pre>import { createElement } from &quot;react&quot;;<br>import { Count } from &quot;./components/Count&quot;;<br>import &quot;./ui/ColourCount.css&quot;;</pre><pre>export function ColourCount({ initialValue }) {<br>    return &lt;Count initialValue={initialValue} /&gt;;<br>}</pre><p>And in the Count file</p><pre>export function Count({ initialValue }) {<br>    return &lt;div&gt;{initialValue}&lt;/div&gt;;<br>}</pre><p>if we rerun our application, we can see our initial value rendered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/0*ZDonXH_pTl8FgT2g.png" /></figure><p>The properties (or props) are passed down from the Mendix application to the ColourCount component, where it is destructured in the function and passed down to the Count component.</p><blockquote>Read more about destructuring javascript objects <a href="https://dmitripavlutin.com/javascript-object-destructuring/">here</a>.</blockquote><p><strong>Create the logic to change this number</strong></p><p>Props shouldn’t be directly changed in React. Instead, we store properties that are changed in the component state.</p><p>In order to leverage state in a functional component, we use the useState hook.</p><blockquote>Hooks were introduced in React 16.8 version. It allows you to use state and other React features without writing a class. Hooks are the functions that “hook into” React state and lifecycle features from function components. It does not work inside classes. Read more about Hooks in React <a href="https://www.javatpoint.com/react-hooks#:~:text=Hooks%20are%20the%20new%20feature,does%20not%20work%20inside%20classes.">here</a>.</blockquote><p>Firstly we need to add <strong>useState</strong> to the imports.</p><p>import { createElement, useState } from &quot;react&quot;;</p><p>Then we add the following code to the Count component.</p><pre>export function Count({ initialValue }) {<br>    const [count, setCount] = useState (initialValue)<br>    return &lt;div&gt;{count}&lt;/div&gt;;<br>}</pre><p>When we call <strong>useState</strong> it returns an array of the state variable, and a function to set the state variable. This is immediately destructured into the <strong>count</strong> state and <strong>setCount</strong> function.</p><p>It accepts the <strong>initialValue</strong> as a parameter, which sets the value of the count variable on creation.</p><p>Now we can change the state, using <strong>setCount</strong>. When setting state, you can either simply pass in a value, or as in this case, you can use the previous state as a parameter in the function.</p><p>Knowing this we can add a function to increase the state value.</p><pre>export function Count({ initialValue }) {</pre><pre>   const [count, setCount] = useState (initialValue)<br>   <br>   const increment = () =&gt; {<br>      setCount(prevState =&gt; prevState + 1);<br>   }; </pre><pre>   return &lt;div&gt;{initialValue}&lt;/div&gt;;<br>}</pre><p>We can do the same for a decrement function.</p><p>Now we need to update the JSX to render the HTML we want for our application:</p><pre>export function Count({ initialValue }) {<br>    const [count, setCount] = useState (initialValue)</pre><pre>    const increment = () =&gt; {<br>         setCount(prevState =&gt; prevState + 1);<br>    };</pre><pre>    const decrement = () =&gt; {<br>        setCount(prevState =&gt; prevState - 1);<br>    };</pre><pre>    return (<br>        &lt;div&gt;<br>              &lt;p&gt;{count}&lt;/p&gt;<br>              &lt;button onClick={increment}&gt;+&lt;/button&gt;<br>              &lt;button onClick={decrement}&gt;-&lt;/button&gt;<br>       &lt;/div&gt;<br>    );<br>}</pre><p>When we run our application we can now increase and decrease the value in the <strong>state</strong>, which is displayed in the widget:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/0*eNf9AGh9JCyrVtVz.png" /></figure><p><strong>Add the random color change to the number</strong></p><p>We now want to generate a randomized colour when the count changes. This would be a time-consuming piece of code to write, fortunately we can make use of a pre-written software package stored in the npm registry: <strong>randomcolor</strong>.</p><p><a href="https://www.npmjs.com/package/randomcolor">randomcolor</a></p><p>The package provides a function that when called returns a randomized color as a string. Leveraging this package is easy: first, we install the package by running npm install randomcolor in our widget folder.</p><p>Then we start changing code in our Count file. First we import the function</p><p>import randomColor from &#39;randomcolor&#39;;</p><p>Then we need to initiate some state to hold our color property</p><p>const [colour, setColour] = useState(&#39;&#39;)</p><p>We also need the color to be reflected in the style of the widget to do this, we can use the style property for the HTML tag. The style property accepts a JS object with the style properties you wish to apply.</p><blockquote>Read more about styling Dom elements using React <a href="https://reactjs.org/docs/dom-elements.html#style">here</a>.</blockquote><p>&lt;p style={{ color: colour }}&gt;{count}&lt;/p&gt;</p><p>Whilst we are here, we can improve the look of our buttons by using the inbuilt Mendix classes:</p><pre>import { createElement, useState } from &#39;react&#39;<br>import randomColor from &#39;randomcolor&#39;</pre><pre>export function Count({ initialValue }) {<br>  const [count, setCount] = useState(initialValue)<br>  const [colour, setColour] = useState(&#39;&#39;)<br>  <br>  const increment = () =&gt; {<br>    setCount((prevState) =&gt; prevState + 1)<br>  }<br>  <br>  const decrement = () =&gt; {<br>    setCount((prevState) =&gt; prevState - 1)<br>  }<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;p style={{ color: colour }}&gt;{count}&lt;/p&gt;<br>      &lt;button className=&quot;mx-button btn-primary&quot; onClick={increment}&gt;<br>        +<br>      &lt;/button&gt;<br>      &lt;button className=&quot;mx-button&quot; onClick={decrement}&gt;<br>        -<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  )</pre><p>We now need to trigger the color to change, when our count variable changes. For this, we can use one of the key utilities available in React: <strong>useEffect</strong>.</p><p><strong>useEffect</strong> is a hook, which calls a function (a side effect) on every render of the component. By adding the following we can set the color to a random value on render:</p><pre>import { createElement, useState } from &#39;react&#39;<br>import randomColor from &#39;randomcolor&#39;</pre><pre>export function Count({ initialValue }) {<br>  const [count, setCount] = useState(initialValue)<br>  const [colour, setColour] = useState(&#39;&#39;)<br>  <br>  useEffect(() =&gt; {<br>    setColour(randomColor())<br>  }, [])<br>  <br>  const increment = () =&gt; {<br>    setCount((prevState) =&gt; prevState + 1)<br>  }<br>  <br>  const decrement = () =&gt; {<br>    setCount((prevState) =&gt; prevState - 1)<br>  }<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;p style={{ color: colour }}&gt;{count}&lt;/p&gt;<br>      &lt;button className=&quot;mx-button btn-primary&quot; onClick={increment}&gt;<br>        +<br>      &lt;/button&gt;<br>      &lt;button className=&quot;mx-button&quot; onClick={decrement}&gt;<br>        -<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br></pre><p>When we run this in the browser we get…DISCO COUNT!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*BLJ0yH2qG7Mv2xph.gif" /></figure><p>This is cool, but definitely not what we want. So why is this happening?</p><p>Well, if we put a console.log(‘Render’) in the useEffect we can see that the component is repeatedly rerendering and this is because components rerender on any change of state or props. So when we set the color state in the useEffect <strong>it causes a rerender and an infinite loop</strong>.</p><p>Fortunately, this is easy to fix. The useEffect hook accepts a 2nd parameter, which is an array of states and/or props to watch. This means the function will only run when one of the watched states/props changes. We only want the color to change when our count changes, so we update our useEffect to:</p><pre>useEffect(() =&gt; {<br>    setColour(randomColor())<br>  }, [count])</pre><p><em>Note: To just run the useEffect once, on component load add an empty array as the second parameter</em></p><p>Now when we update our widget…VOILA!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/0*I0YgsbTVXqlN7Cd0.gif" /></figure><h3>Recap</h3><p>In this blog, we covered how to use Pluggable Widgets with Mendix, how to set up your development environment and some core React concepts including state, props, and useEffect.</p><p>The final code for the widget can be found here:</p><p><a href="https://github.com/joe-robertson-mx/colourCount">GitHub - joe-robertson-mx/colourCount</a></p><h3>What next?</h3><p>Up next we will begin using Typescript, integrate directly with Mendix entities and attributes, and look at how to trigger actions in our Mendix model from our widget.</p><p>Let us know what you think of this post. Are there any widgets you would like to see? Please put any suggestions for future widgets in the comments here.</p><p><strong>Resources</strong></p><p>To learn more about pluggable widgets the following resources might be helpful:</p><ul><li><a href="https://reactjs.org/docs/getting-started.html">Getting Started - React</a></li><li><a href="https://docs.mendix.com/howto/extensibility/pluggable-widgets/">Build Pluggable Web Widgets</a></li><li><a href="https://github.com/mendix/widgets-resources/tree/master/packages/pluggableWidgets">widgets-resources/packages/pluggableWidgets at master · mendix/widgets-resources</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1e400c3cdff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mendix/build-widgets-in-mendix-with-react-part-1-colour-counter-f1e400c3cdff">Build widgets in Mendix with React — Part 1 — Colour Counter</a> was originally published in <a href="https://medium.com/mendix">Mendix Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>