<?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 Sarah Sweat on Medium]]></title>
        <description><![CDATA[Stories by Sarah Sweat on Medium]]></description>
        <link>https://medium.com/@sarahsweat?source=rss-71bead4da933------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1iVycD4ooqnqFs6G16xHnQ.jpeg</url>
            <title>Stories by Sarah Sweat on Medium</title>
            <link>https://medium.com/@sarahsweat?source=rss-71bead4da933------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 00:41:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sarahsweat/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[Unit Testing for React with Jest Snapshots]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/unit-testing-for-react-with-jest-snapshots-ae3e6f58fe07?source=rss-71bead4da933------2"><img src="https://cdn-images-1.medium.com/max/2600/1*-ye3EXXGQUjId6cmmpW_HA.jpeg" width="4032"></a></p><p class="medium-feed-snippet">Jest Snapshots are increasingly being used to test React Components. Snapshots are generally testing the initial rendering of a component&#x2026;</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/unit-testing-for-react-with-jest-snapshots-ae3e6f58fe07?source=rss-71bead4da933------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/unit-testing-for-react-with-jest-snapshots-ae3e6f58fe07?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae3e6f58fe07</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Sun, 31 May 2020 19:56:34 GMT</pubDate>
            <atom:updated>2020-06-01T12:10:28.099Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[DRY Up Your Code with GraphQL Fragments]]></title>
            <link>https://levelup.gitconnected.com/dry-up-your-code-with-graphql-fragments-4d080e4f545e?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d080e4f545e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 06:03:48 GMT</pubDate>
            <atom:updated>2019-06-11T14:12:43.307Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N5ZtsTNNMM9Ht2i6" /><figcaption>Photo by <a href="https://unsplash.com/@katycao?utm_source=medium&amp;utm_medium=referral">Katy Cao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have been learning about using GraphQL and Apollo in my React applications. This blog post is going to assume you have a basic understanding of both technologies and will specifically address using GraphQL fragments in queries defined using Apollo. If you want to learn more about using Apollo and GraphQL with React, I have links to documentation at the end of the article.</p><h3>My problem</h3><p>For my app, I was want to allow users to find recipes in two ways. 1) Supplying a search term and showing a limit of 50 results that were related to the term, and also allow for paging through results if necessary. 2) Allow users to search for a specific recipe by a unique ID and only return the single result. I no longer needed to account for limiting, paging, etc.</p><p>In both cases I wanted to receive the same type of result per recipe. A recipe object returned from both queries should have the same attributes, such as id, title, image, bylines, etc.</p><p>Check out the code below and see the two queries I was using to accomplish this:</p><p><strong>Use case 1:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1652980148013ced79abec2bb3945572/href">https://medium.com/media/1652980148013ced79abec2bb3945572/href</a></iframe><p><strong>Use case 2:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d45138c5cee07cfabfcb1697cdf59a1/href">https://medium.com/media/3d45138c5cee07cfabfcb1697cdf59a1/href</a></iframe><p>As I am sure you noticed, there are several repeated lines here. All of the attributes on a Recipe have been repeated between the two queries. If only there were a way to clean this up and reduce the amount of code I needed to write………..</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F116seTvbXx07F6%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F116seTvbXx07F6%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F116seTvbXx07F6%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="336" frameborder="0" scrolling="no"><a href="https://medium.com/media/e04ac4707178edfcafdec296425a2cf3/href">https://medium.com/media/e04ac4707178edfcafdec296425a2cf3/href</a></iframe><h3>My Solution</h3><p>In order to write the query attributes once, we can use an Apollo/GraphQL Fragment which can be reused in multiple queries.</p><p>At its most simple definition:</p><blockquote>“A <a href="http://graphql.org/learn/queries/#fragments">GraphQL fragment</a> is a shared piece of query logic.” — Apollo documentation (referencing the base GraphQL concept. )</blockquote><p>Also according to the Apollo documentation, there are two principal uses for fragments in Apollo:</p><ul><li>Sharing fields between multiple queries, mutations, or subscriptions.</li><li>Breaking your queries up to allow you to co-locate field access with the places they are used.</li></ul><p>In my case, I am more concerned with the first point, and that’s what I will address here to clean up these two recipe queries.</p><p>First, lets define our fragment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd31e0e912a7d8c428099486d7c8d6ef/href">https://medium.com/media/bd31e0e912a7d8c428099486d7c8d6ef/href</a></iframe><p>You can see on line 1 that I am importing the gql tag from apollo-boost so that I can write my query in React more easily. Then I define a constant in which I am defining the fragment. The name RECIPE_ATTRIBUTES is referring to this segment of gql code so that we can bring it into our other queries later. This is not the fragment itself, just the container for some gql code.</p><p>The snippet of code within our tag is using the fragment key word to define the actual section of code we want to reuse. In this case I have named my fragment recipeAttributes. I put on Recipe after this declaration because that is the type to which these attributes belong.</p><p>Now that I have my fragment defined, I need to add it to my queries and replace the duplicate code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9c1712ef90d22c98c7006e7556ec24a/href">https://medium.com/media/f9c1712ef90d22c98c7006e7556ec24a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6gDPXMNxFhvHdcf6%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6gDPXMNxFhvHdcf6%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExamZkZzIwdW84N3hhanFtbG1oNWl5a2Z4MGd6M25kbTAyYjFrdjZyMyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3o6gDPXMNxFhvHdcf6%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="235" frameborder="0" scrolling="no"><a href="https://medium.com/media/f96c6e6c9a4683f6e5a3dab5270904e5/href">https://medium.com/media/f96c6e6c9a4683f6e5a3dab5270904e5/href</a></iframe><p>That just got so much shorter! I brought in my RECIPE_ATTRIBUTES constant which I had previously defined and interpolated it after the query but still within the gql tag. I then was able to reference the fragment that I had defined as recipeAttributes within my existing query.</p><p>This leaves me with my final code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97888c3106fa097a0ff5b88bec486157/href">https://medium.com/media/97888c3106fa097a0ff5b88bec486157/href</a></iframe><p>To recap, we just wrote a GraphQL fragment in our Apollo gql tag in order to encapsulate and reuse the definition of how we want our recipes to be returned to us. This helps us to enforce the Single Responsibility Principe(SRP). Quick recap on SRP:</p><p><em>“The Single Responsibility Principle (SRP) is one of the five so-called SOLID principles, developed and promoted by Robert C. Martin to help developers produce flexible and maintainable code. In short, the SRP says that a given module or class should have responsible for a single element of a program’s functionality, and thus have just a single reason to change.” — </em><a href="https://medium.com/@severinperez/writing-flexible-code-with-the-single-responsibility-principle-b71c4f3f883f"><em>Severin Perez</em></a></p><p>This also helped us to have a single source of truth for recipes returned to our front end through GraphQL. We have defined the expected recipe attributes in one place.</p><p>Not only do we have a separate variable to hold our query vs our recipe definition and have the structure of recipe result defined in a single place, but also we have reduced the quantity and complexity of our code! Win win!</p><p>Hope this helps you as much as it did me!</p><p><a href="https://graphql.org/learn/">Introduction to GraphQL | GraphQL</a></p><p><a href="https://www.apollographql.com/docs/react/">https://www.apollographql.com/docs/react/</a></p><p><a href="https://www.apollographql.com/docs/react/advanced/fragments/">https://www.apollographql.com/docs/react/advanced/fragments</a></p><p><a href="https://gitconnected.com/learn/graphql">Learn GraphQL - Best GraphQL Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d080e4f545e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/dry-up-your-code-with-graphql-fragments-4d080e4f545e">DRY Up Your Code with GraphQL Fragments</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Context API as an Alternative to State Management Libraries]]></title>
            <link>https://levelup.gitconnected.com/react-context-api-as-an-alternative-to-state-management-libraries-cd061e3f70a2?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd061e3f70a2</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Thu, 18 Apr 2019 01:11:43 GMT</pubDate>
            <atom:updated>2019-04-18T01:11:43.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BeYUlBsXZkU-Nv4O" /><figcaption>Photo by <a href="https://unsplash.com/@kirill23?utm_source=medium&amp;utm_medium=referral">Kirill Petropavlov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the past I have generally reached for libraries like MobX or Redux in order to manage the state in my app and to expose values that I want to access globally, throughout my app. It prevents me from having to pass things around via props and also segregates reused data and actions from simple component-level logic. React’s new Context API has introduced a simple solution for these smaller use cases. There are still instances when Redux and MobX are the right answer, but many times using React’s Context API can get the job done.</p><p>In this post, I am going to do a basic introduction to Context and a quick demo of how to initialize a context with values and then access those values elsewhere in my app.</p><p>I am building this in my Storybook Playground so that I am not launching a whole new app. You can read how I built this environment in one of my previous blog posts:</p><p><a href="https://medium.freecodecamp.org/how-to-build-a-react-development-playground-using-storybook-667ef9808e9f">How to build a React development playground using Storybook</a></p><h3>What is React’s Context API?</h3><blockquote>Context provides a way to pass data through the component tree without having to pass props down manually at every level. — <a href="https://reactjs.org/docs/context.html">React JS documentation</a></blockquote><p>This is most beneficial when you have global data that many components will want to use such as theme attributes, user data, etc.</p><p>There are three main steps in using context:</p><ol><li>Creating your context</li><li>Providing it to your app</li><li>Consuming it in a nested component</li></ol><p>Now, lets build a simple app that renders a message in a nested component.</p><p>This will make more sense as we go through in detail, but as an overview: In this example, I am going to render Component1 which will render Component2 which will render Component3 . Component1 will be where the app is Provided the context and Component3 is where the context will be consumed.</p><h3>Step 1: Create your Context</h3><p>First you must define the default value for your context. This is only used in the case where you try to consumer your context outside of your provider. To simplify this, my default value is also going to be my initial value which will make more sense in the next step. But for now, in the code below you can see a defined initialValue object. This object is responsible for holding the key value pairs of your context. In this case just a message which is a string.</p><pre>const initialValue = {  message: &quot;This is my message from context&quot;}</pre><pre>export const MyContext = React.createContext(initialValue)</pre><h3>Step 2: Provide this value to your app</h3><p>Next we need to let our app know what this value is and in this case, we are going to provide it with the above defined initialValue . You can do this by wrapping the component which holds the part of your app you want to have access to this information. For example, if you had some user data that only your navBar needed to know about, you could wrap just the navBar in a context specific to user data.</p><p>In the example, we want to wrap a top-level component (Component1) with a Provider containing my initial value. I did this by implementing the following:</p><pre>export const Component1 = () =&gt; (  <br>  &lt;MyContext.Provider value={initialValue}&gt;<br>    &lt;HomeWrapper&gt;      <br>      &lt;h1&gt;This is Component 1&lt;/h1&gt;<br>      &lt;Component2 /&gt;    <br>    &lt;/HomeWrapper&gt;  <br>  &lt;/MyContext.Provider&gt;<br>)</pre><h3>Step 3: Consume the value of your context</h3><p>The final step is to consume the value of your app in a child component of your Provider. This is accomplished by wrapping the consuming child component with your context’s consumer which can be accessed by importing your context and rendering its consumer like &lt;MyContext.Consumer&gt;&lt;/MyContext.Consumer&gt; .</p><p>Once you are within the Consumer I am using the render props pattern in order to access the value of my context. I can also destructure the value and only bring in the keys of my value object that I need.</p><p>See the code below for the actual implementation.</p><pre>import { MyContext } from &#39;./Component1&#39;<br> <br>const Component3 = () =&gt; (<br>  &lt;MyContext.Consumer&gt;<br>    {({message}) =&gt; &lt;&gt;<br>      &lt;h3&gt;Component 3&lt;/h3&gt;<br>      message: &lt;h3&gt;{message}&lt;/h3&gt;<br>    &lt;/&gt;}<br>  &lt;/MyContext.Consumer&gt;<br>)</pre><p>If you want to learn more about Render Props, check out my blog post on the topic. The link is at the end of the article.</p><p>Amazing! Now let’s see this in action and if we are getting our message value down into Component3 . We can test this by using Storybook to create a story for Component1 and see if it renders the context value in the nested Component3 . My story is written like:</p><pre>import React from &#39;react&#39;<br>import { storiesOf } from &#39;@storybook/react&#39;<br>import { Component1 } from &#39;./Component1&#39;</pre><pre>storiesOf(&#39;Context API Project&#39;, module)<br>  .add(&#39;Component1&#39;, () =&gt; &lt;Component1 /&gt;)</pre><p>and should then output something like the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRigGkDlKcVcyXIjY2AJAA.png" /></figure><p>Yay! We now see the message that was defined in the initialValue of MyContext being rendered within Component3 . Success!</p><p>Now, imagine all of the use cases for this and why its helpful… Following the Single Responsibility Principle, we have extracted out the storage of this information and letting the context be in charge of it, while the component just needs to worry about consuming it and displaying it. This is allowing for greater reusability of our component as I can change the context and it can then display a different message.</p><p>In the case of creating a theme context, you can have multiple themes as a set of values for fonts, colors, etc. for various brands or looks. Then, in order to change the display of a component, you would need to change the value in your provider to a different theme. Since the nested components all depend on only the context value and nothing is hardcoded or needs redefining.</p><p>For further clarification, I included the code for this project in full below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe6465a282f9c5f7d9d4da3f187d0d90/href">https://medium.com/media/fe6465a282f9c5f7d9d4da3f187d0d90/href</a></iframe><p>Resources:</p><ul><li><a href="https://reactjs.org/docs/context.html">Context - React</a></li><li><a href="https://medium.freecodecamp.org/how-to-build-a-react-development-playground-using-storybook-667ef9808e9f">How to build a React development playground using Storybook</a></li><li><a href="https://levelup.gitconnected.com/improve-code-reusability-with-reacts-render-prop-pattern-1928beaee1a4">Improve Code Reusability With React’s Render Prop Pattern</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd061e3f70a2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/react-context-api-as-an-alternative-to-state-management-libraries-cd061e3f70a2">React Context API as an Alternative to State Management Libraries</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</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 build a React development playground using Storybook]]></title>
            <link>https://medium.com/free-code-camp/how-to-build-a-react-development-playground-using-storybook-667ef9808e9f?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/667ef9808e9f</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 16:53:30 GMT</pubDate>
            <atom:updated>2019-04-02T17:33:36.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7GPOPeGqBSteTFBK" /><figcaption>Photo by <a href="https://unsplash.com/@goshua13?utm_source=medium&amp;utm_medium=referral">Joshua Aragon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Lately, I have been wanting to try new things and test out new technologies or patterns in my React components. I needed a place where I could test these things out without launching a new app every time.</p><p>I recently started using React storybook at work in order to establish a new design system for future projects. I also used it to prototype several versions of a new content authoring tool our team is working on. Putting this tool together with my desire to create components and play around with new things in a low stakes way seemed perfect. A few examples of these new “things” are React Context, SlateJs, and React Hooks.</p><p>This could also be used as a portfolio and a great way to showcase your work. Since Storybook can be deployed as its own app, you can host a webpage where you have a variety of projects and components you can display to potential employers or clients. Once deployed, it’s as easy as sending them a link to your storybook!</p><p>This post will focus on creating the Storybook for React environment and I will aim to post in the future about what I create inside of it!</p><h3>Sooo… What is Storybook?</h3><p>Taken straight from the Storybook website because I couldn’t say it better myself:</p><blockquote>“Storybook is a user interface development environment and playground for UI components. The tool enables developers to create components independently and showcase components interactively in an isolated development environment.</blockquote><blockquote>Storybook runs outside of the main app so users can develop UI components in isolation without worrying about app specific dependencies and requirements.”</blockquote><p>That means… I can create and display/interact with components independently of actually running the React app! And since this project won’t be focused on a single app’s performance or DRYness, I can have multiple prototypes and versions of components so that I can perfect them, allow stakeholders to approve, etc. before bringing them into the app for which they were intended for. I can also use it to just practice making components and testing how to use the new tech I mentioned before.</p><p>Let’s get building now!</p><h3>Create a base React app</h3><pre>npx create-react-app my-playground</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24nxmOxNMmj9yCRagILQjA.png" /></figure><p>You can ensure that your app was created successfully by running yarn start . A new window should appear on your browser to localhost:3000 that looks like the picture above. Once confirmed you can stop it by pressing ⌘ + C.</p><h3>Add Storybook</h3><p>First, from the command line within your project, you will need to add storybook with the following command:</p><pre>npx -p <a href="http://twitter.com/storybook/cli">@storybook/cli</a> sb init</pre><p>Then, you can run storybook by using:</p><pre>yarn storybook</pre><p>Now you should be up and running, seeing a screen in your browser like the one below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmEHtaKS4Pm-b10v04YLew.png" /><figcaption>browser view of storybook</figcaption></figure><p>If you look within your project folder, you will notice that some files have been added and others updated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*VMmKMO3D-2AHC2KZKtWssg.png" /></figure><p>The ./storybook folder is home to where you will configure a lot of the settings for your storybook. There are all sorts of add-ons you can apply to your project to add more features. The config.js file is generally where you will apply add-ons and also tell storybook where to find your stories. The config defaults to the following:</p><pre>import { configure } from &#39;@storybook/react&#39;;</pre><pre>function loadStories() {<br>  require(&#39;../src/stories&#39;);<br>}</pre><pre>configure(loadStories, module);</pre><p>This is telling storybook to look in the ../src/stories folder for the stories you have written. Right now, storybook has gone ahead and added a few default stories for you. You can take a look at those to get an idea of how to write the stories. You are ultimately just rendering your components within their own functions and you can pass them whatever props you like.</p><p>As you can see in the example it gives you below, you can create multiple versions of the same component by just rendering it with different props.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESyNl50wiRuzkT06-F9nhQ.png" /></figure><p>You can imagine though, once you start creating more components, this file could get very large and you don’t want to have to spell out in your config every file with stories in it that you want rendered… Instead, a handy way to to do this is to name any file in your src folder with stories.js and to let storybook dynamically find all files named with stories.js at the end, within your src folder you would put the following in your config file:</p><pre>import { configure } from &#39;@storybook/react&#39;</pre><pre>function loadStories() {<br>  const req = require.context(&#39;../src&#39;, true, /\.stories\.js$/)<br>  req.keys().forEach(filename =&gt; req(filename))<br>}</pre><pre>configure(loadStories, module)</pre><p>This allows for a much cleaner file structure and you can organize your stories by project or even by component within your src folder.</p><h3>Build Your Mini Projects</h3><p>Let’s build a small component as an example to show how you could spin up a quick example project to start learning React’s Context API. Within my src folder I am going to create a ContextProject folder where I am going to add a file where I will define my component, and then another where I will define the story:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wD_qrCicYMO410LZyRpZPw.png" /></figure><p>Now when I check my Storybook, I will see that I have a menu option for my Context API Project and below that, I can click to see my Home component I created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUZ4bLx3-ppfeTmx1efqog.png" /></figure><p>And now I can start building out my context and other components within this folder in src. I will be able to play around and render the components I build, allowing me to quickly see my changes and not have to worry about launching a new React app every time I want to just test out a specific feature or new idea.</p><p>This also allows for a lot of flexibility when trying to quickly prototype a new idea. You already have an environment up and running and can have your favorite libraries like styled components already installed or have pre-defined themes that can just be easily imported into new projects. You can also pre-define some baseline components such as styled headings, divs, buttons etc that you can share across projects to make development go even faster.</p><p>Hope this helps and stay tuned for future posts about my favorite add-ons and details on the test projects I build in my Storybook.</p><p>Happy Coding!</p><p>References:</p><p><a href="https://storybook.js.org/">Storybook: Frontend workshop for UI development</a></p><p>My github Repo:</p><p><a href="https://github.com/sarahsweat/my-playground">sarahsweat/my-playground</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=667ef9808e9f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/how-to-build-a-react-development-playground-using-storybook-667ef9808e9f">How to build a React development playground using Storybook</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improve Code Reusability With React’s Render Prop Pattern]]></title>
            <link>https://levelup.gitconnected.com/improve-code-reusability-with-reacts-render-prop-pattern-1928beaee1a4?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/1928beaee1a4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[render-props]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 00:22:59 GMT</pubDate>
            <atom:updated>2019-04-02T00:22:59.990Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UWK3dTK7hAMXo4Sp" /><figcaption>Photo by <a href="https://unsplash.com/@emilep?utm_source=medium&amp;utm_medium=referral">Émile Perron</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you are a React developer and working with new and/or previously built components every day, you have likely started to notice patterns of repeated logic in your code. This could be as simple as creating multiple functions in a single component to change different keys of state, or it could be on the scale of creating several components which are slightly different versions of the same thing. This post will focus on solving the latter and refactoring a toggle component to be reusable by following the render prop pattern with functions as child components.</p><h3>The Original Component</h3><p>This component is just a regular React component which holds state and toggles a boolean held in state when a button is clicked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*k_0HBp7iGoiC0awzzR3nhg.gif" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e09c9033d0baaccf44e33ffdf87a09/href">https://medium.com/media/70e09c9033d0baaccf44e33ffdf87a09/href</a></iframe><h3>Violation of Single Responsibility Principle</h3><p>So the component above does what we want it to do, but it isn’t flexible or reusable because it doesn’t follow the Single Responsibility Principle. What is that you ask?</p><blockquote>“The Single Responsibility Principle (SRP) is one of the five so-called SOLID principles, developed and promoted by Robert C. Martin to help developers produce flexible and maintainable code. In short, the SRP says that a given module or class should have responsible for a single element of a program’s functionality, and thus have just a single reason to change.” —<a href="https://medium.com/@severinperez/writing-flexible-code-with-the-single-responsibility-principle-b71c4f3f883f"> Severin Perez</a></blockquote><p>If you want to learn more about Single Responsibility Principle, check out the Severin Perez’s article (linked at the quote above and in references at the end of this article.)</p><p>When looking at our original component, we can see that it is responsible for several different bits of logic:</p><ol><li>Rendering a wrapping element with a heading.</li><li>Managing state of a toggle.</li><li>Rendering a div with a button and conditional text.</li></ol><p>This will begin to create problems when we try to reuse this component with alterations or we might notice a pattern of copying the same logic in other places, both signs that I need to re-examine my code and separate its concerns.</p><h3>Refactor #1</h3><p>Let&#39;s make a first pass at refactoring and try to split our original component up so it has a parent component which will be responsible for managing state and then renders a functional component which will be responsible for the button and conditional text, thus separating concern 3 from 1 &amp; 2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c404148f8fad15d9e7a66e84e8a8e741/href">https://medium.com/media/c404148f8fad15d9e7a66e84e8a8e741/href</a></iframe><p>Our functional component ToggleWindow addresses concern 3 and takes props of a function toggle and a value isToggled, and renders the elements it needs with the information given. Toggler is now only responsible for concerns 1 &amp; 2.</p><p>While that’s somewhat cleaner, what happens when we want to reuse the Toggler logic but render a different button and conditional text or better yet, a different parent container too…</p><p>We can break this out by using the render prop pattern and passing the children of the Toggler the additional parameters it needs through a function call.</p><p>First though…</p><h3>What are render props?</h3><p>According to React’s documentation:</p><blockquote>The term <a href="https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce">“render prop”</a> refers to a technique for sharing code between React components using a prop whose value is a function.</blockquote><blockquote>A component with a render prop takes a function that returns a React element and calls it instead of implementing its own render logic.</blockquote><p>So this means we can define the children of a Toggler component to be a function that we can give additional parameters to, in order to implement our toggling logic.</p><h3>Refactor #2</h3><p>If we keep the toggling logic in its own component, I can then define just two functional components when I want to use it in subsequent use cases. This will also fully differentiate and separate the concerns we talked about before.</p><p>If you’re a bit confused, don’t worry, the code does a better job of explaining it. I have created an example below where I have two separate components which have different styling and content specifications for both the parent and child element. Both of them get the Toggler logic component “added” to it, but don’t need to redefine it. Take a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*kAaKQ1dfEgRWWyyuyoV9Lg.gif" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a970a9512820116d4e38cbd76c49e152/href">https://medium.com/media/a970a9512820116d4e38cbd76c49e152/href</a></iframe><p>We have now adhered to the Single Responsibility Principle, which makes our code more loosely coupled, reusable and maintainable. We have separated our 3 main concerns into different definitions allowing them to exist on their own and when they need to be edited, changed or reused in the future, the relevant code is one spot, easily found and adaptable.</p><p>The toggling logic was reused in the same way for each of the two different implementations. I created 2 use cases of functional/presentational components that utilize the Toggler, but reusing the Toggler in both cases, not redefining or altering it.</p><p>While this is a rather small and basic example, imagine how you can expand this pattern to larger and more complex logic patterns, such as data fetching or larger state management tasks. This could become much more useful if applied across your code base.</p><p>Stay tuned for my next blog post on the React Context API which utilizes this pattern to add predefined logic and values into specific components.</p><p>Resources:</p><ul><li><a href="https://reactjs.org/docs/render-props.html">Render Props - React</a></li><li><a href="https://medium.com/@severinperez/writing-flexible-code-with-the-single-responsibility-principle-b71c4f3f883f">Writing Flexible Code with the Single Responsibility Principle</a></li><li><a href="https://gitconnected.com/learn/react">Learn React - Best React Tutorials (2019) | gitconnected</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1928beaee1a4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/improve-code-reusability-with-reacts-render-prop-pattern-1928beaee1a4">Improve Code Reusability With React’s Render Prop Pattern</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Componentized and Reusable “Scroll to Top” Feature in React]]></title>
            <link>https://levelup.gitconnected.com/building-a-componentized-and-reusable-scroll-to-top-feature-in-react-7fa5ac8d4c2d?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fa5ac8d4c2d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[scroll]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Fri, 08 Mar 2019 19:12:07 GMT</pubDate>
            <atom:updated>2019-03-08T22:04:13.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skVKVqQWil2ZYe71ef92ig.gif" /></figure><p>Ok, so my task at hand is to create a scroll-to-top feature which allows the user experience to be as follows:</p><ul><li>as soon as the filters have scrolled out of sight, a greyed “Back to Top” button would appear.</li><li>Upon hovering over the button, it should wiggle and turn black.</li><li>Upon clicking the button, the page should go back to the top and the button would disappear.</li></ul><p>Above and below you will see the visual implementation of this feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kas-tmSRKkZ8wulRxyVhCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7NGD7aa28466ovY8rpJKFw.png" /><figcaption>Scrolled to the top with no button (Left) and scrolled down with the button to “scroll to Top” (Right)</figcaption></figure><p>One of the main considerations in creating this component was that I needed it to be reusable on multiple pages of the site, so my goal was to create something that could be imported and utilized in other react components in order to add to a div which had content that would need to be scrolled through.</p><p>In thinking about the logic of this it would probably be best to have an element which would render a scrollable div which rendered the components children and have a sibling element to the scrollable div which was the “Scroll to Top” button. The component itself would know about the scroll height of the scrolling div and the the button could control it.</p><p>Pseudo Code Example of the structure:</p><pre>&lt;ScrollToTopContainer&gt; <br>  &lt;ScrollToTopButton /&gt;<br>  &lt;ScrollableDiv&gt;<br>    {this.props.children}<br>  &lt;/ScrollableDiv&gt;<br>&lt;/ScrollToTopContainer&gt;</pre><p>Now that we have an idea of the basic structure, lets look at how some of the technical bits would work.</p><p>I found that if I referenced the scrollable div, I could get access to the scrollTop property of the element. In order to reference the div I needed to add a ref. I did so by creating a reference function:</p><pre>reference = id =&gt; ref =&gt; { this[id] = ref  }</pre><p>Which would be used on the scrolling wrapper like:</p><pre>&lt;ScrollingWrapperContainer ref={this.reference(&#39;scrollingWrapper&#39;)}&gt;</pre><p>This would then allow me to check or set the scrollTop value of the scrolling div by calling this.scrollingWrapper.scrollTop anywhere in the class of my component.</p><p>Given that functionality, I could now have an event listener which could check for the changes in scroll height and if it exceeded 100 (the distance relevant to our use case — passing the filters) then it would update the state of the component which would be the boolean which determined the display of the button. I implemented that as follows:</p><pre>state = { hasScrolled: false }   </pre><pre>componentDidMount() {  <br>  this.scrollingWrapper.addEventListener(&#39;scroll&#39;, this.onScroll)<br>}</pre><pre>onScroll = () =&gt; {<br>  if (this.scrollingWrapper.scrollTop &gt; 100 &amp;&amp;     <br>                             !this.state.hasScrolled) {      <br>    this.setState({ hasScrolled: true })    <br>  } else if (this.scrollingWrapper.scrollTop &lt; 100 &amp;&amp; <br>                             this.state.hasScrolled) {      <br>    this.setState({ hasScrolled: false })    <br>  }  <br>}</pre><p>So now, once I have scrolled passed a value of 100, then my button should show up. Now I need to handle the click of that button to actually scroll back to the top! Technically, I want to set the scrollTop back to zero. To do this, I set the onClick event handler to be the function below:</p><pre>scrollToTop = () =&gt; this.scrollingWrapper.scrollTop = 0</pre><p>Now the important part, which is now so easy to do… the implementation of our component!</p><ol><li>Import it into the component file where you want to use it.</li></ol><pre>import ScrollingWrapper from &#39;./scrollingWrapper.jsx</pre><p>2. Wrap the content you want to scroll in the render function of your component.</p><pre>render() {<br>  return(<br>    &lt;ScrollingWrapper&gt;<br>      &lt;MyContentThatNeedsToScroll&gt;<br>    &lt;/ScrollingWrapper&gt;<br>  )<br>}</pre><p>That’s it!</p><p>Below you can find the entire component put together. I also used styled-components to write some css directly in my jsx file which further keeps this component independent from other components and styles throughout my project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c32f53905c2af4fbcefa8a7d43879e5b/href">https://medium.com/media/c32f53905c2af4fbcefa8a7d43879e5b/href</a></iframe><p>Hope this helps you on your coding journey today!</p><figure><a href="https://levelup.gitconnected.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6CoI_MRyZ1JInNPsBSHtA.png" /></a></figure><p><a href="https://gitconnected.com/learn/react">Learn React - Best React Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fa5ac8d4c2d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/building-a-componentized-and-reusable-scroll-to-top-feature-in-react-7fa5ac8d4c2d">Building a Componentized and Reusable “Scroll to Top” Feature in React</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use Code Snippets in VSCode to Create React Components Faster!]]></title>
            <link>https://levelup.gitconnected.com/use-code-snippets-in-vs-code-to-create-react-components-faster-56fe5327896c?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/56fe5327896c</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[code-snippet]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Fri, 22 Feb 2019 04:47:50 GMT</pubDate>
            <atom:updated>2019-02-22T15:01:29.292Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C7WpnUONhPlcj-GM" /><figcaption>Photo by <a href="https://unsplash.com/@clemhlrdt?utm_source=medium&amp;utm_medium=referral">Clément H</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Lately I have been writing a lot of code and trying to rapidly produce different React components, creating stories for them in Storybook and writing tests for them. Generally thats 3 files, per component, with basic and predictable code that I was typically copying and pasting with every new component. I recently created some code snippets to help me produce the code in these files and found it saved me a ton of time. Read on to learn how I did it!</p><h3>What are Code Snippets?</h3><blockquote>“Code snippets are small blocks of reusable code that can be inserted in a code file using a right-click menu (context menu) command or a combination of hotkeys.” — Microsoft</blockquote><p>Woah! Code Snippets can give you a shortcut to turn just a few characters into predefined lines of code. AKA I can turn tcomp into:</p><pre>import React from &#39;react&#39;<br>import styled, { withTheme } from &#39;styled-components&#39;</pre><pre>const ComponentName = props =&gt; {<br>    return (<br>    <br>    )<br>}</pre><pre>export default withTheme(ComponentName)</pre><pre>ComponentName.displayName = &quot;ComponentName&quot;</pre><p>That just saved me a bunch of typing and time! Now all I have to do is replace ComponentName with my desired name. Lets dig into how this all works…</p><h3>How to Create a Code Snippet</h3><p>Step 1: Go to User Snippets in the menu like so….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKpMqGz8HbhuCCoNsrL1jg.png" /></figure><p>Step 2: Select that you want to create a New Global Snippets file if you think you will want to use this snippet across multiple projects…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y5X5ySO_9wEGQxluSJoc-Q.png" /></figure><p>Step 3: Give it a name more creative than untitled…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*NB1TFybeT9dKpvwrvPX0Qw.png" /></figure><p>Step 4: Write your code snippet!</p><p>There are some comments already in the file to help you get started and remind you of the formatting, but you can leave it or delete it. In my case, I deleted it and wrote my snippet as follows:</p><pre>{<br>  &quot;Themed Component&quot;: {<br>    &quot;scope&quot;: &quot;javascriptreact&quot;,<br>    &quot;prefix&quot;: &quot;tcomp&quot;,<br>    &quot;body&quot;: [<br>      &quot;import React from &#39;react&#39;&quot;,<br>      &quot;import styled, { withTheme } from &#39;styled-components&#39;&quot;,<br>      &quot; &quot;,<br>      &quot;const ${1:ComponentName} = props =&gt; {&quot;,<br>      &quot;  return (&quot;,<br>      &quot;    $0&quot;,<br>      &quot;  )&quot;,<br>      &quot;}&quot;,<br>      &quot; &quot;,<br>      &quot;export default withTheme(${1:ComponentName})&quot;,<br>      &quot; &quot;,<br>      &quot;${1:ComponentName}.displayName = \&quot;${1:ComponentName}\&quot;&quot;,<br>    ],<br>    &quot;description&quot;: &quot;Create Themed Component&quot;<br>  }<br>}</pre><p>Now lets step through it… The first key of this object is the <strong>name</strong> of the snippet itself, in this case “Themed Component”. The <strong>scope</strong> is indicating the language it is written for which can be used for filtering purposes when looking through your snippets. The <strong>prefix</strong> is what you will type in the editor to use the shortcut to return your code. In my case I chose tcomp as my prefix because, to me, it represents that I want to create a Themed Component which is also stated in my <strong>description</strong>. This is all subjective and up to you to choose what you will remember and find convenient.</p><p>The <strong>body</strong> is obviously the most important part and as you probably guessed, is where you want to put in the code you want your snippet to return. The format of the body is an array of strings, where each string is a new line of code. You may also have noticed some strange notation: ${1:ComponentName} and $0 . These are examples of placeholders and tabstops respectively. Tabstops allow you to move throughout your snippet once you have it in your file and you can edit in the different places at the same time just by duplicating your tabstop in your code snippet. placeholders are simply tabstops with values. As you edit your code and press tab you will jump through your tabstops numerically, starting at $1 . The $0 tabstop is reserved for where you want your final tab to leave your cursor.</p><p>Below is a clip of this code snippet in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*QlXJ_1oe4OiKfmZa7t8lkw.gif" /><figcaption>My code snippet for my themed components</figcaption></figure><h3>Further Examples</h3><p>So that was my themed component code snippet and used a single tabstop for the final cursor position and a single placeholder for the component name. I also created code snippets for my test files and my storybook files:</p><pre>{<br>  &quot;React Component Test&quot;: {<br>    &quot;scope&quot;:&quot;javascript,javascriptreact&quot;,<br>    &quot;prefix&quot;: &quot;tst&quot;,<br>    &quot;body&quot;: [<br>      &quot;import React from &#39;react&#39;&quot;,<br>      &quot;import { render } from &#39;react-testing-library&#39;&quot;,<br>      &quot;import { ThemedComponent } from &#39;../../../utils/test-utils&#39;&quot;,<br>      &quot;import $1 from &#39;./$2&#39;&quot;,<br>      &quot; &quot;,<br>      &quot;describe(&#39;$1&#39;, () =&gt; {&quot;,<br>      &quot;  it(&#39;$3&#39;, () =&gt; {&quot;,<br>      &quot;    $4&quot;,<br>      &quot;  }) &quot;,<br>      &quot;})&quot;,<br>      &quot; &quot;,<br>    ],<br>    &quot;description&quot;: &quot;Create Test&quot;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VyPVD9aBDcScTM_K-ks4iw.gif" /><figcaption>My code snippet for my testing files</figcaption></figure><pre>{  <br>  &quot;Create Storybook Story&quot;: {<br>    &quot;scope&quot;: &quot;javascript,javascriptreact&quot;,<br>    &quot;prefix&quot;: &quot;story&quot;,<br>    &quot;body&quot;: [<br>      &quot;import React from &#39;react&#39;&quot;,<br>      &quot;import { storiesOf } from &#39;@storybook/react&#39;&quot;,<br>      &quot;import $1 from &#39;./$2&#39;&quot;,<br>      &quot; &quot;,<br>      &quot;storiesOf(&#39;$3|$1&#39;, module)&quot;,<br>      &quot;.addWithJSX(&#39;$1&#39;, () =&gt; &lt;$1 /&gt;)&quot;,<br>      &quot; &quot;,<br>    ],<br>    &quot;description&quot;: &quot;Create Story&quot;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*JdRI21uTEhPN8QV9h_ivvw.gif" /><figcaption>My code snippet to generate my component stories for Storybook</figcaption></figure><p>Check out this link to learn more:</p><p><a href="https://code.visualstudio.com/docs/editor/userdefinedsnippets">Snippets in Visual Studio Code</a></p><figure><a href="https://levelup.gitconnected.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6CoI_MRyZ1JInNPsBSHtA.png" /></a></figure><p><a href="https://gitconnected.com/learn/react">Learn React - Best React Tutorials (2019) | gitconnected</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56fe5327896c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/use-code-snippets-in-vs-code-to-create-react-components-faster-56fe5327896c">Use Code Snippets in VSCode to Create React Components Faster!</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Google Maps API with React]]></title>
            <link>https://medium.com/@sarahsweat/using-the-google-maps-api-with-react-9694a475f00a?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/9694a475f00a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[fundraising]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-maps]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Wed, 16 Aug 2017 15:23:31 GMT</pubDate>
            <atom:updated>2017-08-23T18:57:37.791Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! So this is going to be a brief post about how I am incorporating the google maps API into my final project in order to mark on a map where donations are coming from with the Children’s miracle network balloons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*wX8z7iGFVPzWBlHRnn6weA.png" /></figure><p>Step 1)</p><p>Request a google maps API ket at:</p><p><a href="https://developers.google.com/maps/documentation/javascript/">Google Maps JavaScript API | Google Developers</a></p><p>Here, you can click to get an API key, as well as read up on some of their documentation. They even have a few tutorials on how to implement it in a plain javascript application.</p><p>Step 2)</p><p>Install google-map-react into your project.</p><pre>npm install --save google-map-react</pre><p>You can find the documentation for it here:</p><p><a href="https://www.npmjs.com/package/google-map-react">google-map-react</a></p><p>This supplies you with the react component to generate the map on your webpage.</p><p>Step 3)</p><p>Specify an initial Latitude and Longitude as well as an initial zoom scale.</p><p>You can then render any React object at any specified Longitude and Latitude. In my case I created a basic react object which is just an image src of a cmn balloon.</p><pre>import React, { Component } from &#39;react&#39;;<br>import { Container, Image } from &#39;semantic-ui-react&#39;<br>import GoogleMapReact from &#39;google-map-react&#39;;</pre><pre>const Balloon = () =&gt; &lt;img width=&quot;25&quot; src=&#39;<a href="http://speedwaymiracletournament.com/Images/cmnh-logo-no-text.png&#39;/">http://speedwaymiracletournament.com/Images/cmnh-logo-no-text.png&#39;/</a>&gt;;</pre><pre>export default class DonationMap extends Component {<br>  constructor(props){<br>    super()<br>  }</pre><pre>render() {<br>    return (<br>      &lt;Container style={{width: &#39;100%&#39;, height: &#39;400px&#39;}}&gt;<br>      &lt;GoogleMapReact<br>        center={{lat: 37, lng: -91}}<br>        defaultZoom={4}<br>      &gt;<br>        {this.props.latLongs.map(place =&gt; (<br>          &lt;Balloon lat={place.lat} lng={place.lng} /&gt;<br>        ))}</pre><pre>&lt;/GoogleMapReact&gt;<br>    &lt;/Container&gt;<br>    );<br>  }<br>}</pre><p>Note on Getting the Lat and Long from the Zip:</p><p>Using the zip code of a user, you are able to send a fetch request to the google maps api to retrieve the latitude and longitude points. Then I just passed that into the component to then render.</p><p>First I created a zip code array which collected the respective zipcodes from all the users. What was tricky about this is that given the way I passed my users into this component, it hadn’t necessarily completed the fetch to my backend and would return an empty array. This is why instead of using componentWillMount, I need to use componentWillReceiveProps. This function will only execute once it receives new props (AKA the fetched users) and I could then use these “new props” to collect the necessary zipcodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiWOtPE2G0fxFJZmosOidg.png" /></figure><p>Once I had the array of zipcodes, I was able to map through them and send a fetch request for each one and store the corresponding Lat and Long values which I stored into the components state. This state is then passed into the map component to render the individual balloons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TWZ2FQCaPSKiAWoXIY7EQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9694a475f00a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Rabbit Hole of Fibonacci Sequences, Recursion and Memoization]]></title>
            <link>https://medium.com/@sarahsweat/the-rabbit-hole-of-fibonacci-sequences-recursion-and-memoization-f5c34079a488?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5c34079a488</guid>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[fibonacci]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[rabbits]]></category>
            <category><![CDATA[memoization]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Wed, 26 Jul 2017 04:57:00 GMT</pubDate>
            <atom:updated>2017-07-26T17:03:50.557Z</atom:updated>
            <content:encoded><![CDATA[<p>Ok, prepare yourself for the literal rabbit hole of my Tuesday night….</p><p>First, JP led me to Memoization, which then led me to recursion, which led to Fibonacci Sequences, which obviously and inevitably led me to rabbits…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*O6QcFrRO3X2cXJ-u7JZfrQ.gif" /></figure><p>I am warning you….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ovRi9LMw_Fkp1s9xmkFUNA.gif" /></figure><p><strong>Fibonacci Sequence</strong></p><p>What is the Fibonacci Sequence? It is a series of numbers in which each number is the sum of the two preceding numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*QrEq2fn-wed-wVugimyoIA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*t-QUrXtXpCREqjoorfWsYA.gif" /></figure><p>This is a very famous set of numbers and was found in the 12th century by a mathematician named Leonardo Fibonacci. This sequence was first thought of when Fibonacci was pondering the question of rabbit reproduction? Weird/Random, I know. Stick with me.</p><p>Basically, the problem assumes the following conditions:</p><ul><li>Begin with one male rabbit and female rabbit that have just been born.</li><li>Rabbits reach sexual maturity after one month.</li><li>The gestation period of a rabbit is one month.</li><li>After reaching sexual maturity, female rabbits give birth every month.</li><li>A female rabbit gives birth to one male rabbit and one female rabbit.</li><li>Rabbits do not die.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*ETOCYxatlQZudD_iYIixFw.jpeg" /></figure><p><strong><em>Side Note</em> — Fibonacci Spiral</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*G4bMZPrzK942her0k6e2HA.png" /></figure><p>A Fibonacci spiral is a series of connected quarter-circles drawn inside an array of squares with Fibonacci numbers for dimensions. The squares fit perfectly together because of the nature of the sequence, where the next number is equal to the sum of the two before it. Any two successive Fibonacci numbers have a ratio very close to the Golden Ratio, which is roughly 1.618034. The larger the pair of Fibonacci numbers, the closer the approximation. The spiral and resulting rectangle are known as the Golden Rectangle. The sequence is also closely related to a famous number called the <em>golden ratio. </em>You can find this series of numbers in the turns of natural spirals, in plants, and in the family tree of bees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ill2Utlr7vee-cvlmaFMaw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*apU1U-GZWKISwsVzgX5xUA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Hw6G8EbacnQF3p5cecnuEw.jpeg" /></figure><p><strong>Recursion</strong></p><p>Ok, back to how all this related to the code. So we have all heard people talk about recursion, and that it is when a function calls itself and that it makes programs more efficient. But why? And how? And when would you use this? Lets take a dive using the Fibonacci Sequence as our example!</p><p>Below is an example of how a given index of the Fibonacci Sequence would be calculated. Notice that it is calling the fibonacci sequence on itself until it gets down to the base case of the series, as each proceeding number depends on the ones before it, then calculates back up to the index desired.</p><pre>function fibonacci(n) {<br>  if (n === 0 || n === 1)<br>    return n;<br>  else<br>    return fibonacci(n - 1) + fibonacci(n - 2);<br>}</pre><p>This function performs well for small values of “n”. However, performance quickly degrades exponentially as “n” increases. This is because the two recursive calls repeat the same work. You can see these repetitive calls in the recursion tree below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*3eiROF2Osi6-3YlHYYyjRw.png" /></figure><p>You can see that F(1) gets calculated three times, F(2) 5 times, F(3) 3 times, F(4) twice….…</p><p>In comes Memoization….</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*7_pzxOkdKnTKlCY4yMfepQ.gif" /></figure><p><strong>Memoization</strong></p><p>The idea of Memoization is that it is a programming technique which attempts to increase a function’s performance by caching its previously computed results. Basically, every time that a Fibonacci index gets calculated, the result can be stored in an outside object so that the recursive function can access it and use an already calculated result in its future calculations since they are all dependent upon each other.</p><p><strong>Side Note</strong>: The definition of cache is <em>“a temporary storage space or memory that allows fastaccess to data”. </em>One misconception, albeit mostly on my end, is that caches are only through the browser and in the form of things like cookies, tokens, etc. However, the term refers to anything in computing where things are saved for later use to speed up processing.</p><blockquote>“Memoized functions store a cache which is indexed by their input arguments. If the arguments exist in the cache, then the cached value is returned. Otherwise, the function is executed and the newly computed value is added to the cache.”</blockquote><p>Let’s take a look at the code below and note that we are storing calculated results in memo.</p><ol><li>It establishes its caching object, memo.</li><li>It first checks if the fibonacci index has been calculated before and saved in memo.</li><li>If it is, then it uses that value in the recursive function.</li><li>If it is not, it then continues to calculate the next term in the fibonacci sequence as before, while also saving it into the cache object for future use.</li></ol><pre>var fibonacci = (function() {<br>  var memo = {};<br><br>  function f(n) {<br>    var value;<br><br>    if (n in memo) {<br>      value = memo[n];<br>    } else {<br>      if (n === 0 || n === 1)<br>        value = n;<br>      else<br>        value = f(n - 1) + f(n - 2);<br><br>      memo[n] = value;<br>    }<br><br>    return value;<br>  }<br><br>  return f;<br>})();</pre><p>This code allows the function to reference the previously calculated values. Let’s take a look back at our recursion tree, but with memoization. You can see we are now able to eliminate many of our calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*IpRast6Kb1BjfuPQCf7zWg.png" /></figure><p>This is the magic of Memoization!</p><p>Unfortunately, most problems are more complex and functions have more than just 1 argument. This means there is not a simple key value pair for each calculation to be stored in. This can be dealt with in two ways. The most common being to create a hierarchy of objects(like a nested hash). The less common being a single cache object which is indexed by a combination of all of the function’s arguments. Under this approach, the arguments are transformed into an array and then used to index the cache. Both of these methods are detailed in the last resource below. Take a look!</p><p>In summary, memoization is beneficial when a recursive function is repeating multiple calculations because and it can store those results in an object and pull them when needed, instead of completely recalculating them. If it is a short function that isn’t used often and calculation times are fast, then memoization may not be necessary.</p><p>Resources:</p><ul><li><a href="https://www.livescience.com/37470-fibonacci-sequence.html">What is the Fibonacci Sequence?</a></li><li><a href="https://www.sitepoint.com/recursion-functional-javascript/">Recursion in Functional JavaScript - SitePoint</a></li><li><a href="https://www.sitepoint.com/implementing-memoization-in-javascript/">Implementing Memoization in JavaScript - SitePoint</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5c34079a488" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this Treehouse stuff?]]></title>
            <link>https://medium.com/@sarahsweat/what-is-this-treehouse-stuff-cc678e5b0b34?source=rss-71bead4da933------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc678e5b0b34</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[treehouse]]></category>
            <dc:creator><![CDATA[Sarah Sweat]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 13:35:00 GMT</pubDate>
            <atom:updated>2017-07-05T13:39:12.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*NlNjFayw5CK4URgY8BTHGg.gif" /></figure><p>Remember on Day 1, we were able to list our treehouse account… If you were like me, you probably thought, treehouse? What’s that? Well, let me tell you, it is one of the internet’s best kept secrets when it come to technology education. It is an online learning platform for learning all things code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9Zb9E704YUExuGYHmn2GA.png" /></figure><p>The program is built up by courses and tracks on various topics. Recently I completed the AJAX Basics course when I entered the dreaded “panic mode” and didn’t seem to know where to begin. It took roughly 5 hours to complete, but it started with the very beginning and by the end I had learned the basics of Ajax and created a couple of small projects along the way. An individual course is typically made up of short educational videos, quizzes and code alongs. The code alongs are nice because they provide you with an online workspace to complete the labs and you don’t need to worry about getting caught up in environment issues while trying to learn the AJAX concepts.</p><p>Below, I will show you some screenshots and features that I was able to use while going through the AJAX course and will give you a good idea of what working on Treehouse is like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtvZRcnnXIcPNJmlPzbaKA.png" /></figure><p>Once you have selected a track and/or a course, you will begin with an introductory video. The main form of education on this platform is through recorded lectures. There are no readings, however the lectures are pretty detailed and they will put up slides with important information. This is demonstrated in the screenshots below. I found it very useful to see some of the big picture concepts written out and then afterwards the videos and examples would be more in depth and concerned with syntax and the logistics of actually creating the AJAX calls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Q2hk_XifTJtB4BxWmuzNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*WvGSQKnbTW8c5YzDEuQkBQ.png" /></figure><p>After a few videos, there are sporadically placed quizzes to test your knowledge. I found this very useful to keep myself engaged and also test my knowledge to make sure I was soaking in what I was watching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrAmrKtqAsWKjDaQ9S_qkw.png" /></figure><p>Along with some of the multiple choice quizzes were coding quizzes. The directions would step you through what they wanted conceptually, but then it tested your knowledge of the syntax and details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BUP75G0FUZr2QMjHpP0JHQ.png" /></figure><p>Towards the end of each course you build an actual project. they provide you with the files necessary to do it locally, but they also provide you an online “workspace” where the environment and server are already setup for you. I utilized this so that I could focus on learning AJAX and not get caught up in other issues. However, now I want to go back and attempt everything locally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Udh2OeYLoMFjQ3F8qCJtSA.png" /></figure><p>As you complete different stages in the course, you receive badges and points. I don’t think this really gets you anything, but its kind of a fun incentive to keep going.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ax7dCSFMNRYz-7HLUPiGyQ.png" /></figure><p>So what’s the catch? Treehouse is not free…. Wahhhh. Unfortunate, I know, but understandable. It is great content! There are a few options for how you pay. I started a free trial of 7 days and then am scheduled to begin paying $25/month when the trial ends. I can also select the option to pay for a full year. This option allows you to get 2 months free. There are also different levels of access. For most students at Flatiron, I would simply recommend the Basic package because the only real benefit to the pro package is the ability to download videos offline and a little bit of bonus content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TS7QH9Fh4-guXQiBo0zNA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc678e5b0b34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>