<?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 Mathis Garberg on Medium]]></title>
        <description><![CDATA[Stories by Mathis Garberg on Medium]]></description>
        <link>https://medium.com/@mathis.garberg?source=rss-5dc1286f4ca3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pzkOXDV0FY3QkIROkVnwkA.png</url>
            <title>Stories by Mathis Garberg on Medium</title>
            <link>https://medium.com/@mathis.garberg?source=rss-5dc1286f4ca3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 12:09:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mathis.garberg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building an intuitive Drag and Drop Hierarchy with React Aria]]></title>
            <link>https://medium.com/@mathis.garberg/building-an-intuitive-drag-and-drop-hierarchy-with-react-aria-cd2f58894dc1?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd2f58894dc1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[drag-and-drop]]></category>
            <category><![CDATA[hierarchy]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Wed, 25 Dec 2024 18:04:18 GMT</pubDate>
            <atom:updated>2024-12-25T22:37:37.035Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an interactive Drag and Drop Hierarchy with React Aria ❤️🚀</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kzkzs0lpmpOyJXx8" /></figure><p>Drag and drop (DnD) functionality offers an intuitive way for users to interact with- and organize data. By dragging/grabbing visual representations across the screen, users can transfer data seamlessly within an application. This article demonstrates how to implement a drag and drop hierarchy with <a href="https://react-spectrum.adobe.com/react-aria/index.html"><strong>React Aria</strong></a>, a library for accessible React components.</p><p>This solution demonstrates how to build an interactive hierarchy where each item can act as both a drag source and a drop target. The solution will be minimal, flexible and efficient, with features like drag previews, drop zones, and parent-child relationships, enabling users to reorganize their data in an interactive manner.</p><h3>Getting Started</h3><h4>1. Initialize the React Application with <a href="https://vite.dev/">Vite</a></h4><pre>npm create vite@latest dnd-tree --template react</pre><p>Navigate to the created folder and install the necessary dependencies.</p><pre>cd dnd-tree<br>npm install<br>npm i @react-stately/data react-aria</pre><h4>2. Understanding the concept of drag and drop with React Aria</h4><p>In our drag and drop implementation, the functionality revolves around two hooks — <em>useDrag </em>and <em>useDrop</em>. Here’s an overview of their key functionalities.</p><ul><li><a href="https://react-spectrum.adobe.com/react-aria/useDrag.html">useDrag</a>: Defines draggable elements and handles drag behavior.</li><li><a href="https://react-spectrum.adobe.com/react-aria/useDrop.html">useDrop</a>: Manages drop targets and the behavior when items are dropped in a particular drop target.</li><li>DragPreview: Displays a custom preview of the dragged items under the cursor.</li><li><strong>Hierarchical state</strong>: The <a href="https://react-spectrum.adobe.com/react-stately/useTreeData.html">useTreeData</a> hook from React Stately will help us manage the state throughout our hierarchy.</li></ul><h3>Building the application</h3><p>To structure your application, we’ll create two components:</p><ol><li><em>RecursiveDivTree</em>: Handles the hierarchical logic.</li><li><em>RenderTreeItem</em>: Manages the behavior and appearance of each item in the tree.</li></ol><h4>3. Creating the hierarchy in the <em>RecursiveDivTree </em>component</h4><p>Start with defining a hierarchy of data using the <a href="https://react-spectrum.adobe.com/react-stately/useTreeData.html">useTreeData hook</a>. Each item will have children, and the hierarchy will be dynamically updated as items are dragged and dropped.</p><pre>import { useTreeData } from &quot;@react-stately/data&quot;;<br>import { useState } from &quot;react&quot;;<br>import RenderTreeItem from &quot;./RenderTreeItem&quot;;<br><br>const initialItems = [<br>  {<br>    id: &quot;1&quot;,<br>    name: &quot;Number one&quot;,<br>    children: [<br>      {<br>        id: &quot;2&quot;,<br>        name: &quot;Number two&quot;<br>      }<br>    ]<br>  },<br>  {<br>    id: &quot;3&quot;,<br>    name: &quot;Number three&quot;,<br>    children: [<br>      {<br>        id: &quot;4&quot;,<br>        name: &quot;Number four&quot;<br>      }<br>  }<br>];<br><br>export const RecursiveDivTree = ({ initialFile }) =&gt; {<br>  const tree = useTreeData({<br>    initialItems: initialFile.children,<br>    getKey: (item) =&gt; item.id,<br>    getChildren: (item) =&gt; item.children || [],<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      {tree.items.map((node) =&gt; (<br>        &lt;RenderTreeItem<br>          key={node.value.id}<br>          node={node}<br>          tree={tree}<br>        /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>4. Define draggable elements</h4><p>Then, in our <em>RenderTreeItem </em>component, we’ll start defining our drag interactions. Use the useDrag hook to define the drag behavior for each item. The hook specifies the type of data being transferred, in this case <em>application/json</em>, and manages the drag state.</p><pre>const { dragProps, isDragging } = useDrag({<br>  getItems() {<br>    return [{ &quot;application/json&quot;: JSON.stringify(node) }];<br>  }<br>});</pre><h4>5. Setting up drop zones</h4><p>The useDrop hook enables elements to accept dropped items and handle the logic when a drop occurs, which here means moving the item to a new location within the hierarchy with the <em>move </em>function.</p><pre>const { dropProps, isDropTarget } = useDrop({<br>    async onDrop(e) {<br>      const items = await Promise.all(<br>        e.items.map(async (item) =&gt;<br>          JSON.parse(await item.getText(&quot;application/json&quot;))<br>        )<br>      );<br>      tree.move(items[0].key, node.key);<br>    },<br>});</pre><h4>6. The Drag Preview</h4><p>While dragging an item, we have the option of adding a drag preview, which is displayed under the mouse cursor while dragging the item. This is a copy of the dragged element, but can be customized with the DragPreview component to fit our needs.</p><pre>&lt;DragPreview&gt;<br>  {(items) =&gt; {<br>    const item = JSON.parse(items[0][&quot;application/json&quot;]);<br>    return &lt;div&gt;{item.value.name}&lt;/div&gt;;<br>  }}<br>&lt;/DragPreview&gt;</pre><p>We’ll end up with the folllowing <em>RenderTreeItem</em> component.</p><pre>import { useDrag, useDrop, DragPreview } from &quot;react-aria&quot;;<br>import { useRef } from &quot;react&quot;;<br><br>export const RenderTreeItem = ({ node, tree}) =&gt; {<br>  const dragRef = useRef();<br>  const dropRef = useRef();<br><br>  const { dragProps, isDragging } = useDrag({<br>    getItems() {<br>      return [{ &quot;application/json&quot;: JSON.stringify(node) }];<br>    },<br>    preview: dragRef,<br>  });<br><br>  const { dropProps, isDropTarget } = useDrop({<br>    async onDrop(e) {<br>      const items = await Promise.all(<br>        e.items.map(async (item) =&gt;<br>          JSON.parse(await item.getText(&quot;application/json&quot;))<br>        )<br>      );<br>      tree.move(items[0].key, node.key);<br>    },<br>  });<br><br>  return (<br>    &lt;div ref={dropRef} {...dropProps}&gt;<br>      &lt;div<br>        ref={dragRef}<br>        {...dragProps}<br>        className={`item ${isDragging ? &quot;dragging&quot; : &quot;&quot;}`}<br>      &gt;<br>        {node.value.name}<br>      &lt;/div&gt;<br>      &lt;DragPreview&gt;<br>        {(items) =&gt; {<br>          const item = JSON.parse(items[0][&quot;application/json&quot;]);<br>          return &lt;div&gt;{item.value.name}&lt;/div&gt;;<br>        }}<br>      &lt;/DragPreview&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Start the application</h3><p>Run the application using the following command.</p><pre>npm run dev</pre><p>Visit http://localhost:5173 to see your drag and drop hierarchy in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*D0CEXey12Hp6cnCTgDkmSQ.gif" /></figure><h3>Conclusion</h3><p>This implementation provides a minimal and efficient way to integrate drag and drop functionality into a React application. By leveraging <strong>React Aria</strong>, you can build accessible and dynamic components with ease. Experiment with custom previews, drop operations, and tree structures to further enhance your application’s interactivity.</p><p><em>My name is Mathis Garberg, and I am a consultant at </em><a href="https://www.dfindconsulting.no/"><em>Dfind Consulting</em></a><em> in Oslo, Norway.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*ceXNqTajCimrdavm.png" /></figure><ul><li><a href="https://react-spectrum.adobe.com/blog/drag-and-drop.html">https://react-spectrum.adobe.com/blog/drag-and-drop.html</a></li><li><a href="https://react-spectrum.adobe.com/react-stately/useTreeData.html">https://react-spectrum.adobe.com/react-stately/useTreeData.html</a></li><li><a href="https://react-spectrum.adobe.com/react-aria/useDrop.html">https://react-spectrum.adobe.com/react-aria/useDrop.html</a></li><li><a href="https://react-spectrum.adobe.com/react-aria/useDrag.html">https://react-spectrum.adobe.com/react-aria/useDrag.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd2f58894dc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an interactive Dashboard with react-grid-layout]]></title>
            <link>https://itnext.io/building-an-interactive-dashboard-in-react-22437045d53c?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/22437045d53c</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 21:47:05 GMT</pubDate>
            <atom:updated>2024-08-05T10:26:37.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NYk0n2Wx-wyf6KYVj6eSg.png" /><figcaption>Customizable dashboard, created with react-grid-layout</figcaption></figure><h4>Background</h4><p>In today’s data-driven world, data is crucial for measuring performance, identifying opportunities, and making informed decisions. However, handling complex data structures in a structured manner can be a challenging task.</p><p>Dashboards offer a user-friendly way to visualize and access centralized data in real-time, making them valuable tools for businesses and organizations.</p><p>Our providers sought greater insight into their API usage, and with the dashboard we developed, you can easily track API consumption and gain deeper insights into your API activities.</p><h4>Overview</h4><p>So in this tutorial, I will create a dashboard in <a href="https://reactjs.org/">React</a>. The dashboard will be highly customizable, meaning the user is in complete control of every visual aspect — from controlling the layout to customizing the widgets.</p><p>Before we started out creating the solution, we had to make some initial groundwork in terms of how it should be solved. Here, we started out by running an analysis of which npm dependencies that would best suited for implementing such a solution, and there were several candidates. But the outstanding winner was for sure the <a href="https://github.com/react-grid-layout/react-grid-layout">react-grid-layout</a> library.</p><h4>Getting Started</h4><p>We first need to setup our React application. Since all the cool kids on the block are now using the React, Vite and Tailwind combo, we’ll do this as well. Generate a new project in your desired location with the following command:</p><pre>npm create vite@latest customizable-dashboard --template react</pre><p>Then CD customizable-dashboard and install the necessary dependencies with the following commands:</p><pre>npm i react-grid-layout recharts</pre><p>When this is done, confirm that you’re able to start the server by running the npm run dev command. This should start a new server instance.</p><h4>Start Coding</h4><p>Start with creating a Dashboard folder in the root of your directory. This folder will contain all dashboard-related logic, with the potential of re-usability in other circumstances. Starting with the bare minimum. Then create a file inside called Dashboard.tsx, and add the following code inside:</p><pre>const Dashboard = () =&gt; {<br>  const minColumnWidth = 2<br>  const minColumnHeight = 2<br><br>  const items = [<br>    {<br>        i: `node-1`,<br>        w: minColumnWidth,<br>        h: minColumnHeight,<br>        minW: minColumnWidth,<br>        minH: minColumnHeight,<br>        name: &quot;Node one 😀&quot;<br>    }<br>  ]<br><br>  const gridState = {<br>    columnsPerRow: 12,<br>    items: items,<br>    layout: { lg: items, md: items, sm: items, xs: items, xss: items }<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;GridLayout gridState={gridState}/&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default Dashboard</pre><p>The Dashboard component functions as the container of the board. The values passed down to the GridLayout component describes the items to render.</p><pre>import { Responsive, WidthProvider } from &quot;react-grid-layout&quot;;<br><br>const ResponsiveGridLayout = WidthProvider(Responsive)<br><br>const GridLayout = (gridState) =&gt; {<br>  const defaultProps = {<br>    breakpoints: { lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 },<br>    cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}<br>  }<br><br>  return (<br>    &lt;ResponsiveGridLayout {...defaultProps} layouts={gridState.layout}&gt;<br>      {gridState.items.map((item) =&gt; (<br>        &lt;h1 key={item.i}&gt;{item.name}&lt;/h1&gt;<br>      )}<br>    &lt;/ResponsiveGridLayout&gt;<br>  )<br>}<br><br>export default GridLayout</pre><p>The <em>ResponsiveGridLayout </em>from the <em>WidthProvider</em> allows us to specify the exact breakpoints and column amount to react on during the <em>resize </em>event.</p><pre>export const App = () =&gt; (&lt;Dashboard /&gt;)<br>export default App</pre><p>Start the server again, open a browser and access the application in addressbar to see the result.</p><p>The current implementation works great for static information, but doesn’t allow any customization. So let’s take this one step further, and implement a simple CRUD behavior:</p><pre>const Dashboard = () =&gt; {<br> const [gridState, setGridState] = useState&lt;IGridState&gt;({<br>  currentBreakpoint: &quot;lg&quot;,<br>  maxXCoord: 12,<br>  newCounter: 0,<br>  items: []<br> })<br>const { items, newCounter, maxXcoord currentBreakpoint } = gridState<br><br>const calculateNewCoordinates = () =&gt; {<br> if (items.length) {<br>  const maxYCoord = items.reduce((acc, curr) =&gt; (acc &gt; curr.y + curr.h ? acc : curr.y + curr.h), 0)<br><br>  for (let yPosition = 0; yPosition &lt; maxYCoord; yPosition++) {<br>   for (let xPosition = 0; xPosition &lt; maxXCoord; xPosition++) {<br>    const isCollidingCoordinate = items.some((item) =&gt; {<br>     const inXRange = xPosition &gt;= item.x &amp;&amp; xPosition &lt; item.x + item.w<br>     const inYRange = yPosition &gt;= item.y &amp;&amp; yPosition &lt; item.y + item.h<br>     return inXRange &amp;&amp; inYRange<br>    })<br><br>    if (isCollidingCoordinate) continue<br><br>    return { x: xPosition, y: yPosition }<br>   }<br>  }<br> }<br><br> return { x: 0, y: 0 }<br>}<br><br>  // ...<br>    const onAddColumn = () =&gt; {<br>    const newCoordinates = calculateNewCoordinates()<br><br>      const newItem = {<br>        w: minColumnWidth,<br>        h: minColumnHeight,<br>        minW: minColumnWidth,<br>        minH: minColumnHeight,<br>        x: newCoordinates.x,<br>        y: newCoordinates.y,<br>        i: `node-${newCounter}`,<br>        name: `New node ${newCounter} 😀`<br>      }<br><br>      setGridState(prevState =&gt; ({<br>        ...prevState,<br>        newCounter: prevState.newCounter + 1,<br>        items: [...prevState.items, newItem]<br>      })<br>    }<br><br>    const onRemoveColumn = (index) =&gt; {<br>      setGridState(prevState =&gt; ({<br>        ...prevState,<br>        items: prevState.items.filter(x =&gt; x.i !== index)<br>      })<br>    }<br><br>  // ...<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;Button onClick={onAddColumn} /&gt;<br>      &lt;GridLayout gridState={gridState} onRemoveColumn={onRemoveColumn} /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>You can see that the code have change a bit from the original implementation here. Instead of hardcoding the gridState in a constant, we’ve now defined it with the useState hook. We’ve also created a new method here, called onAddColumn. This function starts out with calling another function, calculateNewCoordinates. We won’t dive too much into how this method functions, but what it essentially does is figuring out where the new column should be added. So it will go along the X-axis, one item at a time and check whether another item occupies that space or not, before finally returning the available coordinates or the initial position.</p><p>Then we create a new item with these coordinates, along with adding a newCounter value to index property, which is an essential step to make the items render correctly.</p><p>Finally, before breaking out of the function, we update the gridState with the new item and increase the counter.</p><p>The 🍒 on the cake will be introducing draggable behavior to our newly created items, which allow us to freely move the boxes around on our board.</p><pre>const GridLayout = (gridState, onRemoveColumn) =&gt; {<br>  const defaultProps = {<br>    breakpoints: { lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 },<br>    rowHeight: 150,<br>    draggableHandle: &quot;.draggable-handle&quot;<br>  }<br>   <br><br>  // ...<br>  <br>  return (<br>    &lt;ResponsiveGridLayout {...defaultProps} layouts={gridState.layout}&gt;<br>      {gridState.items.map((item) =&gt; (<br>        &lt;Card&gt;<br>          &lt;Icon className=&quot;draggable-handle&quot; icon=&quot;faGrips&quot; /&gt;<br>          &lt;Button onClick={onRemoveColumn(item.i)} /&gt;<br>          &lt;h1 key={item.i}&gt;{item.name}&lt;/h1&gt;<br>        &lt;/Card&gt;<br>      )}<br>    &lt;/ResponsiveGridLayout&gt;<br>  )<br>}</pre><p>You’ve probably guessed, but yes, it is as simple as adding the draggable handle property with a class name definition.</p><h3>Conclusion</h3><p>We’ve now created a dashboard layout that allows our users full customize capabilities over each column on the board.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22437045d53c" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/building-an-interactive-dashboard-in-react-22437045d53c">Building an interactive Dashboard with react-grid-layout</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Completely Dynamic UI with Sanity, a Node Server and React]]></title>
            <link>https://itnext.io/build-a-completely-dynamic-ui-with-sanity-a-node-server-and-react-f2418219b761?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2418219b761</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[sanity]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 17:31:07 GMT</pubDate>
            <atom:updated>2024-04-04T08:45:48.622Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*7lRHpIMZvFD_jqhX" /><figcaption>Building LEGOs with a manual</figcaption></figure><p>Building with LEGO has always been an interest of mine. Piecing together a 3-dimensional puzzle, either from the restrictions of a manual or within the creative sphere presents a unique blend of mental stimulation and a test of patience.</p><p>This creativity in building different structures based on a core is a useful trait in many aspects of life, let alone web development. During this article, we’ll build on this concept to create a completely dynamic UI. Much like assembling LEGO blocks, we’ll piece together sections of content, where you’re in complete control of the final outcome.</p><h4>The Goal</h4><p>So the idea is to perform an initial request to retrieve the application routes from Sanity, and dynamically configure a <a href="https://reactrouter.com/en/main">React Router</a> with them. These routes will along with the route name contain a reference to the dynamic page in question, and is used to retrieve the page along with it’s associated sections. Static content like the header and footer exists beyond the outlet, to remain consistent between route transitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*3JMLF24LK0luhI8lPKAOgw.png" /><figcaption>Illustration of the final application structure.</figcaption></figure><h4>Building our Sanity instance</h4><p>Since all the content for our application will be served from Sanity, it’s the logical place to start out. Sanity is a popular solution for serving content to consumer applications in a flexible and dynamic manner. You can follow the instructions on <a href="https://www.sanity.io/docs/create-a-sanity-project">this</a> page on how to set it up.</p><p>Once the initial setup is complete, add the following folder structure inside the Sanity application.</p><pre>|-- ...<br>|-- schemas<br>     |-- documents<br>          |- application.ts<br>     |-- dynamicPage<br>          |-- sections<br>               |- SectionOne.ts<br>               |- SectionTwo.ts<br>               |-- ...<br>               |- index.ts<br>          |- dynamicPage.ts<br>|-- objects<br>      |- dynamicRoute.ts</pre><p><em>A sections </em>does, as the image above describes, define an isolated section of content on the page. This could be everything from a <em>HeroBanner </em>on the top of the page to a simple heading, and will look like this.</p><pre>// schemas/dynamicPage/sections/sectionOne.ts<br>export const sectionOne = defineField({<br>  title: &quot;Section One&quot;,<br>  name: &quot;sectionOne&quot;,<br>  type: &quot;object&quot;,<br>  fields: [<br>    defineField({<br>      title: &quot;Properties&quot;,<br>      name: &quot;properties&quot;,<br>      type: &quot;object&quot;,<br>      fields: [<br>         defineField({<br>            title: &quot;Heading&quot;,<br>            name: &quot;heading&quot;,<br>            type: &quot;string&quot;,<br>            description: &quot;The heading for the banner.&quot;,<br>          }),<br>      ]<br>    })<br>  ]<br>});<br><br>// schemas/dynamicPage/sections/sectionTwo.ts<br>export const sectionTwo = defineField({<br>  title: &quot;Section Two&quot;,<br>  name: &quot;sectionTwo&quot;,<br>  type: &quot;object&quot;,<br>  fields: [<br>    defineField({<br>      title: &quot;Properties&quot;,<br>      name: &quot;properties&quot;,<br>      type: &quot;object&quot;,<br>      fields: [<br>         defineField({<br>            title: &quot;Heading&quot;,<br>            name: &quot;heading&quot;,<br>            type: &quot;string&quot;,<br>            description: &quot;The heading for the banner.&quot;,<br>          }),<br>      ]<br>    })<br>  ]<br>});</pre><p>The <em>properties </em>naming will be familiar for those with a <em>React </em>background, as the idea is to pass these values as <em>props </em>to the component in question.</p><p>Then we need to create an array field to export these sections. We’ll also add a <em>sort </em>with a <em>localCompare fn </em>to sort them alphabetically.</p><pre>// schemas/dynamicPage/sections/sections.ts<br>import {sectionOne} from &quot;./sectionOne&quot;<br>import {sectionTwo} from &quot;./sectionTwo&quot;<br>import {defineField} from &quot;sanity&quot;<br><br>const sectionsByName= [<br>  sectionOne,<br>  sectionTwo<br>].sort((a, b) =&gt; a.title!.localeCompare(b.title!))<br><br>export const sections = () =&gt;<br>  defineField({<br>    title: &quot;Sections&quot;,<br>    name: &quot;sections&quot;,<br>    type: &quot;array&quot;,<br>    of: sectionsByName,<br>  })</pre><p>A dynamic page is comprised of one or more sections in any particular order, and does also include a title for ease of reference.</p><pre>// schemas/dynamicPage/dynamicPage.ts<br>import {sections} from &quot;./sections/sections&quot;<br><br>export const dynamicPage = defineField({<br>  title: &quot;Dynamic Pages&quot;,<br>  name: &quot;dynamicPage&quot;,<br>  type: &quot;document&quot;,<br>  fields: [<br>      defineField({<br>        title: &quot;Title&quot;,<br>        name: &quot;title&quot;,<br>        type: &quot;string&quot;<br>      }),<br>     sections()<br>    ]<br>  })</pre><p>The <em>dynamic route </em>will contain all our application routes with references to the dynamic page(s), and lives within the application document, which outlies the structure of the entire application.</p><pre>// objects/dynamicRoute<br>export const dynamicRoute = defineField({<br>  title: &quot;Dynamic Route&quot;,<br>  name: &quot;dynamicRoute&quot;,<br>  type: &quot;object&quot;,<br>  fields: [<br>     defineField({<br>        title: &quot;Path&quot;,<br>        name: &quot;path&quot;,<br>        type: &quot;string&quot;,<br>        description:<br>          &quot;The path this route should match. Supports all route expressions that expressjs supports.&quot;,<br>        validation: (Rule) =&gt;<br>          Rule.required().custom((path: string | undefined) =&gt;<br>            (path || &quot;&quot;).startsWith(&quot;/&quot;) ? true : &quot;Path must start with /&quot;<br>          ),<br>      }),<br>      defineField({<br>        title: &quot;Properties&quot;,<br>        name: &quot;properties&quot;,<br>        type: &quot;object&quot;,<br>        fields: [<br>          defineField({<br>            title: &quot;Reference page&quot;,<br>            name: &quot;page&quot;,<br>            type: &quot;reference&quot;,<br>            to: [{type: &quot;dynamicPage&quot;}],<br>          })<br>        ]<br>      }),<br>  ]<br>});<br></pre><pre>// schemas/documents/application.ts<br>export const application = defineField({<br>    name: &quot;application&quot;,<br>    type: &quot;document&quot;,<br>    description: &quot;Describes the central configuration for an application&quot;,<br>    fields: [<br>        defineField({<br>          title: &quot;Application name&quot;,<br>          name: &quot;name&quot;,<br>          type: &quot;string&quot;,<br>          validation: (Rule) =&gt; Rule.required()<br>        }),<br>        defineField({<br>          title: &quot;Description&quot;,<br>          name: &quot;description&quot;,<br>          type: &quot;string&quot;,<br>          fieldset: &quot;info&quot;,<br>          description: &quot;A short description of this application.&quot;,<br>        }),<br>        defineField({<br>          title: &quot;Routes&quot;,<br>          name: &quot;routes&quot;,<br>          type: &quot;array&quot;,<br>          of: [dynamicRoute],<br>          options: {<br>            layout: &quot;list&quot;,<br>          },<br>        })<br>    ]<br>});</pre><p>Finally, we need to register our documents among the <em>schemaTypes</em>.</p><pre>// schemaTypes/index.ts<br>import { application } from &quot;../schemas/documents/application&quot;;<br>import { dynamicPage } from &quot;../schemas/dynamicPage/dynamicPage&quot;;<br><br>export const schemaTypes = [application, dynamicPage]</pre><p>Now that all files have been added, our Sanity instance should look and behave like this when launching the dev server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbbmRP-Ncv5zmoATvwlXvA.png" /><figcaption>The initial Sanity application</figcaption></figure><h4>Adding Content</h4><p>Having the CMS instance up and running is as well and good, but we still need to add some content.</p><p>Start with adding a dynamic page document with two sections — <em>SectionOne </em>and <em>SectionTwo</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Re6S4D0pHp3bSAtXrdUWA.gif" /><figcaption>Illustration of SectionOne and SectionTwo within a Dynamic Page</figcaption></figure><p>Then we need to create an application and add a route with a reference to the dynamic page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1k3h-5RApc7eTwtnaAj5A.gif" /><figcaption>Illustration of the application with a Dynamic Page reference</figcaption></figure><p>Finally, publish the changes.</p><h4>Node Server with GROQ Queries</h4><p>Now that our Sanity instance is finished, we need to consume the content. Here, we’ll use a Node Server with a Sanity client to perform GROQ queries towards the instance. Then we’ll expose the content to the client through endpoints created with the <em>Express </em>framework.</p><p>Start with <a href="https://philna.sh/blog/2019/01/10/how-to-start-a-node-js-project/">initializing a new Node application</a> and install the following packages.</p><pre>npm init -y<br><br>npm install express @sanity/client cors</pre><p>Since we want to use TypeScript here as well, we need to configure it within the application through the following command, along with installing the necessary types.</p><pre><br>npx tsc --init<br><br>npm i -D typescript ts-node @types/node @types/express @types/cors</pre><p>Continue with building up the following structure on the server.</p><pre>|-- queries<br>|    |- SanityDynamicRoutesQuery.ts<br>|    |- SanityDynamicPageQuery.ts<br>|- start.ts</pre><p>The <em>start.ts</em> file will be the entry point of the server and contain our endpoints along with CORS configurations for the client-origin.</p><p>In order to create workable Sanity queries, we need some additional configurations, in order to establish a connection towards our instance. This is achieved by adding the desired configurations inside the <em>createClient </em>method, and is all available in Sanity.</p><pre>// start.ts<br>import {createClient} from &#39;@sanity/client&#39;<br>import { SanityDynamicPageQuery } from &#39;./queries/SanityDynamicPageQuery&#39;<br>import { SanityDynamicRoutesQuery } from &#39;./queries/SanityDynamicRoutesQuery&#39;<br>import { Request, Response } from &#39;express&#39;<br>import cors from &quot;cors&quot;;<br><br>export const client = createClient({<br>  projectId: &#39;your-project-id&#39;,<br>  dataset: &#39;your-dataset&#39;,<br>  useCdn: false, // set to `false` to bypass the edge cache<br>  apiVersion: &#39;2024-02-29&#39;, // use current date (YYYY-MM-DD) to target the latest API version<br>})<br><br>var express = require(&#39;express&#39;)<br>var app = express()<br><br>const allowedOrigins = [&#39;https://localhost:5173&#39;]; // standard Vite port<br><br>const options: cors.CorsOptions = {<br>  origin: allowedOrigins<br>};<br><br>app.use(cors(options));<br><br>app.get(&#39;/api/v1/dynamicRoutes&#39;, async function  (req: Request, res: Response) {<br>  var dynamicRoutes = await SanityDynamicRoutesQuery();<br><br>  return res.send(dynamicRoutes);<br>})<br><br>app.get(&#39;/api/v1/dynamicPage/:id&#39;, async function  (req: Request, res: Response) {<br>  var dynamicPage = await SanityDynamicPageQuery(req.params.id)<br><br>  return res.send(dynamicPage);<br>})<br><br>app.listen(3000, () =&gt; {<br>  console.log(`[server]: Server is running at http://localhost:3000`);<br>})</pre><p>Starting with the <em>SanityDynamicRouteQuery</em>, we need to perform a GROQ query to retrieve the data from Sanity. You can experiment with these queries yourself using the Sanity <a href="https://www.sanity.io/docs/the-vision-plugin">Vision Plugin</a> in the CMS instance.</p><p>The query below will return all published dynamic routes of the application in question, excluding draft documents.</p><pre>// queries/SanityDynamicRoutesQuery.ts<br>export const SanityDynamicRoutesQuery = async () =&gt; {<br>  const groqQuery = `<br>    *[!(_id in path(&#39;drafts.**&#39;)) &amp;&amp; _type == &quot;application&quot;][0]{routes}`;<br><br>  const data = await client.fetch(groqQuery);<br><br>  return data<br>}</pre><p>Then add the <em>SanityDynamicPageQuery </em>file. This will query the dynamic page using the reference id from the output in the <em>SanityDynamicRoutesQuery</em>, and return a list sections with it’s associated properties.</p><pre>// queries/SanityDynamicPageQuery.ts<br>export const SanityDynamicPageQuery = async (id: string) =&gt; {<br>  const groqQuery = `*[<br>  _type == &quot;dynamicPage&quot;<br>  &amp;&amp; (_id == &#39;${id}&#39;)]{<br>   id{current},<br>   sections{<br>     _type,<br>     properties,<br>   },<br>   ...<br>  }[0]`<br><br>  const data = await client.fetch(groqQuery);<br><br>  return data;<br>}</pre><p>Start the server and call both of these endpoints with <a href="https://www.postman.com/">Postman</a> or a similar tool to verify that everything works as intended.</p><pre>npx ts-node start.ts<br><br>[server]: Server is running at http://localhost:3000</pre><h4>Building The Dynamic UI</h4><p>Starting with the recent stable version of <a href="https://nodejs.org/en">Node</a>, we’ll use the following command to initialize our application with <a href="https://vitejs.dev/"><em>Vite</em></a>, <a href="https://react.dev/"><em>React</em></a><em> </em>and <em>TypesScript</em>.</p><pre>npm create vite@latest<br><br>&gt; React<br>&gt; TypeScript</pre><p>Once the command is finished, verify everything works by initializing the application.</p><pre>npm run dev</pre><p>This will initialize a local dev-server on http. In order to handle local certificates with Vite, use the <a href="https://github.com/liuweiGL/vite-plugin-mkcert"><em>vite-plugin-mkcert</em></a> with the following configuration options.</p><p>We also utilize this opportunity to install the <em>react-router-dom</em> package.</p><pre><br>npm i react-router-dom<br>npm i -D vite-plugin-mkcert</pre><pre>// vite.config.ts<br>import {defineConfig} from&#39;vite&#39;<br>import mkcert from &#39;vite-plugin-mkcert&#39;<br><br>export default defineConfig({<br>  plugins: [react(), mkcert()]<br>  server: {<br>    https: true<br>  },<br>})</pre><p>The bare bone application should now be up and running on https after initialization, and we can start adding the following structure.</p><pre>|-- features<br>      |--  DynamicPage<br>            |- DynamicPageWrapper.tsx<br>            |- DynamicPage.tsx<br>            |- SectionErrorBoundary.tsx<br>      |-- Sections<br>            |-- SectionOne<br>                  |- SectionOne.tsx<br>                  |- SectionOne.module.scss<br>                  |- index.ts<br>            |-- SectionTwo<br>                  |- SectionTwo.tsx<br>                  |- SectionTwo.module.scss<br>                  |- index.ts<br>      |-- Layout<br>            |- MainContainer.tsx<br>            |- Footer.tsx<br>            |- Header.tsx<br>            |- NotFound.tsx<br>      |- index.ts<br>|-- routes<br>      |- routesConfig.ts<br>|-- interfaces<br>      |- IDynamicSection.ts<br>|- App.tsx</pre><p>Starting with the interfaces, we need to add several of them to handle the dynamic content. The <em>DynamicSectionFinder </em>is an interface for a mapper function, and will be explain in further details later on. The <em>IDynamicRoute </em>is the interface we’ll use for the dynamic routes, and includes a path and properties. The <em>IDynamicSectionProps</em>, <em>IDynamicSection </em>and <em>IDynamicSectionValues</em> are all interfaces related to sections within a dynamic page, and will be made clearer as we move on.</p><pre>// interfaces/IDynamicSectionFinder<br>export type DynamicSectionFinder = <br>  &lt;T&gt;(name: string) =&gt; IDynamicSectionValues&lt;T&gt; | undefined;<br><br>// interfaces/IDynamicRoute<br>export interface IDynamicRoute&lt;Properties = any&gt; {<br>    path: string;<br>    properties: Properties;<br>}<br><br>// interfaces/IDynamicSection<br>export interface IDynamicSectionProps&lt;T&gt; {<br>    properties: T;<br>}<br><br>// interfaces/IDynamicSection<br>export interface IDynamicSection&lt;Properties&gt; {<br>    name: string;<br>    displayComponent: React.ComponentType&lt;IDynamicSectionProps&lt;Properties&gt;&gt;;<br>}<br><br>// interfaces/IDynamicSectionValues<br>export interface IDynamicSectionValues&lt;Properties = any&gt; {<br>    _type: string;<br>    properties: Properties;<br>}</pre><p>Moving on to the <em>routesConfig.ts </em>file, add the following content inside.</p><pre>import {NotFound} from &quot;../features/NotFound/NotFound.tsx&quot;<br><br>export const routesConfig = [<br>  {<br>    path: &quot;*&quot;,<br>    element: &lt;NotFound /&gt;<br>  },<br>]</pre><p>Yes, only <strong>one </strong>route for now, as the other ones will be added dynamically.</p><p>Then we move over to the deepest level of our dynamic structure, the sections. Starting with <em>SectionOne- </em>and <em>Two</em>, add the following content.</p><pre>// features/sections/SectionOne/SectionOne.tsx<br>import { IDynamicSectionProps } from &quot;../../../interfaces/IDynamicSection&quot;;<br><br>export interface ISectionOne {<br>  heading: string;<br>}<br><br>export const SectionOne = ({<br>  properties,<br>}: IDynamicSectionProps&lt;ISectionOne&gt;) =&gt; {<br>  const { heading } = properties;<br>  return &lt;h1&gt;{heading}&lt;/h1&gt;;<br>};<br><br>// features/sections/SectionTwo/SectionTwo.tsx<br>import { IDynamicSectionProps } from &quot;../../../interfaces/IDynamicSection&quot;;<br><br>export interface ISectionTwo {<br>  heading: string;<br>}<br><br>export const SectionTwo = ({<br>  properties,<br>}: IDynamicSectionProps&lt;ISectionTwo&gt;) =&gt; {<br>  const { heading } = properties;<br>  return &lt;h1&gt;{heading}&lt;/h1&gt;;<br>};</pre><p>Now that we’ve added our sections, we’ll move over to the <em>index </em>file of each section.</p><pre>// features/Sections/SectionOne/index.ts<br>import { IDynamicSection } from &quot;../../../interfaces/IDynamicSection&quot;<br>import {SectionOne, ISectionOne} from &quot;./SectionOne&quot;<br><br>const sectionOne: IDynamicSection&lt;ISectionOne&gt; = {<br>  name: &quot;sectionOne&quot;,<br>  displayComponent: SectionOne<br>}<br><br>export default sectionOne<br><br><br>// features/Sections/SectionTwo/index.ts<br>import { IDynamicSection } from &quot;../../../interfaces/IDynamicSection&quot;<br>import {SectionTwo, ISectionTwo} from &quot;./SectionTwo&quot;<br><br>const sectionTwo: IDynamicSection&lt;ISectionTwo&gt; = {<br>  name: &quot;sectionTwo&quot;,<br>  displayComponent: SectionTwo<br>}<br><br>export default sectionTwo</pre><p>You can see that we’ve defined a name for the section along with the <em>displayComponent</em> property which are referencing the component.</p><p>Then we need to create a mapper function, to be able to retrieve the section depending on the name.</p><pre>// features/Sections/index.ts<br>import {IDynamicSection} from &quot;../../interfaces/IDynamicSection&quot;<br><br>import sectionOne from &quot;./SectionOne&quot;<br>import sectionTwo from &quot;./SectionTwo&quot;<br><br>export const appSections: {[key: string]: IDynamicSection&lt;any&gt;} = {<br>  [sectionOne.name]: sectionOne,<br>  [sectionTwo.name]: sectionTwo<br>}<br><br>export const findSectionByName = (name: string) =&gt; appSections[name];</pre><p>Then we move on to the <em>DynamicPage </em>component, responsible of rendering each section.</p><pre>// features/DynamicPage/DynamicPage.tsx<br>import React from &quot;react&quot;;<br>import { useLocation, useNavigate, useParams } from &quot;react-router-dom&quot;;<br>import { IDynamicSectionValues } from &quot;../../interfaces/IDynamicSection&quot;;<br>import { IDynamicPage } from &quot;../../interfaces/IDynamicPage&quot;;<br>import { SectionErrorBoundary } from &quot;./SectionErrorBoundary&quot;;<br>import { findSectionByName } from &quot;../Sections&quot;;<br><br>interface RenderSectionErrorProps {<br>  title: string;<br>  message: string;<br>  section: IDynamicSectionValues;<br>}<br><br>const RenderSectionError = (props: RenderSectionErrorProps) =&gt; (<br>  &lt;div&gt;<br>    &lt;h2&gt;{props.title}&lt;/h2&gt;<br>    &lt;p&gt;{props.message}&lt;/p&gt;<br>    &lt;h3&gt;Section&lt;/h3&gt;<br>    &lt;pre&gt;<br>      &lt;code&gt;{JSON.stringify(props.section, null, 2)}&lt;/code&gt;<br>    &lt;/pre&gt;<br>  &lt;/div&gt;<br>);<br><br>export interface IDynamicPageProps {<br>  dynamicPage: IDynamicPage;<br>  showHandlerNotFoundError?: boolean;<br>  showGenericSectionErrors?: boolean;<br>}<br><br>export const DynamicPage = (props: IDynamicPageProps) =&gt; {<br>  const { showHandlerNotFoundError = true, showGenericSectionErrors = true } =<br>    props;<br><br>  const navigate = useNavigate();<br>  const location = useLocation();<br>  const params = useParams();<br><br>  const RenderSection = (section: IDynamicSectionValues) =&gt; {<br>    try {<br>      const sectionHandler = findSectionByName(section._type);<br><br>      if (!sectionHandler) {<br>        console.error(&quot;SectionHandler not found for&quot;, section._type);<br>        return showHandlerNotFoundError ? (<br>          &lt;RenderSectionError<br>            title=&quot;Not found&quot;<br>            message=&quot;The section was not found&quot;<br>            section={section}<br>          /&gt;<br>        ) : null;<br>      }<br><br>      const sectionProps = {<br>        navigate,<br>        location,<br>        params,<br>        properties: section.properties || {},<br>      };<br><br>      const SectionHandler =<br>        sectionHandler.displayComponent as React.ElementType;<br><br>      return (<br>        &lt;SectionErrorBoundary&gt;<br>          &lt;SectionHandler {...sectionProps} /&gt;<br>        &lt;/SectionErrorBoundary&gt;<br>      );<br>    } catch (error) {<br>      console.error(&quot;Error rendering DynamicPage section&quot;, section, error);<br><br>      return showGenericSectionErrors &amp;&amp; error instanceof Error ? (<br>        &lt;RenderSectionError<br>          section={section}<br>          title=&quot;Render error (check console)&quot;<br>          message={error.message}<br>        /&gt;<br>      ) : null;<br>    }<br>  };<br><br>  return (<br>    &lt;article data-page-id={props.dynamicPage.id}&gt;<br>      {(props.dynamicPage.sections || []).map((section, idx) =&gt; (<br>        &lt;React.Fragment key={idx}&gt;<br>          &lt;RenderSection {...section} /&gt;<br>        &lt;/React.Fragment&gt;<br>      ))}<br>    &lt;/article&gt;<br>  );<br>};</pre><p>We start out by adding the <em>RenderSectionError </em>component, which is a component we’ll display when there’s a problem rendering a section. This component will contain some information about which section has trouble rendering, along with the associated <em>JSON </em>output for debugging purposes.</p><p>So the <em>DynamicPage</em> component have a component within - <em>RenderSection</em>. The <em>RenderSection </em>component is, as the name states, responsible of rendering a section, and accepts a section-data retrieved from Sanity. Then, within a try-catch block, we use the <em>sectionFinder mapping fn </em>to find the specific section.</p><p>In addition to the props we forward for each section, we include some additional meta information for each page. The <em>displayComponent </em>is then retrieved from the sectionHandler and returned.</p><p>One level above the <em>DynamicPage </em>we’ve now created is the <em>DynamicPageWrapper</em>.</p><pre><br>// features/DynamicPage/DynamicPageWrapper.tsx<br>import { useEffect, useState } from &quot;react&quot;;<br>import { IDynamicRoute } from &quot;../../interfaces/IDynamicRoute&quot;;<br>import { DynamicPage, IDynamicPageProps } from &quot;./DynamicPage&quot;;<br>import { NotFound } from &quot;../Layout/NotFound&quot;;<br><br>interface IDynamicPageWrapperProps {<br>  route: IDynamicRoute;<br>}<br>const DynamicPageWrapper = (props: IDynamicPageWrapperProps) =&gt; {<br>  const pageId: string = props.route.properties.page._ref;<br>  const [dynamicPage, setDynamicPage] = useState(null);<br>  const [isLoading, setIsLoading] = useState(true);<br><br>  async function fetchDynamicPage(id: string) {<br>    return fetch(`http://localhost:3000/api/v1/dynamicPage/${id}`)<br>      .then((response) =&gt; response.json())<br>      .then((data) =&gt; {<br>        setDynamicPage(data);<br>      })<br>      .finally(() =&gt; setIsLoading(false));<br>  }<br><br>  useEffect(() =&gt; {<br>    if (!dynamicPage) {<br>      fetchDynamicPage(pageId);<br>    } else {<br>      setIsLoading(false);<br>    }<br>  }, []);<br><br>  const RenderPage = () =&gt; {<br>    if (isLoading) {<br>      return &lt;p&gt;Loading...&lt;/p&gt;;<br>    }<br><br>    if (!dynamicPage) {<br>      return &lt;NotFound /&gt;;<br>    }<br><br>    const newProps: IDynamicPageProps = {<br>      dynamicPage,<br>    };<br><br>    return &lt;DynamicPage {...newProps} /&gt;;<br>  };<br><br>  return &lt;RenderPage /&gt;;<br>};<br><br>export default DynamicPageWrapper;</pre><p>This component has a reference to the page being rendered, which is used to retrieve it’s content through a fetch request. The result of this request along with the <em>sectionFinder fn</em> is then passed down to the <em>DynamicPage </em>as props.</p><p>The content of the <em>Layout</em> folder will act as the static wrapper of our dynamic content.</p><pre>// features/Layout/Footer.tsx<br>export const Footer = () =&gt; {<br>  return &lt;footer&gt;Static Footer&lt;/footer&gt;<br>}<br><br>// features/Layout/Header.tsx<br>export const Header = () =&gt; {<br>  return &lt;header&gt;Static Header&lt;/header&gt;<br>}<br><br>// features/Layout/MainContainer.tsx<br>export const MainContainer = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;Header /&gt;<br>      &lt;Outlet /&gt;<br>      &lt;Footer /&gt;<br>    &lt;/&gt;  <br>  )<br>}</pre><p>And to finish it all up is the <em>App</em> component.</p><pre>// App.tsx<br>import { useEffect, useState } from &quot;react&quot;;<br>import &quot;./App.css&quot;;<br>import { IDynamicRoute } from &quot;./interfaces/IDynamicRoute&quot;;<br>import DynamicPageWrapper from &quot;./features/DynamicPage/DynamicPageWrapper&quot;;<br>import { RouterProvider, createBrowserRouter } from &quot;react-router-dom&quot;;<br>import { MainContainer } from &quot;./features/Layout/MainContainer&quot;;<br>import { routesConfig } from &quot;./routes/routesConfig&quot;;<br><br>interface IRouteHandlerProps {<br>  route: IDynamicRoute;<br>}<br><br>async function fetchRoutes() {<br>  return fetch(&quot;http://localhost:3000/api/v1/dynamicRoutes&quot;)<br>    .then((response) =&gt; response.json())<br>    .then((data) =&gt; data)<br>    .catch((error) =&gt; console.error(&quot;Error:&quot;, error));<br>}<br><br>function App() {<br>  const [routes, setRoutes] = useState([]);<br><br>  const renderRoute =<br>    (route: IDynamicRoute): React.ElementType =&gt;<br>    (routeProps: IRouteHandlerProps) =&gt; {<br>      return &lt;DynamicPageWrapper {...routeProps} route={route} /&gt;;<br>    };<br><br>  const RenderDynamicRoutes = routes.map((route: IDynamicRoute) =&gt; {<br>    const currentRoute = route.path.toString();<br>    const RenderedRoute = renderRoute(route);<br><br>    return {<br>      path: currentRoute,<br>      element: &lt;RenderedRoute /&gt;,<br>    };<br>  });<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      const data = await fetchRoutes();<br>      setRoutes(data.routes);<br>    };<br><br>    fetchData();<br>  }, []);<br><br>  return (<br>    &lt;RouterProvider<br>      router={createBrowserRouter([<br>        {<br>          path: &quot;/&quot;,<br>          element: &lt;MainContainer /&gt;,<br>          children: [...RenderDynamicRoutes, ...routesConfig],<br>          errorElement: &lt;div&gt;ERROR&lt;/div&gt;,<br>        },<br>      ])}<br>      fallbackElement={<br>        &lt;div&gt;<br>          &lt;span&gt;Loading...&lt;/span&gt;<br>        &lt;/div&gt;<br>      }<br>    /&gt;<br>  );<br>}<br><br>export default App;</pre><p>So, we retrieve the routes through a fetch request, which is then added to the component state. Then we have the <em>RouteProvider </em>from React Router which uses the <em>createBrowserRouter </em>method to construct our dynamic routes with the <em>RenderDynamicRoutes </em>mapper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8HKC7uMk_byaP4a59WzQA.png" /><figcaption>Screenshot of the end result</figcaption></figure><p><em>My name is Mathis Garberg, and I am a consultant at </em><a href="https://www.dfindconsulting.no/"><em>Dfind Consulting</em></a><em> in Oslo, Norway.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2418219b761" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/build-a-completely-dynamic-ui-with-sanity-a-node-server-and-react-f2418219b761">Build a Completely Dynamic UI with Sanity, a Node Server and React</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing The Right File Structure for Angular in 2020 and Beyond !]]></title>
            <link>https://itnext.io/choosing-the-right-file-structure-for-angular-in-2020-and-beyond-a53a71f7eb05?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a53a71f7eb05</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Tue, 11 Feb 2020 21:21:57 GMT</pubDate>
            <atom:updated>2020-02-19T06:16:49.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wJDKbEvnWrrgcP84.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/8EzNkvLQosk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maarten van den Heuvel</a> on <a href="https://unsplash.com/search/photos/structure?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>The code associated with this article is available on </em><a href="https://github.com/mathisGarberg/angular-ngxs-and-material-starter"><em>GitHub</em></a><em>. There still needs to be some additions, but it follows the same pattern as described here.</em></p><p>In 2018, I wrote the article <a href="https://itnext.io/choosing-a-highly-scalable-folder-structure-in-angular-d987de65ec7"><strong>How to define a highly scalable folder structure for your Angular project</strong></a>. Since then, two years have pasted, and there’s been several changes in the Angular landscape. We’ve seen onPush change detection, the providedIn decorator being added,exportable directives and several other updates to the Angular core framework as a whole, leaving us at version 9 at the time of writing.</p><p>This fast-pasted release-cycle from the Angular team has brought us some great new features, but it does also mean that we need to make some structural changes on our own. In the light of these changes and frequently asked questions from the original article, I’ve decided to create a new one, which answers all of them.</p><p>Welcome to Choosing The Right File Structure for Angular in 2020 and Beyond!</p><h3>Introduction</h3><p>When working in a large team with many developers that are responsible for the same codebase, having a common understanding of how the application should be structured is vital. The time spent arguing over architectural decisions takes up a large portion of our day to day operations, and having a common understanding comes a long way in solving them.</p><p>The goal of this article is to help those developers by proposing a scalable and maintainable structure for medium to large applications. We’ll explore the structure in the context of the Angular documentation by using their statement to further highlight the advantages here.</p><p><em>Note! There’s almost impossible to find a structure that suits every single use-case. The structure of an application will change a lot depending on the project, and there’s no blueprint here. This article aims to improve the development process by </em><strong><em>proposing </em></strong><em>a structure that should work well for medium to large applications.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43a23f4a096c6a07656d8ca5004b24a6/href">https://medium.com/media/43a23f4a096c6a07656d8ca5004b24a6/href</a></iframe><blockquote>Have a near-term view of implementation and a long-term vision. Start small but keep in mind where the app is heading down the road.</blockquote><blockquote>All of the app’s code goes in a folder named src.</blockquote><blockquote>Do structure the app such that you can Locate code quickly, Identify the code at a glance, keep the Flattest structure you can, and Try to be DRY, but not on the expense of readability.</blockquote><blockquote>Do name the file such that you instantly know what it contains and represents.</blockquote><blockquote>Do keep a flat folder structure as long as possible.</blockquote><p>The ng new command from the Angular CLI provides us with an initial skeleton structure at the root level of the application and is easy to run and build on top of. This default behavior is suitable for new applications, and is the perfect entry point for the structure. You should use the Angular schematics to generate the files in the appropriate areas.</p><h3>The App Module</h3><blockquote>Do create an NgModule in the app’s root folder, for example, in /src/app.</blockquote><p>In Angular, everything is organized in modules, and every application have at least one of them, the app root module. The app module is the entry point of the application, and is the module that Angular uses to bootstrap the application. The setup instructions when creating a new application produces a minimal AppModule with a single component. You’ll evolve this module as the application grows.</p><h3>The Core Module</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/068d9cbbb9ce794c963176628bad3d98/href">https://medium.com/media/068d9cbbb9ce794c963176628bad3d98/href</a></iframe><p>The CoreModule takes on the role of the app root module, but is not the module that gets bootstrapped by Angular at run-time. The common denominator between the files present here is that we only need to load them once, and that is at run-time, which makes them singleton. The module contains root-scoped services, static components like the navbar and footer, interceptors, guard, constants, enums, utils, and universal models. To prevent re-importing the module elsewhere, we should add a module-import-guard in it’s constructor method.</p><h3>The Shared Module</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f425a8504d0d8f8014bae515a04cd948/href">https://medium.com/media/f425a8504d0d8f8014bae515a04cd948/href</a></iframe><blockquote>Do create a feature module named SharedModule in a shared folder; for example, app/shared/shared.module.ts defines SharedModule.</blockquote><blockquote>Do declare components, directives, and pipes in a shared module when those items will be re-used and referenced by the components declared in other feature modules.</blockquote><blockquote>Do declare all components, directives, and pipes in the SharedModule.</blockquote><blockquote>Do export all symbols from the SharedModule that other feature modules need to use.</blockquote><p>When working on large applications, the Angular team suggest us to consider lazy loading of our modules. This decreases the bundle size of our application and therefore the initial build-time, and this is where the SharedModule truly shines.</p><p>The SharedModule allows us to organize and streamline our code. The shared module shouldn’t have any dependency to the rest of the application, and should therefore not rely on any other module. It should contain all the reusable modules, lazy loaded feature modules required to operate. You should add commonly used directives, pipes and components here. Many third-party libraries are available as NgModules such as <a href="https://material.angular.io/">Material Design</a>, and exposing them through the SharedModule might be a good idea.</p><p>We can easily publish and share these components between applications.</p><h3>The Feature Modules</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b87890a6fb0ed0b466b1778557b0d41f/href">https://medium.com/media/b87890a6fb0ed0b466b1778557b0d41f/href</a></iframe><blockquote>Do create an NgModule for all distinct features in an application; for example, a <em>Heroes</em> feature. All feature areas are in their own folder, with their own NgModule.</blockquote><blockquote>Do place the feature module in the same named folder as the feature area; for example, in <em>app/heroes</em>.</blockquote><blockquote>Do name the feature module file reflecting the name of the feature area and folder; for example, <em>app/heroes/heroes.module.ts</em>.</blockquote><blockquote>Do name the feature module symbol reflecting the name of the feature area, folder, and file; for example, <em>app/heroes/heroes.module.ts</em> defines <em>HeroesModule</em>.</blockquote><p>The initial Angular application does only have one single module, which works great for small applications. But as the application grows, you’ll need to consider subdividing it into multiple feature modules, some which can be lazy loaded. These modules should only depend on the SharedModule, and their functionality should be scoped to the module.</p><p>Feature modules deliver user experience dedicated to a particular application feature like the user- or the administration-part of the app. We’re grouping the components, services, models and other functionality that belongs together. They typically have a top component that acts as the feature root and private, supporting sub-components descend from it. They might be imported by the root AppModule of a small application that lacks routing or need to show some initial content, but can also be lazy loaded with references in the app routing file.</p><p>Domain feature modules rarely have providers, but when they do, the lifetime of the provided services should be the same as the lifetime of the module. Beginning with Angular 6.0, the preferred way pf creating a singleton is to set providedIn to root on the service’ @Injectable decorator. This tells Angular to provide the service in the application root. But we can also use this</p><p>to create a singleton service is to set <a href="https://angular.io/api/core/Injectable#providedIn">providedIn</a> to root on the service&#39;s @<a href="https://angular.io/api/core/Injectable">Injectable</a>() decorator. This tells Angular to provide the service in the application root. We can use this in the context of a feature by using the providedIn property on the module instead, resulting in an error when using it elsewhere.</p><p>When you need the service in other modules as well, it probably belongs in the CoreModule’ service’s declaration instead.</p><h3>Styles</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9b5b7b3858f7e03f764f222b3cbb909/href">https://medium.com/media/c9b5b7b3858f7e03f764f222b3cbb909/href</a></iframe><p>In a similar way to how we want to avoid bloating up the AppModule as the application grows, it’s also true for the styles.scss file.You should instead create a styles folder, which contains mixins or css-functions, responsible for their own areas. These files are then imported in the appropriate order inside the styles.scss file, providing their global styles to the rest of the app. Create mixins for reusable css-snippets, and scope the associated logic together.</p><h3>Assets</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df6e1f1cbe3de912e3b7929f698fe89b/href">https://medium.com/media/df6e1f1cbe3de912e3b7929f698fe89b/href</a></iframe><p>The assets folder is generated for us by the Angular CLI with the ng new command, and is the perfect place for storing all our media files. Using it in combination with a PathLocationStrategy gives easily referable files across the app. This folder persists at build time.</p><h3>Going Beyond!</h3><p>Even though the structure described above solves a lot of problems, we’ve still left out one big area, and that is state management in Angular. The reason for this is that there’s so many different ways to solve this exact problem, and one solution might not apply to another. The context of <a href="https://material.angular.io/">Angular Material</a> and other component libraries are another area that will define large areas of the application structure. The context of The emergence of <a href="https://nrwl.io/">Nrwl </a>with micro-frontends have also gained hype. Would you like to see this kind of article of some point, please let me know.</p><h3>Summary</h3><p>Choosing an appropriate folder structure is not an easy task. You need to agree with the team on the structure that suits the application, and what might suit one need, might not suit another. Should hopefully be valid for the next years to come. What would you do differently to ensure a good, maintainable structure?</p><p><em>My name is Mathis Garberg, a consultant at </em><a href="https://www.dfindconsulting.no/"><em>Dfind Consulting</em></a><em> in Oslo, Norway. Living in Norway and need some Angular expertise? Feel free to reach out!</em></p><p>You can check out my other Angular articles and/or subscribe to me to be one step further, and/or if you like the story, a 👏 is always appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a53a71f7eb05" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/choosing-the-right-file-structure-for-angular-in-2020-and-beyond-a53a71f7eb05">Choosing The Right File Structure for Angular in 2020 and Beyond 📕!</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nordic.js 2019 — A Personal Review]]></title>
            <link>https://medium.com/@mathis.garberg/nordic-js-2019-a-personal-review-c1d702b464dd?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1d702b464dd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Wed, 16 Oct 2019 15:47:51 GMT</pubDate>
            <atom:updated>2019-10-28T07:17:28.673Z</atom:updated>
            <content:encoded><![CDATA[<h3>Nordic.js 2019 — A Personal Review</h3><h4>A place for code and great experiences</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQXnmsh-hjXxKDP9q3FYrg.png" /><figcaption>Photo by Yours Truly 📷</figcaption></figure><h4>Introduction</h4><p>One of the great benefits of working for <a href="https://www.dfindconsulting.no/om-oss">Dfind Consulting</a> agency is being able to attend international conferences through a development budget. This budget is reserved for educational content and experiences in the consultant’ respective fields.</p><p>Since the development budget is renewed each year, and this year is nearly coming to an end, I was happy to see there still was some good conferences left to choose from.</p><p>This was my first international conferences, and what better way to kick things off than in beautiful Stockholm, Sweden, with it’s very well-known JavaScript-conference, Nordic.js.<br>So with my travel-gear packed and curiosity and enthusiasm in my mind, I found myself on a plane to Stockholm ✈️</p><h4>The Conference</h4><p>Nordic.js follows a single track format with 8–10 talks a day, and a focus on high quality talks in an open environment. This format allows the audience to concentrate on the moment, without the fear of missing out, which is a huge disadvantage with multi -track conferences.</p><p>We did also have a fair amount of breaks, with a good amount of time to process what we&#39;ve d just learned. Sitting down on a conference for eight straight hours and listen to people speak can be tiresome, and the organizers understood the importance of that.</p><p>With talks from internationally renowned speakers and other rising stars in the JavaScript community, huge expectations are set. I’m happy to say that everyone who entered the main stage delivered.<br>The talks were extremely well balanced, both in gender of presenters and in terms of balance of topics. The technical ones were predominating and there were very interesting talks which aren’t focused to technical detail, but enlighten human parts of our work life.</p><p><em>All talks should now be available on the </em><a href="https://www.youtube.com/user/nordicjs"><em>Nordic.js youtube channel</em></a><em>!</em></p><p>Here is an overview of all the presenters with some additional text on my personal highlights.</p><ul><li><strong>Mark Volkmann — Simplify Web App Development with Svelte</strong> 😲</li></ul><p><a href="https://svelte.dev/">Svelte</a> is one of those framework almost all of us have heard of, but never gotten to use. This talk explained how to get started with Svelte, a review of the most important features and a walk through of an example app.</p><ul><li><strong>Fernando Via Canel — Universal Components &amp; Deterministic Rendering </strong>😲</li></ul><p>With Angular being a main part of my work-life, seeing how other popular frameworks solve similar issues has always fascinated me. This talk took this one step further by utilizing React Native to get the application working on <strong>multiple</strong> platforms.</p><ul><li><strong>Piérre Reimertz — Gettin’ into the (Tensor)Flow </strong>😲</li></ul><p>Constructing web application and acting upon several user actions in an automated fashion might seem like a far-fetched idea, specially in the JavaScript community. This talk explains the basics of machine learning through the raising popular library, <a href="https://www.tensorflow.org/js">Tensorflow.js</a>. The visual presentation of each concept was also beautifully highlighted.</p><ul><li><strong>Godfrey Chan — Thinking in TypeScript</strong>😲</li></ul><p>TypeScript is reaching new heights of popularity. <strong>We </strong>use it every day, and it provides a seamless experience with some great benefits. “Thinking in TypeScript” explores the benefits of TypeScript in our development workflow to improve scalability and design better APIs.</p><ul><li><strong>Robert Zhu — Full Stack Type Safety with React, GraphQL and TypeScript </strong>😲</li></ul><p>One might think TypeScript on the client is good. But what if this awesome tool could be available across the <strong>entire</strong> stack?! This talk gives a detailed walk-through of his personal development setup with type-safety in mind.</p><ul><li><strong>Sara Vieira — Building dumb sh*t</strong> 😂</li></ul><p>When we learn something we make to-do lists, we make useful things. This talks focuses on doing the exact opposite by learning and motivate through building dumb, useless things.</p><h4>Socializing &amp; Networking 👋</h4><p>With nearly 1000- developers, designers and other creators heading to Stockholm for the event, and both structured and informal networking sessions provided, it’s a brilliant opportunity for you and your team to establish new connections and make new friends. Nordic.js had gone to great extent to create an including atmosphere where people feel welcomed and loved. The diverse group of presenters and attendees is a testimony to that.</p><h4>The Venue 🏠</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ucHCyAiQMvuqm2eK.jpg" /><figcaption>Magasin 9 at night</figcaption></figure><p>The conference was hosted in Stockholm, at <a href="https://www.magasin9.se/">Magasin 9</a>, in an old industrial building normally used for concerts and other big events. This was a nice location for the conference, and the production that surrounded it was of really high quality. <br>Sitting all day in a room listening to speaker after speaker can be challenging. The organizers realized this and they break up the day with activities. Between each session, during the break, attendees surrounded the booths across the venue. With a huge ball pit, multiple table tennis boards and even a sauna with bathrobes for rent, running out of things to do during the breaks never became an issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTAC6uTxwF9cuZoRu4aZTQ.png" /><figcaption>Spent some time at the LEGO-station, and this is what I ended up with.</figcaption></figure><h4>The Food 🌿</h4><p>Food was delivered by the Swedish catering company <a href="http://joppesfood.se/jf/en/home-2/">Joppes food</a>, and was without animals or animal-derived products. Serving an audience of almost 1000 people needs a huge amount of effort, and I was unfortunately not that happy about the food. Maybe I’m just picky.</p><h4>The Party 🎉</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w52TQUMdpCDjva-z.jpg" /><figcaption>The light indicates which music people listen to</figcaption></figure><p>A very special highlight was the party after the second conference day. Putting a stronger focus on enabling conference attendees to connect and meet with other conference attendees in a playful and fun atmosphere. There were VR, board games, Silent Disco and other cool interactive experiences.</p><h4>Code in the dark 🌑</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pY6tw0o3vPjrIkjY" /><figcaption>Image by Nordic.js</figcaption></figure><p>Code in the Dark is a competition where front-end development meets smoke machines and lasers. Given a screenshot of a website, the contestants have 15 minutes to replicate it using HTML/CSS, without previewing the result. The winner in each heat is decided by the audience. The competition continues until there’s only one contestant left — the Champion of the Dark. Shout out to <strong>John</strong>, a contender I randomly met at breakfast at Scandic Ariadne, who manged to reach the final.</p><h4>Conclusion</h4><p>This was my first time attending Nordic.js. Besides the talks, I especially was delighted by the social aspects of this conference attendance. Thanks to the folks for organizing Nordic.js and all the people for the nice conversations and your openness. See you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1d702b464dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Read Code?]]></title>
            <link>https://itnext.io/how-to-read-code-bf478c262932?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf478c262932</guid>
            <category><![CDATA[read-code]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[readable-code]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Sat, 03 Aug 2019 11:27:13 GMT</pubDate>
            <atom:updated>2024-08-05T19:13:37.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*10w1Rl085BACdXf0xvUDqA.jpeg" /></figure><h3>Background</h3><p>As developers, we spend the majority of our time reading and trying to understand someone else’s code. Specially in the consultant industry, you’re introduced to several enterprise solutions with a large existing codebase, where you’re now the maintainer, expected to provide deliverables on a timeline of code you didn’t write. This can be challenging for even the most experienced developers, and you will need good code-browsing skills to make sense of the code.</p><p>By utilizing a few popular code-browsing techniques I’ll explain throughout this article, you’ll soon know everything you need to approach a large existing codebase.</p><h3>The Problem</h3><p>In ideal world, all code would be well written, documented, structured and comprehensibly tested, both with automatic tools such as unit tests and end-to-end tests.</p><p>However, we don’t live in an ideal world. We live in the real world, where code never dies and programmers come and go, which leads to people spending an enourmous amount of time reading code. This makes understanding unfamiliar code all the more important. Probably more important than writing code.</p><p>Unfortunately, this skill is widely undertaught in school and not that well-recognized in the industry, which leads to people reading programs like they were books, trying to connect every piece of the puzzle.</p><p>This is not the right frame of mind. You don’t want to think of the scope to which you don’t understand something, but instead, gradually start connecting the pieces until they fit.</p><h3>The Solution</h3><p>So, what are you going to do when you’re faced with a brand new codebase?</p><p>Requirement gathering is usually the first stage in any big project, and talking with the prospective users of the system is always an important part of that. In order to fix the program, you first need to understand the problems it’s trying to solve. There’s usually a reason for why things are done a certain way. Remember. Dealing with other people’s code is the norm, not the exception, and becoming adept and figuring out how the other programmers worked are an important part of that. By adopting their style when continuing their work, you’ll also make it easier for the next developer to follow.</p><h4>Exploring The Scope</h4><p>When we know something about the purpose and style the application is developed in, it’s time to start breaking things down. We need to narrow things down to something we can actually process. By understanding the various components in the software, and how they relate to each other, you’ll start figuring out how different parts are connected and start developing an understanding of the codebase as a whole.</p><h4>Breaking Things Down</h4><p>So, how do we start breaking things down? One method the community strongly suggests is to set out breakpoint on methods that triggers behaviours that concerns you. If changing a line of code causes unexpected changes on other places, put a breakpoint on that line, and see what happens. You have a lot of information on the runtime state once the breakpoint hits. Breakpoints stops the execution of the code on a certain line, and from there, you can see from the stacktrace how the code got there. Use the step into and step out functions to see what the different methods does and how events are propogated in the application. This will teach you something about the structure of the codebase.</p><h4>Bookmarks</h4><p>One other method I’ve recently started to adopt is adding some sort of bookmarks above methods that triggers behavior that affects the functionallity I’m exploring. This will guide you through the debugging process, and reduce the time spent searching for methods over and over again.</p><p><em>You can check out the VS Code Bookmark extension </em><a href="https://marketplace.visualstudio.com/items?itemName=alefragnani.Bookmarks"><em>here</em></a><em>.</em></p><h4>Writing and Understanding Tests</h4><p>One other thing I also need to mention is the importance of testing. Cause although they are rare, they’re a great resource for learning what certain unit of code is meant to do. By reading and writing tests, you’ll start understanding the expected behavior of the program, and can then compare that with the actual result.</p><p>The more of those you build, the more confidence you’ll have that your added code won’t break something else.</p><h3>Summary</h3><ul><li>Start by gathering information about which problems the program should solve and which code style to adapt.</li><li>Don’t spend all your time figuring out how everything works at the beginning. Narrow things down to something you can actually process.</li><li>Step through behavior that concerns you with a debugger. The stack trace have a lot of information about how events are propogated in the application.</li><li>Although testing is rare, it acts as a wonderful documentation tool, and is a good introduction to a new codebase.</li></ul><p>On a final note, I really would like you to share you’re best methods for approaching unfamiliar code. This is a widely discussed topic, and there is no blueprint here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*7hVKnCb9TtSwe547.png" /></figure><p>Just don’t spend all your time explaining your problems to a rubber duck. People will think you’re insane 😉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf478c262932" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-read-code-bf478c262932">How To Read Code?</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code Checklist in Angular ✔️]]></title>
            <link>https://itnext.io/clean-code-checklist-in-angular-%EF%B8%8F-10d4db877f74?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/10d4db877f74</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 13:58:58 GMT</pubDate>
            <atom:updated>2019-10-26T17:29:36.482Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*XZiWn4Ej-ZfJ6Pxj-b9AkQ.png" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/search/photos/structure?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>Angular has rapidly grown to become one of the most popular frameworks for building front-end, cross-platform web applications. It gives you a lot of the out-of-the-box features, such as a routing system, a dependency injection framework, forms handling, etc. Angular also enforces you to use both TypeScript and RxJS, since its already part of the Angular ecosystem. This extensive width of features makes Angular a good candidate for large enterprise solutions.</p><p>While Angular is an extremely powerful framework with a broad toolkit, it’s hard to master, especially if it’s your first JavaScript framework. In an attempt to reduce complexity, I decided to put together a clean code checklist which covers my personal recommendations for writing clean and production-ready Angular code.</p><h3><strong>Background</strong></h3><p>As we become better developers, structuring and organizing code becomes more and more important. We want to write code that improves readability, scalability, maintainability and performance, and minimizes the time spent debugging.</p><p>As <strong>Martin Golding</strong> stated:</p><blockquote>Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.</blockquote><p>Sounds disturbing, but it doesn’t make the message any less true. Programmers are really authors and other developers are their target audience. The time spent attempting to understand someone else’s code takes up large portion of our day to day operations. We should therefore consciously try to improve the quality of our code. It’s essential for creating a successful, maintainable product.</p><h3><strong>Style Guide</strong></h3><p>The logical place to start looking for best practices in Angular is the <a href="https://angular.io/guide/styleguide">Angular Style Guide</a>. This is an opinionated guide on syntax, conventions, and application structuring. The style guide presents preferred conventions and explains with examples why you should use them.</p><h3>Angular CLI</h3><p>The <a href="https://cli.angular.io/">Angular CLI</a> is a great tool for creating and working with Angular applications. It increases productivity by taking away the tedious work of creating each file manually. With only a few commands, you’re able to:</p><ul><li>Create a project from scratch</li><li>Scaffold components, directives and services</li><li>Lint your code</li><li>Serve the application</li><li>Run unit- and end to end tests</li></ul><p>You can find more information about the Angular CLI <a href="https://www.intertech.com/Blog/angular-tutorial-getting-started-with-the-angular-cli/">here</a>.</p><h3><strong>Folder Structure</strong></h3><p>As the application grows in size, it’s important to have a structure in place that allows for easy management and maintenance of your code base. Whichever structure you decide to use, it’s important to be consistent and choose a structure the entire team is happy with.</p><p>The article “<a href="https://itnext.io/choosing-a-highly-scalable-folder-structure-in-angular-d987de65ec7">How to define a highly scalable folder structure for your Angular project</a>” discusses these topics, and can be used as a reference point when deciding on your own structure.</p><h3><strong>Write Readable Code</strong></h3><p>If you want the refactoring to be as efficient as possible, it’s important to have readable code. Readable code is easier to understand, which makes it easy to debug, maintain and extend.</p><h4><strong>File names</strong></h4><p>While adding new files, pay attention to the file-names you decide to use. File names should be consistent and describe the feature by dot separation.</p><pre>|-- my-feature.component.ts<br>or<br>|-- my-service.service.ts</pre><h4><strong>Variable- and function names</strong></h4><p>You need to name the variables and functions so the next developer understands them. Be descriptive and use meaningful names — clarity over brevity<em>.</em></p><p>This will help us avoid writing functions like this:</p><pre>function div(x, y)) {<br> const val = x / y;<br> return val;<br>}</pre><p>And hopefully more like this:</p><pre>function divide(divident, divisor) {<br>  const quotient = divident / divisor;<br>  return quotient;<br>}</pre><h4><strong>Write Small pure functions</strong></h4><p>When we write functions to execute some business logic, we should keep them small and clean. Small functions are easier to test and maintain. When you start noticing that your function is getting long and cluttered, it’s probably a good idea to abstract some of the logic to a new one.</p><p>This avoids functions like this:</p><pre>addOrUpdateData(data: Data, status: boolean) {<br>  if (status) {<br>    return this.http.post&lt;Data&gt;(url, data)<br>      .pipe(this.catchHttpErrors());<br>  }<br>  return this.http.put&lt;Data&gt;(`${url}/${data.id}`, data)<br>    .pipe(this.catchHttpErrors());<br>  }<br>}</pre><p>And hopefully more like this:</p><pre>addData(data: Data) {<br>  return this.http.post&lt;Data&gt;(url, data)<br>    .pipe(this.catchHttpErrors());<br>}</pre><pre>updateData(data: Data) {<br>  return this.http.put&lt;Data&gt;(`${url}/${data.id}`, data)<br>    .pipe(this.catchHttpErrors());<br>}</pre><h4><strong>Remove unused code</strong></h4><p>It is extremely valuable to know if a piece of code is being used or not. If you let unused code stay, then in the future, it can be hard or almost impossible to be certain if it’s actually used or not. Therefore, you should make it a high priority to remove unused code.</p><h4><strong>Avoid code comments</strong></h4><p>Although there are cases for comments, you should really try to avoid them. You don’t want your comments to compensate for your failure to express the message in your code. Comments should be updated as code is updated, but a better use of time would be to write code that explains itself. Inaccurate comments are worse than no comments at all, as stated by <strong>anonymous</strong>:</p><blockquote>Code never lies, comments do.</blockquote><p>This avoids writing code like this:</p><pre>// check if meal is healthy or not<br>if (meal.calories &lt; 1000 &amp;&amp;<br>    meal.hasVegetables) {<br>  ...<br>}</pre><p>And hopefully more like this:</p><pre>if (meal.isHealthy()) {<br> ...<br>}</pre><h3><strong>Separation of Concerns</strong></h3><p>Angular is built around separation of concerns. This is a design-pattern that makes our code easier to maintain and extend, and more reusable and testable. It helps us encapsulate and limit the logic of components to satisfy what the template actually needs, and nothing more. Separation of concerns is the core of writing clean code in Angular, and uses the following rule-set:</p><ul><li>Split the application into multiple modules. The project becomes more organized, maintainable, readable and reusable, and we’re able to lazy load features.</li></ul><pre>|-- modules<br>|    |-- home<br>|    |     |-- home.spec|module|component|scss||routing.module|.ts<br>|    |-- about<br>|    |     |-- about.spec|module|component|scss|routin.module|.ts</pre><ul><li>When we find ourself in situations where we want to reuse business logic in other parts of our application, we should consider creating a service. Services are a central part of Angular and a great place for your reusable business logic. The most common use case for services are HTTP-related events. By using a service to manage our HTTP calls, we know exactly where the changes has to be made and those are the only line affected.</li></ul><p><em>Quick tip! You can also create an API service which handles a lot of the HTTP-related logic for you. I recommend checking out </em><a href="https://github.com/gothinkster/angular-realworld-example-app/blob/master/src/app/core/services/api.service.ts"><em>this</em></a><em> GitHub-example.</em></p><ul><li>You should create something like a “common frame” for your application where you will include common components. This comes in handy when you don’t want to contaminate your components with the same code. Since Angular doesn’t allow us to import component directly between different modules, we need to put these components inside the shared module.</li></ul><pre>// src/app/shared/components/reusable/resuable.component</pre><pre>...</pre><pre>export class ReusableComponent implements OnInit {<br>  @Input() title: string;<br>  @Input() body: string;<br> <br>  @Output() buttonClick = new EventEmitter();</pre><pre>  constructor() { }</pre><pre>  ngOnInit() {}</pre><pre>  onButtonClick(){<br>    this.buttonClick.emit(&#39;Button was clicked&#39;);<br>  }<br>}</pre><pre>--------------------------------------------------------------------</pre><pre>// You can then use this component directly inside the components of<br>// your choice</pre><pre>// src/app/some/some.component</pre><pre>@Component({<br>  selector: &#39;app-some&#39;,<br>  template: `&lt;app-reusable [title]=&quot;&#39;Awesome title!&#39;&quot;<br>               [body]=&quot;&#39;Lorem ipsum&#39;&quot;<br>               (buttonClick)=&quot;buttonClick($event)&gt;<br>             &lt;/app-reusable&gt;`,<br>})<br>export class SomeComponent implements OnInit {</pre><pre>  constructor() {}</pre><pre>  ngOnInit() {}</pre><pre>  public buttonClick(e){<br>    console.log(e);<br>  }<br>}</pre><p><em>Quick tip! We’re able to control the HTML contents from the “parent” component by using the </em><em>ng-content tag. Read more about content projection with </em><em>ng-content </em><a href="https://codecraft.tv/courses/angular/components/content-projection/"><em>here</em></a><em>.</em></p><ul><li>When we find our self in situations where multiple HTML elements share the same behavior (e.g. some piece of text is highlighted on click), we should consider using an attribute directive. Attribute directives are used to change the behavior or appearance of a HTML-element.</li></ul><h3><strong>Utilize TypeScript</strong></h3><p>TypeScript is a superset of JavaScript which primary provides static typing, classes and interfaces. Angular is built on TypeScript, and as a result, using TypeScript with Angular becomes a pleasurable experience. It provides us with advanced autocompletion, quick navigation and refactoring. Having such a tool at your disposal shouldn’t be taken for granted.</p><p>To get the most out of TypeScript:</p><ul><li>We should always use interfaces to force the class to implement declared functions and properties.</li></ul><pre>// .../burger.model.ts<br>export interface Burger {<br>  name: string;<br>  calories: number;<br>}</pre><pre>// .../show-burger.component.ts<br>this.burger: Burger;</pre><ul><li>We should make use of type unions and intersections. This comes extremely handy when dealing with data from an API.</li></ul><pre>export interface Burger {<br>  ...,<br>  bestBefore: string | Date;<br>}</pre><p><em>Quick tip! We should always declare variables and constants with a type definition other than “any”. Strictly typed code is less error-prone.</em></p><h3><strong>Use TSLint</strong></h3><p>One way of improving your development experience immensely is by using TSLint. This is a static code analysis tool we use in software development for checking if TypeScript code complies with the coding rules. Having these rules in place will give you an error when you do something wrong.</p><h4><a href="https://www.npmjs.com/package/tslint-config-prettier">Prettier with TSLint</a></h4><p>You can combine TSLint with Prettier. Prettier is an amazing tool that enforces a consistent style by parsing your code and re-printing it, with it’s own rules in place. Having Prettier setup with TSLint gives you a strong foundation for your applications, as you no longer need to maintain your code-style manually. Prettier takes care of code formatting and TSLint handles the rest.</p><h4><a href="https://www.npmjs.com/package/husky">Lint with Husky</a></h4><p>Even with these rules in place, it can be hard to maintain them. You can easily forget to run these commands before pushing your code to production, which leads to a broken result. One way to work around this problem is by using husky. Husky allows us to run custom scripts before the staged files are committed — keeping our production code clean and organized.</p><h3>RxJS in Angular</h3><p>RxJS is a library for reactive programming that allows us to work with asynchronous data streams. Angular comes packaged with RxJS, so it’s to our great advantage to make the most of it.</p><h4>Pipeable operators</h4><p>RxJS 5.5 introduced pipeable operators. This pipe-based approach to observable-composition allows us to import on a per-operators basis, rather than importing everything. Pipeable operators does also have tree-shaking advantages and allows us to build own custom operators without extending the Observable.prototype.</p><p>This will help us avoid writing code like this:</p><pre>...</pre><pre>const name = this.loadEmployees()<br>  .map(employee =&gt; employee.name)<br>  .catch(error =&gt; Rx.Observable.of(null));</pre><p>And hopefully more like this:</p><pre>const name = this.loadEmployees()<br>    .pipe(<br>      map(employee =&gt; employee.name),<br>      catchError(error =&gt; of(null))<br>    );</pre><h4>Subscribe in Template</h4><p>Imagine a case where we need to subscribe to multiple streams. It would be a headache to manually map every single property to the corresponding value and manually unsubscribe when the component gets destroyed.</p><p>With the async pipe, we subscribe to the stream directly inside our template, without having to store the result in an intermediate property. The subscription will terminate when the component gets destroyed, which makes subscription-handling easier and contributes to cleaner code.</p><p>This will help us avoid writing code like this:</p><pre>@Component({<br>  ...<br>  template: `&lt;items [items]=&quot;item&quot;&gt;`<br>})<br>class AppComponent {<br>  items: Item[];</pre><pre>  constructor(private itemService: ItemService) {}</pre><pre>  ngOnInit() {<br>    this.loadItems()<br>      .pipe(<br>        map(items =&gt; this.items = items;<br>      ).subscribe();<br>  }</pre><pre>  loadItems(): Observable&lt;Item[]&gt; {<br>    return this.itemService.findItems();<br>  }<br>}</pre><p>And hopefully more like this:</p><pre>@Component({<br>    ...<br>    template: `&lt;items [items]=&quot;items$ | async&quot;&gt;&lt;/items&gt;`<br>})<br>class AppComponent {<br>  items$: Observable&lt;Item[]&gt;;<br><br>  constructor(private itemService: ItemService) {}</pre><pre>  ngOnInit() {<br>    this.items = this.loadItems();<br>  }</pre><pre>  loadItems(): Observable&lt;Item[]&gt; {<br>    return this.itemService.findItems();<br>  }<br>}</pre><h4>Avoid memory leaks</h4><p>While Angular takes care of unsubscribing when using the async pipe, it quickly becomes a mess when we have to do this on our own. Failing to unsubscribe will lead to memory leaks, as the observable stream is left open.</p><p>The solution is to compose our subscription with the takeUntil operator, and use a subject that emits a value when the component gets destroyed. This will complete the observable-chain, causing the stream to unsubscribe.</p><p>This help us avoid writing code like this:</p><pre>this.itemService.findItems()<br>  .pipe(<br>    map((items: Item[]) =&gt; items),<br>  ).subscribe()</pre><p>And hopefully more like this:</p><pre>  private unsubscribe$: Subject&lt;void&gt; = new Subject&lt;void&gt;();</pre><pre>  ...</pre><pre>   this.itemService.findItems()<br>    .pipe(<br>       map(value =&gt; value.item)<br>       takeUntil(this._destroyed$)<br>     )<br>    .subscribe();</pre><pre>  ...</pre><pre>  public ngOnDestroy(): void {<br>    this.unsubscribe$.next();<br>    this.unsubscribe$.complete();<br>    this.unsubscribe$.unsubscribe();<br>  }</pre><p><em>Quick tip! We now have another way to accomplish this using something called subsink. It’s a </em><a href="https://www.npmjs.com/package/subsink"><em>library developed by Ward Bell</em></a><em> for easy unsubscribing.</em></p><h4>Don’t use nested subscriptions</h4><p>There may be situations where you need to consume data from multiple observable streams. In those cases, you should generally try to avoid socalled nested subscriptions. Nested subscriptions becomes hard to understand and may introduce unexpected side effects. We should instead use chainable methods like switchMap, forkJoin and combineLatest to condense our code.</p><p>This will help us avoid writing code like this:</p><pre>this.returnsObservable1(...)<br>  .subscribe(<br>    success =&gt; {<br>      this.returnsObservable2(...)<br>        .subscribe(<br>          success =&gt; {<br>            this.returnsObservable3(...)<br>              .subscribe(<br>                success =&gt; {<br>                   ...<br>                },</pre><p>And hopefully more like this:</p><pre>this.returnsObservable1(...)<br>  .pipe(<br>    flatMap(success =&gt; this.returnObservable2(...),<br>    flatMap(success =&gt; this.returnObservable3(...)<br>   )<br>   .subscribe(success =&gt; {...});</pre><p><em>+Quick tip! There may be confusion around when to use the appropriate operators when dealing with multiple streams. I recommend checking out </em><a href="https://medium.com/@shairez/a-super-ninja-trick-to-learn-rxjss-switchmap-mergemap-concatmap-and-exhaustmap-forever-88e178a75f1b"><em>this </em></a><em>article for some clarity on this topic.</em></p><h4>Subjects in RxJS</h4><p>A Subject acts as both an observable and an observer. Because Subjects allows us to emit data into an observable stream, people tend to abuse them. This is especially popular among developers new to RxJS. To determine when it might be a good time to use a Subject, we’re first going to see what subjects are, and what subjects are not.</p><p>What subjects <strong>are</strong>:</p><ul><li>Subjects are multicasted, which means you can create multiple subscriptions on a single observer. You can notify all the observers in the list with the next() method. This is the primarily use of Subjects in RxJS.</li><li>Since Subjects implements Observable and Observer simultaneously, their suitable for both input and output events.</li></ul><p>What subjects <strong>are not</strong>:</p><ul><li>RxJS Subjects can’t be reused. You’re not allowed to call the next() method on a completed Subject.</li></ul><p><em>Quick tip! On top of vanilla Subject, there are also a few specialized types of subjects like async subjects, behavior subjects and replay subjects. You can read more about those types of subjects </em><a href="https://alligator.io/rxjs/subjects/"><em>here</em></a><em>.</em></p><h3><strong>Clean up imports with path aliases</strong></h3><p>Consider a case where you need to import something far down the application hierarchy. This would lead to an import statement looking something like this:</p><pre>import &#39;reusableComponent&#39; from &#39;../../../shared/components/reusable/reusable.component.ts&#39;;</pre><p>Then imagine that you need to change the location this file. You would then have to update the path of every single file which uses that feature. This doesn’t sound very efficient, does it?</p><p>We can clean up these imports considerably by using aliases to reference our files, which looks something like this:</p><pre>import &#39;reusableComponent&#39; from &#39;@app/shared/components/reusable.component.ts&#39;;</pre><p>To be able to do this, we need to add a baseUrl and the desired paths inside our tsconfig.json file:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    ...<br>    &quot;baseUrl&quot;: &quot;src&quot;,<br>    &quot;paths&quot;: {<br>      &quot;@app:&quot;: [&quot;@app/*&quot;]<br>    }<br>  }<br>}</pre><p>The most common use case for imports are component and services from the Core- and Shared module. To avoid writing out the entire path for those features, we’ll create multiple index.ts-files, which exports those features:</p><pre>// src/app/shared/components/index.ts</pre><pre>export * from &#39;./reusable/reusable.component.ts&#39;;</pre><pre>// src/app/shared</pre><pre>export * from &#39;/components&#39;;</pre><p>We can now reference the file import like this:</p><pre>import &#39;ReusableComponent&#39; from &#39;@app/shared/&#39;;</pre><p><em>Quick tip! Be aware when using path aliases to import services or components inside the Shared- or Core module. This may lead to “circular dependencies”. In those cases, you need to write the entire path.</em></p><h3>Spice up your App with animations</h3><p>Animation is defined as the transition from an initial state to a final state. It is an integral part of any modern web application. Animation not only helps us create a great UI but it also makes the application interesting and fun to use. A well-structured animation keeps the user engaged with the application and enhances the user experience.</p><h3><strong>Lazy Load Your Modules</strong></h3><p>If your using a multiple-module architecture, it’s probably a good idea to lazy load your modules. Only the feature module which is used to display the initial content to the user should be loaded synchronously. The advantage of using lazy loading is that module isn’t loaded before the user actually accesses the route. This helps decrease the overall startup time by only loading the modules we’re currently presenting.</p><h3>Reduce final bundle size</h3><p>Bundle sizes has a huge impact on the performance of the application. It’s not just about download speed, but all the JavaScript we ship to the browser needs to be parsed and compiled before it can be executed. Keeping our bundle in check can be difficult, but it’s much easier when we can see where the bloat is coming from.The webpack-bundle-analyzer plugin allows us to visualize the contents of the production build.</p><h3><strong>State Management</strong></h3><p>When building large, complex applications that has lots of information coming from and going to the database, and where state is shared across multiple components, you might start considering adding a state management library. By using a state management library, you are able to keep the application state in one single place, which reduces the communication between components and keeps your app more predictable and easier to understand.</p><h3><strong>Conclusion</strong></h3><p>Angular is a very powerful framework with a lot of functionality. But if you’re new to the game, it can seem overwhelming with all its different options and whatnot. Hopefully, by following the guidelines outlined here, some of the concepts became more clear to you. Although there are no blueprint for how to write clean code, there’s some key takeaways here:</p><p><strong>Write readable code</strong>. Focus on writing code that is easy to understand.</p><p><strong>Separation of concerns</strong>. Encapsulate and limit logic inside your components, services and directives. Each file should only be responsible for a single functionality.</p><p><strong>Utilize TypeScript</strong>. TypeScript provides advanced autocompletion, navigation and refactoring. Having such a tool at your disposal shouldn’t be taken for granted.</p><p><strong>Use TSLint</strong>. TSLint checks if TypeScript code complies with the coding rules in place. Combined with Prettier and Husky makes for an excellent workflow.</p><p><strong>RxJS in Angular</strong>. RxJS comes packaged with Angular, it’s to our great advantage to make the most of it.</p><p><strong>Clean up imports with path aliases</strong>. We can clean up our imports considerably by using path aliases to reference our files.</p><p><strong>Lazy load your modules</strong>. Lazy loading helps us decrease the startup time of our app by only loading the modules we’re currently presenting.</p><p><strong>State management (if necessary)</strong>. State management is a great tool to have at your disposal, but should only be used for large, complex applications where multiple components shares the same state.</p><p>Other useful resources on this topic:</p><ul><li><a href="https://medium.freecodecamp.org/best-practices-for-a-clean-and-performant-angular-application-288e7b39eb6f">https://medium.freecodecamp.org/best-practices-for-a-clean-and-performant-angular-application-288e7b39eb6f</a></li><li><a href="https://code-maze.com/angular-best-practices/">https://code-maze.com/angular-best-practices/</a></li><li><a href="https://github.com/ryanmcdermott/clean-code-javascript">https://github.com/ryanmcdermott/clean-code-javascript</a></li></ul><p><em>That’s it from me. I would greatly appreciate if you gave me some feedback on these guidelines. Do you have some other recommendations? Would you do something differently?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10d4db877f74" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/clean-code-checklist-in-angular-%EF%B8%8F-10d4db877f74">Clean Code Checklist in Angular ✔️</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Enterprise Angular Apps With The ngX-Rocket Generator]]></title>
            <link>https://itnext.io/creating-enterprise-angular-apps-with-the-ngx-rocket-generator-871ac76ace87?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/871ac76ace87</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[ngx-rocket]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Tue, 08 May 2018 17:14:10 GMT</pubDate>
            <atom:updated>2018-05-10T14:33:37.276Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/649/0*nuoUYU9QH9BbpBbB.png" /><figcaption><a href="https://www.npmjs.com/package/generator-ngx-rocket">https://www.npmjs.com/package/generator-ngx-rocket</a></figcaption></figure><h3>Introduction</h3><p>In this article, we will dive deep into a new Angular generator called ngX-Rocket. ngX-Rocket is an Angular 5+ enterprise project-generator based on the <a href="https://github.com/angular/angular-cli">Angular-CLI</a> with best practices from the community. It allows developers to easily make applications with a lot of functionality, right out of the box. Among it’s core features is PWA- (Progressive Web App) and Cordova-support, a scalable starter template, coding guides and much, much more.</p><blockquote>Version 4.2 is the latest version at the time of writing. You can look over the changes in <a href="https://medium.com/ngx-rocket/version-4-0-0-of-ngx-rocket-now-available-fa0c5d090cc1">this</a> Medium-article. I will also suggest following ngX-Rocket’ github-repo. to keep an overview of further changes and improvements.</blockquote><h3>Benefits vs. Bare Angular CLI App</h3><p>The most of you are probably already familiar with the Angular CLI. Like ngX-Rocket, Angular CLI is a command-line interface for creating quick-start Angular projects and automate your development workflow. So why would you choose ngX-Rocket instead?</p><p>The github-page of the <a href="https://github.com/ngx-rocket/generator-ngx-rocket">project</a> highlights some reasons why choosing this generator over the Angular CLI might be a good idea:</p><blockquote><strong>A complete starter template</strong>: example app-structure tailored for scalability, with examples and boilerplate code for every common thing needed in enterprise projects, such as unit tests, routing, authentication, HTTPS service extensions, i18n support with dynamic language change and automatic user language detection.</blockquote><blockquote><strong>Improved tooling</strong>: SCSS &amp; HTML linting, stricter TSLint rules, markdown-based local wiki server for documentation, automated localizable strings extraction, corporate proxy support, <a href="https://cordova.apache.org/">Cordova</a> integration.</blockquote><blockquote><strong>Extensive base documentation</strong>: <a href="https://github.com/ngx-rocket/generator-ngx-rocket#coding-guides">coding guides</a> for TypeScript/SCSS/HTML, Angular onboarding guide, corporate proxy and other tools <a href="https://github.com/ngx-rocket/generator-ngx-rocket#other-documentation">configuration and usage</a>.</blockquote><blockquote><strong>Ready-to-use UI components</strong>: focus on your app, not on the stack! <a href="https://github.com/ngx-rocket/generator-ngx-rocket#libraries">Choose</a> between a <a href="https://getbootstrap.com/">Bootstrap 4</a>, <a href="http://ionicframework.com/">Ionic</a> or <a href="https://material.angular.io/">Angular Material</a> based UI with nicely looking, responsive starter templates.</blockquote><blockquote><strong>Mobile app support</strong>: choose between a web app, a mobile app (using <a href="https://cordova.apache.org/">Cordova</a>) or both using the same code base.</blockquote><blockquote><strong>API proxy example setup</strong>: develop and debug faster using any remote server.</blockquote><blockquote><strong>Generator output customization</strong>: with the provided <a href="https://github.com/ngx-rocket/generator-ngx-rocket/tree/master/generators/addon">add-on support</a>, start multiple projects even faster by plugging in additions that fit your needs, such as your enterprise theme, SSO authentication, services integrations.</blockquote><h3>Creating a new project</h3><h4>Prerequisites</h4><p>Before you can use the ngX -Rocket CLI, you need to have Node.js 6.9.0 and npm 3.0.0 or higher installed on your system. You can download the latest version of Node.js for your operating system on Node’ official site.</p><p>If you already have Node.js and npm installed, verify their versions by running:</p><pre>$ node -v # =&gt; displays node version<br>$ npm -v # =&gt; displays npm version</pre><p>Once you have Node.js installed, you can use the npm command to install <a href="http://www.typescriptlang.org/">TypeScript</a>:</p><pre>$ npm install -g typescript</pre><p>You don’t technically need TypeScript, but it’s highly recommended by the Angular team, so I recommend you install it to make working with Angular as comfortable as possible.</p><p>Now that you have Node.js and TypeScript installed, you can install the ngX-Rocket CLI by running:</p><pre>$ npm i -g generator-ngx-rocket</pre><p>This will install the ngX-Rocket generator globally on your system. You can verify the installation by using the following command:</p><pre>$ ngx version # =&gt; displays ngx-rocket version</pre><h4>Create the app</h4><p>The first thing we need to do is creating a folder for our new project, since the generator doesn’t do this by default:</p><pre>$ mkdir ngx-starter</pre><p>Navigate inside the newly created folder:</p><pre>$ cd ngx-starter</pre><p>And initialize a new ngx project:</p><pre>$ ngx new</pre><p>When initializing a new project, you will be prompted with the following options:</p><pre>$ ngx new</pre><pre>$ What&#39;s the name of your app?  (ngx app)</pre><pre>$ What kind of app do you want to create? <br>&gt; (*) Web app<br>&gt; ( ) Mobile app(using Cordova)</pre><pre>$ Do you want a progressive web app? (with manifest and service worker) (Y/n)</pre><pre>$ Which UI framework do you want?<br>&gt; Bootstrap (more website-oriented)<br>  Angular Material (more website-oriented)<br>  Ionic (more mobile-oriented)</pre><pre>$ Do you want authentication? (Y/n)</pre><pre>$ Do you want lazy loading? (y/N)</pre><pre>$ Do you want analytics support (with Angularatstics2)? (y/N)</pre><p>This will create a new ngX-Rocket application inside you’re chosen directory. The CLI will download all required NPM packages and set everything up.</p><p>You can now run the app:</p><blockquote>Note! You need to run the app using npm start instead of ng serve since it doesn’t use the backend proxy configuration by default.</blockquote><pre>$ npm start</pre><p>Let’s head over to localhost:4200 to make sure that everything is working as expected so far.</p><h4>Application Structure</h4><pre>dist/                      =&gt; app production build<br>docs/                      =&gt; project docs and coding guides<br>e2e/                       =&gt; end-to-end tests<br>src/                       =&gt; project source code<br>|- app/                    =&gt; app components<br>|  |- core/                =&gt; core module (singleton services and<br>|  |                          single-use components)<br>|  |- shared/              =&gt; shared module  (common components, <br>|  |                          directives and pipes)<br>|  |- app.component.*       =&gt; app root component (shell)<br>|  |- app.module.ts         =&gt; app root module definition<br>|  |- app-routing.module.ts =&gt; app routes<br>|  +- ...                   =&gt; additional modules and components<br>|- assets/                  =&gt; app assets (images, fonts, sounds...)<br>|- environments/            =&gt; values for various build environments<br>|- theme/                   =&gt; app global scss variables and theme<br>|- translations/            =&gt; translation files<br>|- index.html               =&gt; html entry point<br>|- main.scss                =&gt; global style entry point<br>|- main.ts                  =&gt; app entry point<br>|- polyfills.ts             =&gt; polyfills needed by Angular<br>+- test.ts                  =&gt; unit tests entry point<br>reports/                    =&gt; test and coverage reports<br>proxy.conf.js               =&gt; backend proxy configuration</pre><h4>Documentation Server</h4><p>The docs contains a comprehensive overview of best practises in Angular. You can display the documentation in a separate server by running the npm run docs command. You’re browser will open at http://localhost:4040 and display the project documentation.</p><h4>HttpClient extension</h4><p>You can cache any HTTP request by calling the cache() before making your request:</p><pre>this.httpClient<br>   .cache()<br>   .get(&#39;https://myapi.com&#39;);</pre><h4>Proxy-server</h4><p>To ease development, they’ve sat up a backend proxy which redirects API calls to whatever URL and port you want. This allows you to:</p><blockquote>Develop frontend features without the need to run an API backend locally</blockquote><blockquote>Use a local development server without <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing">CORS</a> issues</blockquote><blockquote>Debug frontend code with data from a remote testing platform directly</blockquote><h3>Customization</h3><p>One of the things I love about this Angular starter project is how easy it is to add functionality. Here’s an overview of some customizations I like to do.</p><pre>docs/                      <br>e2e/              <br>src/                  <br>|- app/      <br>|  |- core/<br>|  |  |- data                =&gt; mock services<br>|  |  |- json                =&gt; json files exported for mocks<br>|  |  |- services            =&gt; singleton services<br>|  |                 <br>|  |- shared/<br>|  |  |- directives          =&gt; directives used across the app<br>|  |  |- models              =&gt; models used across the app<br>|  |  |- pipes               =&gt; pipes used across the app<br>|  |  |- components          =&gt; components used across the app<br>|  |<br>|  |- modules                =&gt; collection of all the modules<br>|  |  |- components          =&gt; components which are shared across<br>|  |  |                         the module<br>|  |  |- pages               =&gt; pages the module consist of<br>|  |                  <br>|  |- app.component.*  <br>|  |- app.module.ts        <br>|  |- app-routing.module.ts<br>|  +- ...                 <br>|- assets/<br>|- environments/         <br>|- theme/                  <br>|- translations/      <br>|- index.html              <br>|- main.scss          <br>|- main.ts            <br>|- polyfills.ts          <br>+- test.ts        <br>reports/                  <br>proxy.conf.js       </pre><h3>Conclusion</h3><p>The ngX-Rocket project is a great starting point for your development process. You’re provided with a large set of tools and the project follows best practises which both the Angular- team and community recommends. The project is also quite easy to customize, which means adding new functionality isn’t that big of a task. Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=871ac76ace87" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/creating-enterprise-angular-apps-with-the-ngx-rocket-generator-871ac76ace87">Creating Enterprise Angular Apps With The ngX-Rocket Generator</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to define a highly scalable folder structure for your Angular project]]></title>
            <link>https://itnext.io/choosing-a-highly-scalable-folder-structure-in-angular-d987de65ec7?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d987de65ec7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[structured-data]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Tue, 27 Mar 2018 09:55:49 GMT</pubDate>
            <atom:updated>2020-07-03T20:13:14.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKHp_rhoFSLOJ3NEZWVr1Q@2x.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/8EzNkvLQosk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maarten van den Heuvel</a> on <a href="https://unsplash.com/search/photos/structure?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>Update! The code for this article is now available at GitHub. You can view the project </em><a href="https://github.com/mathisGarberg/angular-folder-structure"><em>here</em></a><em> The structure is slightly different from the one discussed in this article, but builds on the same concepts and ideas.</em></p><h3>Preface</h3><p>Finding a suitable folder structure for my Angular applications is something I’ve struggled with for a long time. This became a real issue in my first ever real-world Angular project — especially when the application grew in size. I ended up continuously adding new features with no real structure in place. This made it hard to locate files and making additional changes to the folder structure became time-consuming. But I did get a good understanding about do’s and don’ts when structuring an Angular app.</p><p>The goal of this article is to help other developers in a similar situation.</p><p><em>I want to underline that the practices used in this article is very applicable for my single use-case, and should by no means be strictly followed. The folder structure of a project will change based on a broad range of factors. But if you’re interested in a structure which focuses on a multiple-module architecture with a large focus on scaling, continue reading.</em></p><p><em>Note! The [+] indicates that the folder has additional files.</em></p><pre>|-- app<br>     |-- modules<br>       |-- home<br>           |-- [+] components<br>           |-- [+] pages<br>           |-- home-routing.module.ts<br>           |-- home.module.ts<br>     |-- core<br>       |-- [+] authentication<br>       |-- [+] footer<br>       |-- [+] guards<br>       |-- [+] http<br>       |-- [+] interceptors<br>       |-- [+] mocks<br>       |-- [+] services<br>       |-- [+] header<br>       |-- core.module.ts<br>       |-- ensureModuleLoadedOnceGuard.ts<br>       |-- logger.service.ts<br>     |<br>     |-- shared<br>          |-- [+] components<br>          |-- [+] directives<br>          |-- [+] pipes<br>          |-- [+] models<br>     |<br>     |-- [+] configs<br>|-- assets<br>     |-- scss<br>          |-- [+] partials<br>          |-- _base.scss<br>          |-- styles.scss</pre><h4>The Angular Style Guide</h4><p>The logical place to start looking for best practices in Angular is the <a href="https://angular.io/guide/styleguide">Angular Style Guide</a>. The guide offers an opinionated view on syntax, conventions and application structure.</p><p>The key guidelines that really stood out for me was “<em>Structure the app such that you can locate code quickly</em>” and “<em>Have a near-term view of implementation and a long-term vision. Start small but keep in mind where the app is heading down the road</em>”. This means that you shouldn&#39;t lock yourself to one structure, since it will change a lot depending on the project.</p><h4>Modules</h4><pre>|-- modules<br>       |-- home<br>           |-- components<br>           |-- pages<br>           |    |-- home<br>           |         |-- home.component.ts|html|scss|spec<br>           |<br>           |-- home-routing.module.ts<br>           |-- home.module.ts</pre><p><a href="https://medium.com/@motcowley">Tom Crowley</a> has a really interesting article on this topic (<a href="https://medium.com/@motcowley/angular-folder-structure-d1809be95542">found here</a>), where he works his way from a bare bone Angular project to a really solid folder structure. I really liked the idea of modules with designated folders for pages- and components. It’s perfect for scaling and component- and page logic are separated. So if you’re interested in the though-process behind this structure, head over there.</p><h3>The Core Module</h3><p>The CoreModule takes on the role of the root AppModule , but is not the module which gets bootstrapped by Angular at run-time. The CoreModule should contain singleton services (which is usually the case), universal components and other features where there’s only once instance per application. To prevent re-importing the core module elsewhere, you should also add a guard for it in the core module’ constructor.</p><pre>|-- core<br>       |-- [+] authentication<br>       |-- [+] footer<br>       |-- [+] guards<br>       |-- [+] http<br>       |-- [+] interceptors<br>       |-- [+] mocks<br>       |-- [+] services<br>       |-- [+] header<br>       |-- core.module.ts<br>       |-- ensureModuleLoadedOnceGuard.ts<br>       |-- logger.service.ts</pre><p>The authentication folder simply handles the authentication-cycle of the user (from login to logout).</p><pre>|-- authentication<br>     |-- authentication.service.ts|spec.ts</pre><p>The footer- and header folders contains the global component-files, statically used across the entire application. These files will appear on every page in the application.</p><pre>|-- header<br>     |-- header.component.ts|html|scss|spec.ts<br>|-- footer<br>     |-- footer.component.ts|html|scss|spec.ts</pre><p>The http folder handles stuff like http calls from our application. I’ve also added a api.service.ts file to keep all http calls running through our application in one single place. The folder does otherwise contain folders for interacting with the different API-routes.</p><pre>|-- http<br>     |-- user<br>          |-- user.service.ts|spec.ts<br>     |-- api.service.ts|spec.ts</pre><p>Angular 4.x introduced a long-awaited feature for handling http requests — the HttpInterceptor interface. This allows us to catch and modify the requests and responses from our API calls. The interceptors folder is a collection of interceptors I find specially useful.</p><pre>|-- interceptors<br>       |-- api-prefix.interceptor.ts<br>       |-- error-handler.interceptor.ts<br>       |-- http.token.interceptor.ts</pre><p>The guards folder contains all of the guards I use to protect different routes in my applications.</p><pre>|-- guards<br>     |-- auth.guard.ts<br>     |-- no-auth-guard.ts<br>     |-- admin-guard.ts </pre><p>Mocks are specially useful for testing, but you can also use them to retrieve fictional data until the back-end is set up. The mocks folder contains all the mock-files of our app.</p><pre>|-- mocks<br>       |-- user.mock.ts</pre><p>All additional <strong>singleton </strong>services are placed in the services folder.</p><pre>|-- services<br>     |-- srv1.service.ts|spec.ts<br>     |-- srv2.service.ts|spec.ts</pre><h3>The Shared Module</h3><p>The SharedModule is where any shared components, pipes/filters and services should go. The SharedModule can be imported in any other module when those items will be re-used. The shared module shouldn’t have any dependency to the rest of the application and should therefore not rely on any other module.</p><pre>|-- shared<br>     |-- [+] components<br>     |-- [+] directives<br>     |-- [+] pipes</pre><p>The components folder contains all the “shared” components. This are components like loaders and buttons , which multiple components would benefit from.</p><pre>|-- components<br>     |-- loader<br>          |-- loader.component.ts|html|scss|spec.ts<br>     |-- buttons<br>          |-- favorite-button<br>               |-- favorite-button.component.ts|html|scss|spec.ts<br>          |-- collapse-button<br>               |-- collapse-button.component.ts|html|scss|spec.ts</pre><p>The directives , pipes and models folders contains the directives, pipes and models used across the application.</p><pre>|-- directives<br>      |-- auth.directive.ts|spec.ts</pre><pre>|-- pipes<br>     |-- capitalize.pipe.ts<br>     |-- safe.pipe.ts</pre><pre>|-- models<br>     |-- user.model.ts<br>     |-- server-response.ts</pre><h3>Configs</h3><p>The config folder contains app settings and other predefined values.</p><pre>|-- configs<br>     |-- app-settings.config.ts<br>     |-- dt-norwegian.config.ts</pre><h3>Styling</h3><p>The global styles for the project are placed in a scss folder under assets .</p><pre>|-- scss<br>     |-- partials<br>          |-- _layout.vars.scss<br>          |-- _responsive.partial.scss<br>     |-- _base.scss<br>|-- styles.scss</pre><p>The scss folder does only contain one folder — partials. Partial-files can be imported by other scss files. In my case, styles.scss imports all the partials to apply their styling.</p><h3>Lazy Loading</h3><p>The application uses lazy-loading, which means the module isn’t loaded before the user actually accesses the route. By using the structure described in the “Modules”-section, you can easily refer each module in your main app-routing file.</p><h3>Summary</h3><p>In conclusion, there’s no blueprint when it comes to creating a folder-structure in Angular. The structure will change a lot depending on the project you’re working on. This article covers an explicit use-case using multiple modules, which in turn are divided into pages and a shared set of components. But here are links to some github repos with a flatter structure:</p><ul><li><a href="https://github.com/ngx-rocket/starter-kit/tree/master/src">https://github.com/ngx-rocket/starter-kit/tree/master/src</a></li><li><a href="https://github.com/gothinkster/angular-realworld-example-app">https://github.com/gothinkster/angular-realworld-example-app</a></li></ul><p>Check out my website on <a href="https://mathisgarberg.no/">https://mathisgarberg.no</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d987de65ec7" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/choosing-a-highly-scalable-folder-structure-in-angular-d987de65ec7">How to define a highly scalable folder structure for your Angular project</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Forms Inside Modals with ng-bootstrap]]></title>
            <link>https://itnext.io/creating-forms-inside-modals-with-ng-bootstrap-221e4f1f5648?source=rss-5dc1286f4ca3------2</link>
            <guid isPermaLink="false">https://medium.com/p/221e4f1f5648</guid>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ng-bootstrap]]></category>
            <dc:creator><![CDATA[Mathis Garberg]]></dc:creator>
            <pubDate>Thu, 22 Mar 2018 12:43:21 GMT</pubDate>
            <atom:updated>2018-06-29T21:09:42.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*9kP1dxKPMiz2Otb5zu7RRg.jpeg" /></figure><p>Creating forms inside modals has some great benefits. Using them along with valuable content might bring a lot of attraction to your project. With the emergence of ngx- and ng-bootstrap, we can easily integrate any Bootstrap components to our application.</p><p>This article covers the following topics:</p><ul><li>Creating a Angular Project</li><li>Adding ng-bootstrap and create a simple modal</li><li>Adding the form inside of our modal</li><li>Summary</li></ul><p>So, let’s get started!</p><h4>Creating The Project</h4><p>The best way to start a new project, is by using the Angular CLI. The CLI takes care of code-scaffolding of the initial app, building our app, creating of components, and much, much more. To get access to the Angular CLI toolkit, you first need to install it.</p><p>Use the following command:</p><p>npm install @angular/cli -g</p><p>Then initialize a new Angular project with:</p><p>ng new ngModalForm</p><p>Once it is finish, access the directory and run ng serve. This will serve our application at localhost:4200. When pasting and enter this snippet in your URL, you should see a basic page.</p><h4>Adding ng-bootstrap</h4><p>As I mentioned earlier, we’ll use the ng-bootstrap library in our project. ng-bootstrap is dependent on both Angular and Bootstrap. Since we already have Angular sat up, we only need Bootstrap.</p><p>Run the following command:</p><pre>npm i bootstrap</pre><p>This will install the package, but we still need to set it up. In your angular-cli.json file, add the following lines in the styles array:</p><pre>&quot;styles&quot;: [<br>&quot;styles.css&quot;,<br>  &quot;../node_modules/bootstrap/dist/css/bootstrap.min.css&quot;<br>],...</pre><p><em>Note! I ran into a issue with the bootstrap version I used (4.0.0-beta.3). You need to downgrade to beta 2 to make it work. Simply update dependency inside </em><em>package.json and run </em><em>npm i .</em></p><p>Then install ng-bootstrap with:</p><pre>npm i --save @ng-bootstrap/ng-bootstrap</pre><p>Once installed, import the module in the app.module:</p><pre>import { NgbModule } from &#39;@ng-bootstrap/ng-bootstrap&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent, ...],<br>  imports: [<br>    NgbModule.forRoot(),<br>    ...<br>  ],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule {<br>}</pre><p>This allows us to simply import NgbModule in other components that wants to use the toolkit of the library.</p><h4>Adding The Modal</h4><p>Let’s start by creating a modal with some simple content in it.</p><p>Create a new component for the component: ng g c FormModal . This creates the new component and adds it to the module declaration. But we also need to add it in the entryComponents declarations.</p><pre>...<br>bootstrap: [AppComponent],<br>entryComponents: [<br>  FormModalComponent<br>]<br>...</pre><p>The next thing we’ll need to do is registering a service provider for NgbActiveModal inside the FormModalComponent we just created.</p><pre>import { NgbActiveModal } from &#39;@ng-bootstrap/ng-bootstrap&#39;;</pre><p>We’ll also need to create a reference to the service in our constructor:</p><pre>constructor(<br>  public activeModal: NgbActiveModal<br>) { }</pre><p>And a method for closing for closing the modal and pass some data back to the trigger method.</p><pre>closeModal() {<br>  this.activeModal.close(&#39;Modal Closed&#39;);<br>}</pre><p>The last thing we need to do with the component, is adding the content in form-modal.component.html .</p><pre>&lt;div class=&quot;modal-header&quot;&gt;<br>  &lt;h4 class=&quot;modal-title&quot;&gt;Modal Title&lt;/h4&gt;<br>  &lt;button type=&quot;button&quot; class=&quot;close&quot; aria-label=&quot;Close&quot;<br>   (click)=&quot;activeModal.dismiss(&#39;Cross click&#39;)&quot;&gt;<br>  &lt;/button&gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;modal-body&quot;&gt;<br>  &lt;p&gt;My modal content&lt;/p&gt;<br>&lt;/div&gt;<br>&lt;div class=&quot;modal-footer&quot;&gt;<br>  &lt;button (click)=&quot;activeModal.dismiss(&#39;Close clicked&#39;)&quot;&gt;<br>    Close Clicked<br>  &lt;/button&gt;<br>&lt;/div&gt;</pre><p>So, the modal-component is all set up, but how do we initialize it? We will do this through the app.component.ts file.</p><p>Start by importing the NgbModal and FormModalComponent .</p><pre>import { NgbModal } from &#39;@ng-bootstrap/ng-bootstrap&#39;;<br>import { FormModalComponent } from &#39;./form-modal/form-modal.component&#39;;</pre><p>Create a reference in the constructor:</p><pre>constructor(<br>  private modalService: NgbModal<br>) { }</pre><p>And a method for initializing the modal.</p><pre>openFormModal() {<br>  const modalRef = this.modalService.open(FormModalComponent);<br>  <br>  modalRef.result.then((result) =&gt; {<br>    console.log(result);<br>  }).catch((error) =&gt; {<br>    console.log(error);<br>  });<br>}</pre><p>Finally, add a button with a click event, attached to it.</p><pre>&lt;button (click)=&quot;openFormModal()&quot;&gt;Open Modal&lt;/button&gt;</pre><p>And voilá! Clicking the “Open Modal”-button will launch the modal.</p><h4>Adding The Form</h4><p>We want to achieve a couple of things when implementing the form inside our modal.</p><ul><li>Pass a id to the form (in case you want to retrieve some editable information).</li><li>Pass the result back to the component which triggered the modal.</li></ul><p>Start by adding these declarations inside the app.module .</p><pre>import { FormsModule, ReactiveFormsModule } from &#39;@angular/forms&#39;;</pre><pre>...<br>imports: [<br>  BrowserModule,<br>  NgbModule.forRoot(),<br>  FormsModule,<br>  ReactiveFormsModule<br>],<br>...</pre><p>We may want to pass an id to the modal-component. This is achieved by adding the following line inside the openFormModal method.</p><pre>openFormModal() {<br>  const modalRef = this.modalService.open(FormModalComponent);<br>  modalRef.componentInstance.id = 10; // should be the id<br>  <br>  modalRef.result.then((result) =&gt; {<br>    console.log(result);<br>  }).catch((error) =&gt; {<br>    console.log(error);<br>  });<br>}</pre><p>Retrieve it in the FormModalComponent , using the Input binding.</p><pre>import { Component, OnInit, Input } from &#39;@angular/core&#39;;<br>...<br>@Input id: number;</pre><p>You now have access to the id inside of the modal.</p><p>So let’s add the form.</p><pre>&lt;div class=&quot;modal-header&quot;&gt;<br>  &lt;h4 class=&quot;modal-title&quot;&gt;My Form&lt;/h4&gt;<br>  &lt;button type=&quot;button&quot; class=&quot;close&quot; aria-label=&quot;Close&quot;<br>   (click)=&quot;activeModal.dismiss(&#39;Cross click&#39;)&quot;&gt;<br>  &lt;/button&gt;<br>&lt;/div&gt;<br>&lt;form [formGroup]=&quot;myForm&quot; (ngSubmit)=&quot;submitForm()&quot;&gt;<br>  &lt;div class=&quot;modal-boy&quot;&gt;<br>    &lt;div class=&quot;container&quot;&gt;<br>      &lt;div class=&quot;form-group&quot;&gt;<br>        &lt;label for=&quot;username&quot;&gt;Username&lt;/label&gt;<br>        &lt;input type=&quot;text&quot; <br>          class=&quot;form-control&quot;<br>          formControlName=&quot;username&quot; /&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;form-group&quot;&gt;<br>        &lt;label for=&quot;password&quot;&gt;Password&lt;/label&gt;<br>        &lt;input type=&quot;password&quot; class=&quot;form-control&quot;&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;modal-footer&quot;&gt;<br>    &lt;button class=&quot;btn btn-success&quot;<br>      [disabled]=&quot;!myForm.valid&quot;&gt;<br>      Submit Form<br>    &lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/form&gt;</pre><p>And the component.</p><pre>import { Component, Output, EventEmitter, Input } from &#39;@angular/core&#39;;<br>import { FormGroup, FormBuilder, FormControl, Validators } from &#39;@angular/forms&#39;;<br>import { NgbActiveModal } from &#39;@ng-bootstrap/ng-bootstrap&#39;;</pre><pre>@Component({<br>  selector: &#39;app-form-modal&#39;,<br>  templateUrl: &#39;./form-modal.component.html&#39;<br>})<br>export class FormModalComponent {</pre><pre>  @Input()id: number;<br>  myForm: FormGroup;</pre><pre>  constructor(<br>   public activeModal: NgbActiveModal,<br>   private formBuilder: FormBuilder<br>  ) {<br>    this.createForm();<br>  }</pre><pre>  private createForm() {<br>    this.myForm = this.formBuilder.group({<br>      username: &#39;&#39;,<br>      password: &#39;&#39;<br>    });<br>  }</pre><pre>  private submitForm() {<br>    this.activeModal.close(this.myForm.value);<br>  }<br>}</pre><p>This will currently log the form-values to the console, but you’ll do what it whatever you wish.</p><h4>Summary</h4><p>So we’ve achieved the goal of creating a form inside of our ng-boostrap modal. With this approach, you can pass id’s to the form-component, retrieving editable information. You can also pass the values back to the component that initialized it, updating a table or give the user a response.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=221e4f1f5648" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/creating-forms-inside-modals-with-ng-bootstrap-221e4f1f5648">Creating Forms Inside Modals with ng-bootstrap</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>