<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Nishan Bajracharya</title>
    <description>The latest articles on Forem by Nishan Bajracharya (@nishanbajracharya).</description>
    <link>https://forem.com/nishanbajracharya</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F50276%2Fd2c622cf-9f4f-4b62-889c-5b8ff0c19a8c.jpeg</url>
      <title>Forem: Nishan Bajracharya</title>
      <link>https://forem.com/nishanbajracharya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/nishanbajracharya"/>
    <language>en</language>
    <item>
      <title>Implementing the Observer pattern in JavaScript</title>
      <dc:creator>Nishan Bajracharya</dc:creator>
      <pubDate>Tue, 27 Nov 2018 17:23:14 +0000</pubDate>
      <link>https://forem.com/nishanbajracharya/implementing-the-observer-pattern-in-javascript-5heh</link>
      <guid>https://forem.com/nishanbajracharya/implementing-the-observer-pattern-in-javascript-5heh</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fss8ub4zt0vc89nao98js.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fss8ub4zt0vc89nao98js.png"&gt;&lt;/a&gt;Shamelessly borrowed from Wikipedia&lt;/p&gt;

&lt;p&gt;The observer pattern is a design pattern that observes an entity and on change, notifies all subscribers of the change. It is very simple to understand and is very effective for when a change in an entity needs to trigger many events.&lt;/p&gt;

&lt;h4&gt;
  
  
  How does the observer pattern work?
&lt;/h4&gt;

&lt;p&gt;The observer pattern is a combination of two elements, a &lt;strong&gt;Subject,&lt;/strong&gt; and an &lt;strong&gt;Observer&lt;/strong&gt;. The Subject tracks the value of an entity and the Observer listens for changes tracked by the Subject.&lt;/p&gt;

&lt;p&gt;When an entity tracked by the Subject changes, the Subject notifies the Observer of the change. One Subject can have many Observers, in which case it notifies all the Observers of the change in the entity. The observers can be subscribed to trigger events when the Subject notifies them.&lt;/p&gt;

&lt;h4&gt;
  
  
  So how do you implement the observer pattern in JavaScript?
&lt;/h4&gt;

&lt;p&gt;Let’s start with the Subject, which is alternatively called an &lt;strong&gt;Observable&lt;/strong&gt;. The subject contains a &lt;strong&gt;state&lt;/strong&gt; and a &lt;strong&gt;collection of observers&lt;/strong&gt; that it notifies to when the state changes.&lt;/p&gt;

&lt;p&gt;The subject provides methods to register and unregister observers and a method to notify all the observers.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Each observer has a notify method which the subject calls when it needs to notify observers for change in state.&lt;/p&gt;

&lt;p&gt;Next, let’s look at the Observer. It simply only contains a &lt;strong&gt;notify&lt;/strong&gt; method but we add a &lt;strong&gt;subscribe&lt;/strong&gt; method that is used to subscribe an event to the Observer. When the Subject notifies the Observer of change in state, the Observer triggers the subscribers.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The subscriber is a function that gets called when the Observer’s notify function is called.&lt;/p&gt;

&lt;h4&gt;
  
  
  How do you use it?
&lt;/h4&gt;

&lt;p&gt;We create a new subject that tracks the value of an entity and an observer for the subject an subscribe to the observer. Then when there is a change in the subject’s state, all the observers are notified and their subscribers are triggered.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The subject has two observers and each observer is subscribed by two functions. When the observable changes the state by calling the &lt;strong&gt;setState&lt;/strong&gt; method, both the observers are notified and each of their subscribers are triggered.&lt;/p&gt;

&lt;p&gt;And that is how the observer pattern works and how it is implemented in JavaScript.&lt;/p&gt;

&lt;h4&gt;
  
  
  An alternate and simpler approach
&lt;/h4&gt;

&lt;p&gt;While the above approach to implementing the observer pattern is more than enough, it requires creating at least one instance of the subject and one instance of the observer to work. So we can simplify the pattern using a single Observer class that maintains the state and also triggers the subscribers of the observer.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h4&gt;
  
  
  What are some practical use cases of the Observer Pattern?
&lt;/h4&gt;

&lt;p&gt;When done correctly, the observer pattern can be very powerful and extremely helpful for broadcasting information across an application. Some use cases of the observer pattern can be like so:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Group Messaging:&lt;/strong&gt; When a message is sent to a group chat, all the participants of the chat receive the notification of the new message.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Website Newsletters:&lt;/strong&gt; All subscribers of a website newsletter receive email notifications when the website publishes a new newsletter.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Redux:&lt;/strong&gt; When a redux action is dispatched, all the subscribers of the store are notified.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;References and Further Learning&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Observer_pattern" rel="noopener noreferrer"&gt;Observer pattern - Wikipedia&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.tutorialspoint.com/design_pattern/observer_pattern.htm" rel="noopener noreferrer"&gt;Design Patterns Observer Pattern&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://pawelgrzybek.com/the-observer-pattern-in-javascript-explained/" rel="noopener noreferrer"&gt;The Observer Pattern in JavaScript explained | pawelgrzybek.com&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>observer</category>
      <category>observerpattern</category>
      <category>designpatterns</category>
    </item>
    <item>
      <title>What I learned from building my own virtualized list library for React</title>
      <dc:creator>Nishan Bajracharya</dc:creator>
      <pubDate>Wed, 08 Aug 2018 08:20:26 +0000</pubDate>
      <link>https://forem.com/nishanbajracharya/what-i-learned-from-building-my-own-virtualized-list-library-for-react-45ik</link>
      <guid>https://forem.com/nishanbajracharya/what-i-learned-from-building-my-own-virtualized-list-library-for-react-45ik</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2qnqaec8jk0vtgdum23b.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2qnqaec8jk0vtgdum23b.png" width="800" height="450"&gt;&lt;/a&gt;Virtualized vs non-virtualized lists&lt;/p&gt;

&lt;p&gt;A project I’m working on has a contact list that needs to show 5000 contacts on average. That means 5000 complex DOM elements with lots of nested components need to be rendered on the screen. We knew when we started building this that rendering so many of these elements would be a very taxing operation on the DOM. And React, ever so dilligent, will absolutely render all the DOM elements if we were to map them into our view even if it kills our rendering performance.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  LIST_WITH_5000_ITEMS.map(item =&amp;gt; &amp;lt;ComplexListItem {...item} /&amp;gt;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we opted for a better approach than this. Our first approach was to use an infinite scroll component that would load 250 contacts at a time and after reaching to the end of the list would load another 250 contacts. This made the initial render performance better but would start to get considerably slower as you scroll to the end. This did not fix the original issue at hand.&lt;/p&gt;

&lt;p&gt;Our second approach was to use something called a virtualized list. This fixed the majority of our underlying rendering and performance issues related to the list DOM and scrolling and we could finally focus on optimizing the non-DOM related issues with the contact list logic, like a heavy fetch API request.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a virtualized list?
&lt;/h3&gt;

&lt;p&gt;A virtualized list is a technique where a large list of items in a scrollable view is virtually rendered to only show items that are visible within the the scrollable view window. That may sound like a handful but it basically means a virtualized list only renders items that are visible on the screen.&lt;/p&gt;

&lt;h3&gt;
  
  
  Why the need for this?
&lt;/h3&gt;

&lt;p&gt;Consider an application that deals with a large list of items, say 10000 rows in a list. What is the best and most performant way to render this list? Some would say a paginated list where rows are unmounted when the page is changed. But what about infinite scroll views, ones that add rows to the bottom of the current view once we scroll towards the bottom. Each of the rows are rendered and more rows get rendered as we scroll below.&lt;/p&gt;

&lt;p&gt;We could have a view window that can only show 20 items at a time but we are rendering tens of thousands of DOM elements. This is very ineffective and causes a lot of sluggish scrolling and unresponsive lists. This is no good.&lt;/p&gt;

&lt;p&gt;Ideally we would only render the items that are visible. The items outside of the view window don’t need the rendering power. Only when they come into the visible window do they need to be rendered. This is where virtualized list &lt;em&gt;comes into view&lt;/em&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Is this a new idea?
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhfoivr0o556g77xw7avf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhfoivr0o556g77xw7avf.png" width="800" height="610"&gt;&lt;/a&gt;react-virtualized by Brian Vaughn&lt;/p&gt;

&lt;p&gt;No. In fact, the idea of virtualized lists has been available for quite a while now. Android development has had the &lt;a href="https://developer.android.com/guide/topics/ui/layout/recyclerview" rel="noopener noreferrer"&gt;Recycler View&lt;/a&gt; since 2014, React Native provides &lt;a href="https://facebook.github.io/react-native/docs/virtualizedlist.html" rel="noopener noreferrer"&gt;VirtualizedList&lt;/a&gt; component out of the box and for React developers, we have a highly extensible library called &lt;a href="https://github.com/bvaughn/react-virtualized" rel="noopener noreferrer"&gt;react-virtualized&lt;/a&gt;. Each of these libraries and features may have different implementations, but they all try to fix the same issue.&lt;/p&gt;

&lt;h3&gt;
  
  
  What came next?
&lt;/h3&gt;

&lt;p&gt;I became interested in how a virtualized list works behind the scenes. A virtualized list doesn’t have any scrolling artifacts that you might expect considering it is rendering new items that come into view and un-rendering items that get out of the view on the fly. It works basically the same as a non virtualized list, showing the scrollbar on the side with the same functionality when dragging the scroll bar.&lt;/p&gt;

&lt;p&gt;So how does it imitate these behaviors and how is it keeping track of what elements are on the view? These were the burning questions running through my head when I started looking into the inner workings of a virtualized list. I had read a blog about virtualized list I had received from a friend a while back and all I remember from that is that instead of rendering a list as you would normally do, you use position: absolute on the elements and keep track of the scroll position of the list.&lt;/p&gt;

&lt;p&gt;So I started to work on my own implementation of a virtualized list in the form of a React library that I &lt;em&gt;brilliantly&lt;/em&gt; called &lt;a href="https://github.com/nishanbajracharya/react-virtualized-listview" rel="noopener noreferrer"&gt;react-virtualized-listview&lt;/a&gt; . Since I had already worked with react-virtualized , I was heavily inspired by that library’s API. And I also wanted something that a lot more simpler than all the various features that react-virtualized provided. Don’t get me wrong, react-virtualized is definitely among the best libraries of available for React, but it was a little daunting to start with because of all the various features it provides. I wanted something that was much easier to use and in the process of building the library, I would understand how virtualized list worked.&lt;/p&gt;

&lt;p&gt;An example of how this would work in code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const data = [1, 2, 3, 4, 5];

&amp;lt;List
  source={data}
  rowHeight={40}
  renderItem={({ index, style }) =&amp;gt; (
    &amp;lt;div key={index} style={style}&amp;gt;
      Hello {index}
    &amp;lt;/div&amp;gt;
  )}
/&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  So how does it work?
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq8ajiwjw29m08nk01k98.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq8ajiwjw29m08nk01k98.png" width="800" height="450"&gt;&lt;/a&gt;Props of a rendered list item&lt;/p&gt;

&lt;p&gt;Let’s take a list with a 1000rows. Say each row is 20pxin height. So we would have a list with a height of 20000px. This is where the virtualized list starts. It creates a DOM element that matches the width dimension of its parent visible window and a height that equals the total item count multiplied by the height of the item (20000px here). This is so that the position of the scrollbar perfectly imitates the behavior of a non-virtualized list. So scrolling the mouse wheel on the list and dragging the scrollbar both work as intended. The DOM element is empty at this point.&lt;/p&gt;

&lt;p&gt;Next we keep track of the scroll position within the list. This is the critical part of the virtualization. The scroll position determines which index we’re at in the list. This index coupled with the height of the visible window determines the indices that are visible and need to be rendered. The list item to be rendered is given a position: absolute style and a top value calculated using the index of the item and the row height of the item. So we only render the items that match the calculated indices.&lt;/p&gt;

&lt;p&gt;One additional trick we use to imitate a non-virtualized list is the &lt;em&gt;overscan.&lt;/em&gt; We render a small number of non-visible items above and below the visible window so that it appears like other items exist when scrolling, as opposed to just popping into view when it enters the visible window.&lt;/p&gt;

&lt;p&gt;A codesandbox example of the virtualized list in action&lt;/p&gt;

&lt;p&gt;&lt;a href="https://codesandbox.io/embed/r5kxmymx8q" rel="noopener noreferrer"&gt;React virtualized listview on Codesandbox&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;More on virtualized lists.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://github.com/nishanbajracharya/react-virtualized-listview" rel="noopener noreferrer"&gt;nishanbajracharya/react-virtualized-listview&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://github.com/bvaughn/react-virtualized" rel="noopener noreferrer"&gt;bvaughn/react-virtualized&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://dev.to/bnevilleoneill/rendering-large-lists-with-react-virtualized-2p8b"&gt;Rendering large lists with React Virtualized&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/outsystems-engineering/virtualizing-the-virtual-dom-pushing-react-further-d76a16e5f209" rel="noopener noreferrer"&gt;Virtualizing The Virtual DOM — Pushing React Further&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://sergimansilla.com/blog/virtual-scrolling/" rel="noopener noreferrer"&gt;Virtual list in vanilla JavaScript&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>react</category>
      <category>virtualized</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Using SVG Icons Components in React</title>
      <dc:creator>Nishan Bajracharya</dc:creator>
      <pubDate>Tue, 13 Mar 2018 14:39:15 +0000</pubDate>
      <link>https://forem.com/nishanbajracharya/using-svg-icons-components-in-react-163k</link>
      <guid>https://forem.com/nishanbajracharya/using-svg-icons-components-in-react-163k</guid>
      <description>&lt;p&gt;SVGs are cool. They scale up. They scale down. Sometimes they try to kill you in your sleep but you know, necessary evil and stuff.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2A7I6hcXUXbAxL5Uzn." class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1024%2F0%2A7I6hcXUXbAxL5Uzn."&gt;&lt;/a&gt;Photo by &lt;a href="https://unsplash.com/@nordwood?utm_source=medium&amp;amp;utm_medium=referral" rel="noopener noreferrer"&gt;NordWood Themes&lt;/a&gt; on &lt;a href="https://unsplash.com?utm_source=medium&amp;amp;utm_medium=referral" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;So what’s good about SVG?&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;SVG or Scalable Vector Graphics are XML-based image formats that can be scaled to any size while maintaining the quality of the image. So when you need an image that needs to be scaled as big or as small as you want, SVGs are the way to go. They’re basically XML documents so their file sizes also tend to be tiny compared to other image formats.&lt;/p&gt;

&lt;p&gt;Also they are effectively XML elements and can be manipulated using CSS. So changing colors and strokes on SVG can be done all via CSS.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Sounds good. What about the bad stuff?&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;When it comes to images, SVGs are great for simple shapes, full of basic strokes and color. Anything more complex than icons though and they are not worth the hassle. (Unless you’re doing data visualizations, in which case, let me point you towards &lt;a href="https://d3js.org/" rel="noopener noreferrer"&gt;D3.js&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;It is also more complicated to build SVGs on your own. Since they are structured in XML, building one can be harder than an equivalent raster image, which stores pixels data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe22hrwl8b8mximejoy0n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe22hrwl8b8mximejoy0n.png"&gt;&lt;/a&gt;Scaling — Raster vs Vector&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Where does React come into all this?&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;When using SVG in a web document, you have two options. Either render the SVG document as is, or use it as source in the &lt;strong&gt;&lt;em&gt;img&lt;/em&gt;&lt;/strong&gt; tag. The preferable option is to use it as is, since SVG in the image tag is rendered as an image and cannot be manipulated beyond the css styles for the image tag.&lt;/p&gt;

&lt;p&gt;So when deciding on using SVG in a React project, it is preferable to build a component than render the SVG into the document.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Svg = () =&amp;gt; 
 &amp;lt;svg
 width="100%"
 height="100%"
 viewBox="0 0 32 32"
 xmlns="http://www.w3.org/2000/svg"
 xmlnsXlink="http://www.w3.org/1999/xlink"
 &amp;gt;
   &amp;lt;path d="some path here" fill="#000" /&amp;gt;
 &amp;lt;/svg&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This would render a static SVG into the html document. Let’s add some props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Svg = ({
 style = {},
 fill = '#fff',
 width = '100%',
 className = '',
 height = '100%',
 viewBox = '0 0 32 32',
}) =&amp;gt; 
 &amp;lt;svg
 width={width}
 style={style}
 height={height}
 viewBox={viewBox}
 className={className}
 xmlns="http://www.w3.org/2000/svg"
 xmlnsXlink="http://www.w3.org/1999/xlink"
 &amp;gt;
   &amp;lt;path d="some path here" fill={fill} /&amp;gt;
 &amp;lt;/svg&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can now use this component to render SVG of different colors, classnames and styles. Check out a CodeSandbox demonstration below.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://codesandbox.io/s/q79o54pxmj" rel="noopener noreferrer"&gt;&lt;em&gt;Link to CodeSandbox&lt;/em&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;OK, so we now have a general idea of how we can create React components for SVG icons. How do we deal with a large plethora of icons then, which is quite common in large projects? Here we have multiple options to go for. We could have a giant component which returns the required SVG icon or create a mapper component that takes in a prop and maps it to the equivalent SVG component.&lt;/p&gt;

&lt;p&gt;Let’s take a look at how they can be achieved.&lt;/p&gt;

&lt;h4&gt;
  
  
  Approach #1
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://codesandbox.io/s/ryy418r5km" rel="noopener noreferrer"&gt;&lt;em&gt;Link to CodeSandbox&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; We create a single SVG component and pass a &lt;strong&gt;&lt;em&gt;name&lt;/em&gt;&lt;/strong&gt; prop to it. The component resolves the viewBox and path values associated with the icon and returns the SVG element.&lt;/p&gt;

&lt;p&gt;Lets start with adding the name prop to our SVG component and resolve the path for that name prop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getPath = (name, props) =&amp;gt; {
 switch(name) {
 case 'icon-1':
 return &amp;lt;path {...props} d="icon-1-path" /&amp;gt;;
 case 'icon-2':
 return &amp;lt;path {...props} d="icon-2-path" /&amp;gt;;
 default:
 return &amp;lt;path /&amp;gt;;
 }
}

const Svg = ({
 name = '',
 style = {},
 fill = '#000',
 width = '100%',
 className = '',
 height = '100%',
 viewBox = '0 0 32 32',
}) =&amp;gt; 
 &amp;lt;svg
 width={width}
 style={style}
 height={height}
 viewBox={viewBox}
 className={className}
 xmlns="http://www.w3.org/2000/svg"
 xmlnsXlink="http://www.w3.org/1999/xlink"
 &amp;gt;
   {getPath(name, { fill })}
 &amp;lt;/svg&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Works great. But we haven’t considered that each SVG icons can have their own viewBox values. So we also need to resolve the viewBox based on the name prop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const getViewBox = name =&amp;gt; {
 switch(name) {
 case 'icon-1':
 return 'icon-1-view-box'; // Eg. 0 0 32 32
 default:
 return '';
 }
}

&amp;lt;Svg
 width={width}
 style={style}
 height={height}
 className={className}
 viewBox={getViewBox(name)}
 xmlns="http://www.w3.org/2000/svg"
 xmlnsXlink="http://www.w3.org/1999/xlink"
&amp;gt;
 {getPath(name, { fill })}
&amp;lt;/Svg&amp;gt;;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that’s it. We can add more paths and viewBoxes to this component and use it by adding the name prop for the icon we need.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;Svg fill="#49c" width={100} name="icon-1" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Approach #2
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://codesandbox.io/s/vvzkzwvp10" rel="noopener noreferrer"&gt;&lt;em&gt;Link to CodeSandbox&lt;/em&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; We create separate files for each SVG icon and create an index file that returns the SVG component based on the &lt;strong&gt;&lt;em&gt;name&lt;/em&gt;&lt;/strong&gt;  prop.&lt;/p&gt;

&lt;p&gt;We create separate components for each SVG icon we want.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./icons
--/Phone.js
--/Trash.js
--/Messages.js
--/Envelope.js
--/Wifi.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Each component is independent of one another and can be used on their own.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Phone from './icons/Phone';

&amp;lt;Phone width={100} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We then create an index file that returns the component itself based on the name prop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;./icons
--/Phone.js
--/Trash.js
--/Messages.js
--/Envelope.js
--/Wifi.js
--/...
--/index.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The index file would look something like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';

import Phone from './Phone';
import Messages from './Messages';

const Icon = props =&amp;gt; {
 switch(props.name) {
 case "phone":
 return &amp;lt;Phone {...props} /&amp;gt;;
 case "messages":
 return &amp;lt;Messages {...props} /&amp;gt;;
 default:
 return &amp;lt;div /&amp;gt;;
 }
}

export default Icon;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So anytime we need to add new icons into the mix, we create new components and include them in the index file. We use this component by importing a single Icon component and sending the &lt;strong&gt;&lt;em&gt;name&lt;/em&gt;&lt;/strong&gt; prop into it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Icon from './icons';

&amp;lt;Icon fill="#49c" width={100} name="phone" /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that’s it. I’ve detailed a few ways to create React components to manipulate SVG images. Of course these aren’t the only ways, or the even best ways to deal with SVGs in React applications. Just like anything in the world of Javascript, there are always other options at our disposal.&lt;/p&gt;

&lt;h4&gt;
  
  
  Alternate options
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://github.com/webpack-contrib/svg-inline-loader" rel="noopener noreferrer"&gt;Webpack SVG Loader&lt;/a&gt; — A &lt;a href="https://webpack.js.org/" rel="noopener noreferrer"&gt;webpack&lt;/a&gt; loader to import SVG files as components.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/gilbarbara/react-inlinesvg" rel="noopener noreferrer"&gt;React Inline SVG&lt;/a&gt; — A react component that takes SVG file paths as prop to render them on the document.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This article was last published in Medium. &lt;a href="https://blog.lftechnology.com/using-svg-icons-components-in-react-44fbe8e5f91" rel="noopener noreferrer"&gt;Using SVG Icons Components in React&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;




</description>
      <category>react</category>
      <category>programming</category>
      <category>webdev</category>
      <category>svg</category>
    </item>
  </channel>
</rss>
