<?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 Precious Nyarko on Medium]]></title>
        <description><![CDATA[Stories by Precious Nyarko on Medium]]></description>
        <link>https://medium.com/@mrewusi?source=rss-2d9bf80cb91d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZqxnWIPToA8rUPLvVtQklA.jpeg</url>
            <title>Stories by Precious Nyarko on Medium</title>
            <link>https://medium.com/@mrewusi?source=rss-2d9bf80cb91d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 13:19:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrewusi/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[Working with lists in React]]></title>
            <link>https://medium.com/@mrewusi/working-with-lists-in-react-678e60c3208f?source=rss-2d9bf80cb91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/678e60c3208f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Precious Nyarko]]></dc:creator>
            <pubDate>Wed, 08 Jan 2020 14:33:17 GMT</pubDate>
            <atom:updated>2020-01-08T14:33:17.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FFtxtk_Fv5MQ0iKz" /><figcaption>Photo by <a href="https://unsplash.com/@bergerteam?utm_source=medium&amp;utm_medium=referral">Florian Berger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><pre>function TodoList({ todos }) {<br>  const todoItems = todos.map((todo) =&gt;<br>    &lt;li&gt;{todo.description}&lt;/li&gt;<br>  );</pre><pre>  return (<br>    &lt;ul&gt;{todoItems}&lt;/ul&gt;<br>  );<br>}</pre><p>If you’ve done any amount of coding in React, then the following code snippet above should look more than a little familiar 😛. Rendering lists of things is something we find ourselves doing many times over when building web applications.</p><p>If we run this code, we’d get a warning that a key should be provided for list items. When I first started learning React, I would quickly modify the above snippet to the following to make the warning go away.</p><pre>function TodoList({ todos }) {<br>  const todoItems = todos.map((todo<strong>, index</strong>) =&gt;<br>    &lt;li <strong>key={index}</strong>&gt;{todo.description}&lt;/li&gt;<br>  );</pre><pre>return (<br>    &lt;ul&gt;{todoItems}&lt;/ul&gt;<br>  );<br>}</pre><p>The above change looks straightforward, and it does get rid of the warning too. So we are home and dry right? Well… depending on how the user is meant to interact with the list being rendered, using keys <strong>may</strong> break your application and display wrong data.</p><p>In this post, I will attempt to explain why these keys are necessary and how to use them in ways that don’t inadvertently produce bugs and unexpected behavior in your react applications.</p><p>React uses these <em>keys</em> as unique identifiers to identify DOM elements. The React docs put it aptly.</p><blockquote>Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.</blockquote><p>While the only requirement for the <em>key</em> is that it is a string, React recommends that this be a string that uniquely identifies a list item amongst its siblings. It is highly desirable an item’s <em>key</em> is<em> </em>stable<em>: i.e. </em>doesn’t change between renders.</p><p>This is important because if you use stable keys, you can be 100% confident that no matter what happens to the items in that list, or how many times it gets re-rendered, the key will be same as before and as a result, the DOM element will represent the same component as before.</p><p>Therein lies the potential pitfalls of using indexes as keys. If the list items ever get re-ordered, filtered or if items get added or removed, you suddenly have a situation where index 0 could be pointing at a different DOM element than it did previously. This can have a negative impact on performance and may cause issues with component state, which could cause your app to display incorrect data.</p><p>In summary, your goal shouldn’t be to avoid using indexes as keys at all costs. If you have a use case where the list itself is static (i.e. it is not computed dynamically and is never re-ordered or filtered) and the items have no ids, then you may safely use the item indexes as keys.</p><p>Otherwise, you should use the item ids as keys if you have them. If your items have no ids and your list isn’t static, you should generate unique ids for each item in the list. A library like <a href="https://www.npmjs.com/package/shortid">shortid</a> can help with generating short unique ids that you can use as keys for your list items.</p><h3>A few things to note</h3><h4>Extracting Components with Keys</h4><p>Keys only make sense in the context of the surrounding array or list. What this means is that if we were to extract the rendering of the list item into a separate ListItem component, the correct usage of the key attribute would be to keep the key on the &lt;ListItem /&gt; elements in the array rather than on the &lt;li&gt; element in the ListItem itself.</p><p><strong>Example: Incorrect Key Usage</strong></p><pre>function ListItem(props) {<br>  const value = props.value;<br>  return (<br>    // Wrong! There is no need to specify the key here:<br>    &lt;li key={value.toString()}&gt;<br>      {value}<br>    &lt;/li&gt;<br>  );<br>}</pre><pre>function NumberList(props) {<br>  const numbers = props.numbers;<br>  const listItems = numbers.map((number) =&gt;<br>    // Wrong! The key should have been specified here:<br>    &lt;ListItem value={number} /&gt;<br>  );<br>  return (<br>    &lt;ul&gt;<br>      {listItems}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>We would see the missing keys warning if we ran this code because we haven’t provided keys for the &lt;ListItem /&gt; items in the listItems array. The correct usage would be to move the key provision inside the array as shown below:</p><p><strong>Example: Correct Key Usage</strong></p><pre>function ListItem(props) {<br>  // Correct! There is no need to specify the key here:<br>  return &lt;li&gt;{props.value}&lt;/li&gt;;<br>}</pre><pre>function NumberList(props) {<br>  const numbers = props.numbers;<br>  const listItems = numbers.map((number) =&gt;<br>    // Correct! Key should be specified inside the array.<br>    &lt;ListItem key={number.toString()}<br>              value={number} /&gt;<br>  );<br>  return (<br>    &lt;ul&gt;<br>      {listItems}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>If you are ever in doubt, here’s a good rule of thumb from the React docs:</p><blockquote>Elements inside map() calls need keys.</blockquote><h4>Keys Don’t Need To Be Unique Globally — Only Among Siblings</h4><p>Because keys used within arrays should be unique among their siblings. You can use the same keys in two different arrays. Here’s an example:</p><pre>function Blog(props) {<br>  const sidebar = (<br>    &lt;ul&gt;<br>      {props.posts.map((post) =&gt;<br>        &lt;li key={post.id}&gt;<br>          {post.title}<br>        &lt;/li&gt;<br>      )}<br>    &lt;/ul&gt;<br>  );</pre><pre>  const content = props.posts.map((post) =&gt;<br>    &lt;div key={post.id}&gt;<br>      &lt;h3&gt;{post.title}&lt;/h3&gt;<br>      &lt;p&gt;{post.content}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );</pre><pre>  return (<br>    &lt;div&gt;<br>      {sidebar}<br>      &lt;hr /&gt;<br>      {content}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4><strong>Parting words</strong></h4><p>Lists are everywhere in web applications. Hopefully, this post makes it easier to avoid some of the pitfalls of working with lists in React. If you found this post useful, feel free to pass it on.</p><p>Onward!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=678e60c3208f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I love Strict Mode in React]]></title>
            <link>https://medium.com/@mrewusi/why-i-love-strict-mode-in-react-cf72acfa8978?source=rss-2d9bf80cb91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf72acfa8978</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Precious Nyarko]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 13:03:09 GMT</pubDate>
            <atom:updated>2020-01-01T13:03:09.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VQARWexYafiyv_8U" /><figcaption>Photo by <a href="https://unsplash.com/@johnschno?utm_source=medium&amp;utm_medium=referral">John Schnobrich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently discovered Strict Mode in React. And I think it&#39;s great! Here’s why…</p><p>According to the React docs:</p><blockquote>StrictMode is a tool for highlighting potential problems in an application. Like Fragment, StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.</blockquote><h4>Let’s break this down…</h4><h4>Okay. What sorts of checks does it actually do?</h4><p>Strict Mode currently helps with the following:</p><ul><li>Identifying components with unsafe lifecycles</li><li>Warning about legacy string ref API usage</li><li>Warning about deprecated findDOMNode usage</li><li>Detecting unexpected side effects</li><li>Detecting legacy context API</li></ul><h4>Why bother with it?</h4><h4>1 — It’s declarative</h4><p>&lt;React.StrictMode&gt; is essentially a React component that enables additional checks and warnings for its descendants. This means we can enable strict mode checks for any part of our application by simply wrapping it with &lt;React.StrictMode&gt; This declarative API makes it easy to incrementally adopt it in your codebase. Whether you wrap it around your entire app or only specific component or screen is completely up to you.</p><h4>2 — It helps with identifying unsafe lifecycles</h4><p>When strict mode is enabled, React compiles a list of all class components using the unsafe lifecycles, and logs a warning message with information about these components, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*O8BUgW6c-CcIRdOv.png" /></figure><p>The nice thing is, that these warnings will be logged even if the offending code is in a third-party library.</p><h4>3 — It warns about legacy string ref API usage</h4><p>Previously, React provided two ways for managing refs: the legacy string ref API and the callback API. Although the string ref API was the more convenient of the two, it has <a href="https://github.com/facebook/react/issues/1373">several downsides</a> and so the React docs recommend was to <a href="https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs">use the callback form instead</a>.</p><p>Since object refs were largely added as a replacement for string refs, strict mode now warns about the usage of string refs.</p><h4>4 — It warns about deprecated findDOMNode usage</h4><p>React used to support findDOMNode to search the tree for a DOM node given a class instance. Normally you don’t need this because you can <a href="https://reactjs.org/docs/refs-and-the-dom.html#creating-refs">attach a ref directly to a DOM node</a>. Strict Mode will warn about usage of this deprecated API.</p><h4>5 — Detecting unexpected side effects</h4><p>React does work in two phases:</p><ul><li>The <strong>render</strong> phase determines what changes need to be made to e.g. the DOM. During this phase, React calls render and then compares the result to the previous render.</li><li>The <strong>commit</strong> phase is when React applies any changes. (In the case of React DOM, this is when React inserts, updates, and removes DOM nodes.) React also calls lifecycles like componentDidMount and componentDidUpdate during this phase.</li></ul><p>The commit phase is usually very fast, but rendering can be slow. This is why async mode (which is not enabled by default yet) breaks the rendering work into pieces, pausing and resuming the work to avoid blocking the browser. As a result, React may invoke render phase lifecycles more than once before committing, or it may invoke them without committing at all (because of an error or a higher priority interruption).</p><p>Render phase lifecycles include the following class component methods:</p><ul><li>constructor</li><li>componentWillMount</li><li>componentWillReceiveProps</li><li>componentWillUpdate</li><li>getDerivedStateFromProps</li><li>shouldComponentUpdate</li><li>render</li><li>setState updater functions (the first argument)</li></ul><p>Because the above methods might be called more than once, it’s important that they do not contain side-effects. Ignoring this rule can lead to a variety of problems, including memory leaks and invalid application state.</p><p>Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally <strong>double-invoking</strong> the following methods:</p><ul><li>Class component constructor method</li><li>The render method</li><li>setState updater functions (the first argument)</li><li>The static getDerivedStateFromProps lifecycle</li></ul><blockquote><em>Note:</em></blockquote><blockquote><em>This only applies to development mode. </em>Lifecycles will not be double-invoked in production mode.</blockquote><h4>6 — Detecting legacy context API</h4><p>The legacy context API is error-prone and will be removed in a future major version. It still works for all 16.x releases but will show this warning message in strict mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*yVd3fHiN-pCb9HUj.png" /></figure><p>Read the <a href="https://reactjs.org/docs/context.html">new context API documentation</a> to help migrate to the new version.</p><h4>Conclusion</h4><p>Remember, that this isn’t something that you absolutely have to add to your codebase, and <strong>your code will continue to work</strong> whether you’re using strict mode and fixing the warnings or not.</p><p>But if you do want to give it a go, a great way to get get a feel for things is to start by opting certain parts of your app into strict mode without getting a slew of warnings everywhere.</p><p>Hopefully, this helps you catch bugs and potential issues in your React codebases, as you incrementally cover more of the codebase.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf72acfa8978" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Synthetic Events in React]]></title>
            <link>https://medium.com/@mrewusi/synthetic-events-in-react-4f3de0c827f?source=rss-2d9bf80cb91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f3de0c827f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Precious Nyarko]]></dc:creator>
            <pubDate>Thu, 26 Dec 2019 19:13:51 GMT</pubDate>
            <atom:updated>2019-12-26T19:13:51.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mp-Pq2dXsvZRnaRY" /><figcaption>Photo by <a href="https://unsplash.com/@codestorm?utm_source=medium&amp;utm_medium=referral">Safar Safarov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><pre><em>This synthetic event is reused for performance reasons. If you&#39;re seeing this, you&#39;re accessing the property &lt;property&gt; on a released/nullified synthetic event. This is set to null. If you must keep the original synthetic event around, use event.persist()...</em></pre><p>If you’ve ever seen the error above and wondered… wait, what? then it is my hope that this article shines some light on what’s really happening and why event.persist() is necessary at all.</p><p>Let’s begin by exploring what actually gets passed to our event handlers when an event occurs. The React docs put it very succinctly.</p><blockquote>Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser’s native event.</blockquote><p>Even though it is a wraps the browser’s native event, SyntheticEvent has the same interface as the native event. This is nice because it means that you get to use the familiar event methods like stopPropagation() and preventDefault(), while enjoying the benefits of working with events in a browser-agnostic way.</p><p>Regardless of this, if you find yourself in need of the underlying browser event, you can still access it by reading the nativeEvent attribute on the SyntheticEvent instance that gets passed to your event handler.</p><p>This is all well and good but there’s one important detail to keep in mind when working events in React.</p><h4>Synthetic Events are pooled</h4><p>For performance reasons, React will prepare the SyntheticEvent instance that gets passed to your event handler, for reuse, by nullifying all properties on the object the event handler has been called. This means that if you try to use the event in an asynchronous way, (say in a set timeout or some other asynchronous code) you won’t get the results you expect.</p><h4>Let’s drive the point home with an example.</h4><p>Say we are implementing a username input that checks calls an API endpoint to check that the user’s entry is available. Now say we have the following basic implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/063a5f6559dca54c137c410649d850f7/href">https://medium.com/media/063a5f6559dca54c137c410649d850f7/href</a></iframe><p>While this looks innocent enough, our attempt to read the length of the user’s input on line 12 would cause the code to break, sinceSyntheticEvent instance would have been nullified by the time execution got to that point.</p><p>We can deal with this in a couple of ways:</p><h4>1) Persist the event</h4><p>SyntheticEvent instances have a persist() method, that when called, will remove the event from the pool and allow references to the event to be retained by user code. This means we can simply modify our earlier example to include a line (line 19) that explicitly persists the event so that isNameAvailable can still access it even after the event handler (handleInputChange in our example) has been called. Here’s the modified version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f120de7aadf58219cedf3489040fd19/href">https://medium.com/media/5f120de7aadf58219cedf3489040fd19/href</a></iframe><h4>2) Preserve event attributes</h4><p>Sometimes you’ll find that you don’t actually need to keep the original event around. In our example, it is obvious that the only reason we needed the original SyntheticEvent instance to stick around, was so that we access itstarget.value attribute. In these cases, it may be better to assign the attribute(s) to a variable(s) that we can pass around as we please regardless of whether the original event has been nullified. If we modified our example to do this it would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/094ad2f3a72ab088d18bdaf3aa2f5d60/href">https://medium.com/media/094ad2f3a72ab088d18bdaf3aa2f5d60/href</a></iframe><p>This way, it doesn’t matter whether or not the original event has been nullified. We would still be able to access the values that we preserved via assignment. No persist needed!</p><h4>Conclusion</h4><p>If you need to access a whole bunch of stuff on the event instance, it may make more sense to keep the event around longer by persisting it, rather than wrangling a whole bunch of variables around. Otherwise extracting the single value you need might be better. It’s neither here nor there. What is important is that <strong>evaluate your specific situation and pick the approach</strong> — what works for you is good enough.</p><p>I truly hope this post has been of some help. Any questions, comments or suggestions for improvement are welcome. Onward!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f3de0c827f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusing logic in your React apps with Higher-Order Components]]></title>
            <link>https://medium.com/@mrewusi/reusing-logic-in-your-react-apps-with-higher-order-components-70cdb8e7230a?source=rss-2d9bf80cb91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/70cdb8e7230a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[higher-order-components]]></category>
            <dc:creator><![CDATA[Precious Nyarko]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 20:13:24 GMT</pubDate>
            <atom:updated>2018-11-21T20:36:27.849Z</atom:updated>
            <content:encoded><![CDATA[<p>As you build React applications, you will run into situations where you want to <strong><em>share some functionality</em></strong><em> across multiple components</em>. It could be that you you want a component to display a loading indicator, while it waits for some data to become available. Or perhaps, you need to access logged in user state from multiple components in your app. There’s got to be a way to share this state across those components, without having to basically copy-paste logic around, right? Enter <strong>Higher-Order Components (HOCs)</strong>.</p><p>This post is a look at HOCs and how they make it easy to write <em>easy-to-reason-about</em>, <em>reusable</em> code. I hope to leave you with a good understanding of how HOCs work and how to start using them in your own code. Let’s get started!</p><h4>What is a Higher-Order Component?</h4><p>According to the React docs, a higher-order component is a function that <strong>takes a component</strong> and <strong>returns a component</strong>. Put differently, a HOC will basically take some component as an argument, (let’s call this the <strong>passed-in component</strong> from now on) and return a new component (let’s call this the <strong>enhanced component</strong>) that essentially wraps the passed-in component, with logic or functionality (via props), that it wouldn’t have had access to otherwise.</p><p>So whenever we want a component to access some reusable logic, we run that component through a HOC and render new component that gets returned.</p><p>Let’s consider a simple example to drive the point home. Say we want to be able to access the current date from several of the components in our app. Well, we could write const currentDate = new Date() in any component that needs it. But instead, let’s see how using a HOC would nicely abstract that logic away and make it available on-demand to any component that needs it.</p><p>We’ll call this HOC withCurrentDate. Here’s the code for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e55bb64c5aaab9e06b71be8d6469bb/href">https://medium.com/media/e6e55bb64c5aaab9e06b71be8d6469bb/href</a></iframe><p>Let’s take a moment to understand what’s happening here. The withCurrentDate function is a JavaScript function like any other. It takes PassedComponent as an argument and returns a new component. This new component passes currentDate along with any other props it receives downPassedComponent. Okay, let’s move on.</p><p>With our withCurrentDate HOC defined, we can now use it, to make any component currentDate-aware, by simply passing the component as the argument to our HOC like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6415311c63f1b64ad32704b07f4e1bac/href">https://medium.com/media/6415311c63f1b64ad32704b07f4e1bac/href</a></iframe><h4>A more practical Higher-Order Component</h4><p>The example above — while useful in demonstrating how a HOC works — , is a bit contrived. Let’s look at a more practical example. Say we have two components. The first — ContactList — renders a loading indicator, while it waits for contacts to be loaded from the <a href="https://randomuser.me/">randomuser.me</a> API and renders list of contacts when the data arrives:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f8f0888ec9aa5835f1681ecfd3e713a/href">https://medium.com/media/0f8f0888ec9aa5835f1681ecfd3e713a/href</a></iframe><p>The second — GithubUserList — also renders a loading indicator, while it waits for user data to be loaded from <a href="https://developer.github.com/v3/">Github’s API</a> and renders list of users when the data arrives:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9858b3fda4c08e9c479a5e152fd1086d/href">https://medium.com/media/9858b3fda4c08e9c479a5e152fd1086d/href</a></iframe><p>ContactList and GithubUserList aren’t identical — they load data from different endpoints, and they render different output. But much of their implementation is the same:</p><ul><li>On mount, make a call the remote endpoint for data</li><li>Render loading text, while we wait</li><li>Call setState with the results, when the data comes back</li><li>Render a list of items with the retrieved data</li></ul><p>You can imagine that in a large app, this same pattern of showing some loading text while we wait for data to become available will occur over and over again. What we want is an abstraction that allows us to define this logic in a single place and share it across many components. This is where higher-order components excel.</p><p>Let’s write a function that creates components, like ContactList and GithubUserList, that show a spinner while they make a request to a remote source for data and render that data when it becomes available. This function (which is our HOC) will accept as one of its arguments a child component that will receive the data once it arrives. Let’s call the function withLoader:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2586dc67c64c4f3d0cc8a8b38355e926/href">https://medium.com/media/2586dc67c64c4f3d0cc8a8b38355e926/href</a></iframe><p>The interesting thing to note here, is that because we want withLoader itself to be reusable, we want to keep it as generic as possible. In other words, withLoader shouldn’t concern itself with how and from where the data is fetched. It is for this reason, that withLoader accepts a second argument:loadData, that handles the details of making the necessary API calls. This allows with loader to simply call fetchData and wait for it to return some data with which, which it then uses to update its local state.</p><p>With the introduction of withLoader we can now re-write ourContactList and GithubUserList as presentational components (i.e. simple components that simply accept some props and return some UI), since all the logic to deal with network calls, loading spinners etc has been nicely abstracted away. Plus we can reuse it anywhere we need that functionality.</p><p>Having been freed of the burden of dealing with network calls and loading spinners etc, our ContactList and GithubUserList components can now be re-implemented as simple presentational components — functional components that simply accept some props and return some ui.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4c49800439a8828bea361f3c269ec14/href">https://medium.com/media/c4c49800439a8828bea361f3c269ec14/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caf73496434c2f6e3096c0d34ad1fde9/href">https://medium.com/media/caf73496434c2f6e3096c0d34ad1fde9/href</a></iframe><p>Take a moment to compare these versions with the ones we started out with. That’s pretty damn sweet, if you ask me. Maintaining components like these is pure bliss.</p><p>Nice, but how do we actually use the withLoader component? Check it out:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a624cf572d611ab1f97e9bf48f647797/href">https://medium.com/media/a624cf572d611ab1f97e9bf48f647797/href</a></iframe><p>We just call withLoader with the component that needs functionality — which in this caseContactList and a function to fetch the data we need — fetchRandomUsers in this case. What we get in return, is a new component — ContactListWithLoader that has all the functionality we need. Now, instead of rendering ContactList directly, we’ll simply render ContactListWithLoader and boom — done.</p><p>You can see the withLoader HOC in action <a href="https://codesandbox.io/s/k2m840lv1o">here</a>.</p><p>Thanks to higher-order components, we can enhance our simple functional components with whatever logic we want. This is the power of the HOC pattern. We can manipulate props or maintain internal state outside of our presentational components.</p><h3>A few caveats to look out for</h3><p>Higher-order components come with a few caveats that aren’t immediately obvious if you’re new to React.</p><h4>1 — Don’t Use HOCs Inside the render Method</h4><p>React’s uses component identity to determine whether it should update the existing subtree or throw it away and mount a new one. If the component returned from render is identical (===) to the component from the previous render, React goes the update route. If they’re not equal, the previous subtree is completely unmounted (and remounted).</p><p>You normally shouldn’t need to think about this, but in the case of HOCs, it matters because it means you can’t apply a HOC to a component inside the render method of a component, since you’ll be effectively creating a completely new component every time. What to do instead?</p><p>Better to apply HOCs outside the component definition so that the resulting component is created only once. This way, its identity will be consistent across renders. If you need to apply a HOC dynamically, you can also do it inside a component’s lifecycle methods or its constructor to achieve the same effect of preserving the component’s identity across renders.</p><h4>2 — Static Methods Must Be Copied Over</h4><p>If you have defined any static methods on your React component, the new container component that gets returned when you apply a HOC will not have any of the static methods of your original component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4a28d19bcf965b713442213791e3ad0/href">https://medium.com/media/e4a28d19bcf965b713442213791e3ad0/href</a></iframe><p>To solve this, you could copy the methods onto the container before returning it like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a55a9028aacdbb869d414b5ea250e76/href">https://medium.com/media/8a55a9028aacdbb869d414b5ea250e76/href</a></iframe><p>However, this approach requires you to know exactly which methods need to be copied. You can use <a href="https://github.com/mridgway/hoist-non-react-statics">hoist-non-react-statics</a> to automatically copy all non-React static methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba12c4ce8acabf2dbb863f6e733ced38/href">https://medium.com/media/ba12c4ce8acabf2dbb863f6e733ced38/href</a></iframe><h4>3 — Refs Aren’t Passed Through</h4><p>The key thing to note here is, if you pass a ref to a HOC it will not get passed through to the wrapped component. The ref will refer to the outermost container component, instead of the the wrapped component. This is because when React encounters a ref attribute on a component, it attaches the ref to the HTML element or component on which the attribute was set. This is <strong>not</strong> what we want. Fortunately, we can explicitly forward refs to the wrapped component using the React.forwardRef API. Learn more about how to do this in <a href="https://medium.com/p/f407101a5ea6#25a3">this post on using refs</a>.</p><h3>Interesting Aside: Usage out in the wild</h3><p>I thought I’d take a moment to highlight out a good example of HOCs being used out there on the wild.</p><p><a href="https://redux.js.org/">Redux</a>, for example, uses a higher-order component returned by its, connect function to pass values from your application store to your components. It also does some error checking and component lifecycle optimisations that, if done manually would cause you to write a ton of boilerplate code. connect&#39;s typical signature looks like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/318c3630a26c790c19172dd50a61af09/href">https://medium.com/media/318c3630a26c790c19172dd50a61af09/href</a></iframe><p>It might not be immediately, obvious but connect is actually just a higher-order function that returns a higher-order component! If you break it apart, it’s easier to see what’s going on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b68c1448de39e0970e91b3ccac3b9e6/href">https://medium.com/media/0b68c1448de39e0970e91b3ccac3b9e6/href</a></iframe><h4><strong>Conclusion</strong></h4><p>By now, you hopefully have good understanding of HOCs — the situations where they really come in handy and how you might use them to share functionality and simplify things in your projects.</p><p>Higher-Order components are a very useful pattern in React. When used correctly, they can lead us to write significantly less code, and components that are easy to reason about and maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PB5HCij1C084Brzc" /><figcaption>Photo by <a href="https://unsplash.com/@ayahya09?utm_source=medium&amp;utm_medium=referral">Ali Yahya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Congratulations! You made it to the end. I had a lot of fun writing this article. If you find out useful, share it with someone who might too. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70cdb8e7230a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JSX — Up Close]]></title>
            <link>https://medium.com/@mrewusi/jsx-up-close-9d9d96248fe2?source=rss-2d9bf80cb91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9d96248fe2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Precious Nyarko]]></dc:creator>
            <pubDate>Mon, 29 Oct 2018 00:08:05 GMT</pubDate>
            <atom:updated>2018-10-29T00:08:05.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PMdH7aBldV0OHFAj" /><figcaption>“monitor showing C++” by <a href="https://unsplash.com/@dlanor_s?utm_source=medium&amp;utm_medium=referral">Dlanor S</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>JSX — Up Close</h3><p>If you write React code, then you no doubt, spend quite a bit of time, looking at, and writing JSX — perhaps, so much so, that you barely pause to give it a thought. But do you ever wonder why it works the way it does? Or why React must be in scope for it to work? Or why failing to wrap adjacent JSX elements in an enclosing tag, throws an error?</p><p>I could go on and on, but my point is that it’s often very helpful to know what’s happening under the hood, because it solidifies your understanding of how things work, and how to fix them when they don’t. Plus it makes you appreciate the tools you use even more. This post is an attempt to do just that!</p><h4>A world without JSX</h4><p>To appreciate what JSX is really doing for us, we have to first attempt to live in a world with JSX. To do that, it is helpful to remember that when a component renders it returns a tree of React<strong> elements</strong> — keyword here, being <em>elements</em>.</p><p>Without JSX the only other way to create a react element is to use the React.createElement(component, props, ...children) function. Let’s look at a simple example to see how it works:</p><p>Say we wanted to output a basic HTML form element to the DOM. Perhaps something like so &lt;form class=&quot;login-form&quot;&gt;&lt;/form&gt;. Using React.createElement() we’d something like so:</p><pre>React.createElement(<br>  &quot;form&quot;,<br>  { className: &quot;login-form&quot; }<br>);</pre><p>At first glance that might not seem so bad, but that’s because our form currently is doing anything useful. Now, say we wanted to add two text inputs and a button to allow users log into our app. The code would now become:</p><pre>function hello() {<br>  return React.createElement(<br>    &quot;form&quot;,<br>    { className: &quot;login-form&quot; },<br>    React.createElement(<br>      &quot;div&quot;,<br>      { className: &quot;input-group&quot; },<br>      React.createElement(&quot;input&quot;, {<br>        type: &quot;text&quot;,<br>        value: &quot;&quot;,<br>        placeholder: &quot;Email Address&quot;<br>      })<br>    ),<br>    React.createElement(<br>      &quot;div&quot;,<br>      { className: &quot;input-group&quot; },<br>      React.createElement(&quot;input&quot;, {<br>        type: &quot;password&quot;,<br>        value: &quot;&quot;,<br>        placeholder: &quot;Password&quot;<br>      })<br>    ),<br>    React.createElement(<br>      &quot;button&quot;,<br>      {<br>        type: &quot;submit&quot;<br>      },<br>      &quot;Login&quot;<br>    )<br>  );<br>}</pre><p>Now, mind you, all of the code above was needed to render something, as basic as, a couple of inputs in a form. Now try to imagine, for a moment, expressing more complex UI with this approach. Now, scratch that! Could you imagine writing your entire application’s UI like this?</p><p>Not only would trying to write a React application without JSX make for a very unpleasant developer experience. It would be extremely time consuming and will very likely turn into a spaghetti code mess, very quickly.</p><h4><strong>Enter JSX</strong></h4><p>JSX is a syntax extension to JavaScript. Basically, it produces React elements and provides us a sweeter, more compact way to describe what our UI should look like.</p><p>Put simply, JSX is just a shorthand way of writing React.createElement(). It basically gets compiled down into React.createElement() calls.</p><p>If you take a moment to mull over this, you now see why attempting to use JSX without having first imported React, produces an error. Basically, for us to be able to call React.createElement(), React must first be in scope.</p><p>Armed with this knowledge, it also becomes clear why something like this wouldn’t work:</p><pre>return (<br>  &lt;p&gt;A paragraph!&lt;/p&gt;<br>  &lt;p&gt;Another paragraph!&lt;/p&gt;<br>);</pre><p>Since both JSX expressions boil down to React.createElement() calls, you can see that we are essentially providing more than one return value, which won’t work. Hence the need to wrap them in an enclosing tag.</p><p>With that out of the way, let’s explore the the goodies that JSX has to offer.</p><h4>Expressions in JSX</h4><p>In the example below, we declare a variable called age and then use it inside JSX by wrapping it in curly braces:</p><pre>const age = 28;<br>const element = &lt;h1&gt;Hello, I&#39;m {age} year&#39;s old&lt;/h1&gt;;</pre><pre>ReactDOM.render(element, document.getElementById(&#39;root&#39;)); </pre><p>You can put any valid <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions">JavaScript expression</a> inside the curly braces in JSX. For example, !booked, user.firstName, or formatName(user) are all valid JavaScript expressions.</p><p>In the example below, we embed the result of calling a JavaScript function, formatName(user), into an &lt;h1&gt; element.</p><pre>function formatName(user) {<br>  return user.firstName + &#39; &#39; + user.lastName;<br>}<br><br>const user = { firstName: &#39;John&#39;, lastName: &#39;Doe&#39; };<br>const element = (<br>  &lt;h1&gt;<br>    Hello, {formatName(user)}!<br>  &lt;/h1&gt;<br>);<br><br>ReactDOM.render(element, document.getElementById(&#39;root&#39;)); </pre><p>Note that, if statements and for loops are expressions in JavaScript, so can’t be used inside JSX directly, but are fine when used in the surrounding code.</p><h4>JSX is an Expression Too!</h4><p>Because JSX expressions compile to regular JavaScript function calls, you can use JSX inside of if statements and for loops, assign it to variables, accept it as arguments, and return it from functions:</p><pre>function getGreeting(user) {<br>  if (user) {<br>    return &lt;h1&gt;Hello, {formatName(user)}!&lt;/h1&gt;;<br>  }<br>  return &lt;h1&gt;Hello, Stranger.&lt;/h1&gt;;<br>}</pre><h4>Specifying Attributes</h4><p>You may use either quotes (for string literals) or curly curly braces (to embed a JavaScript expression) when specifying the value of attributes in JSX.</p><pre>&lt;input placeholder=&quot;Enter your name&quot; /&gt;; // quoted string literal<br>&lt;img src={user.avatarUrl} /&gt; // expression</pre><p>Also, remember to not put quotes around curly braces when embedding a JavaScript expression in an attribute. You should either use quotes (for string values) or curly braces (for expressions), but not both in the same attribute.</p><pre>&lt;img src=&quot;{user.avatarUrl}&quot; /&gt; // don&#39;t do this</pre><h4>Specifying Children with JSX</h4><p>JSX tags may contain children:</p><pre>const element = (<br>  &lt;div&gt;<br>    &lt;h1&gt;Hello!&lt;/h1&gt;<br>    &lt;h2&gt;Good to see you here.&lt;/h2&gt;<br>  &lt;/div&gt;<br>);</pre><p>If a tag is empty, you may close it immediately with /&gt;:</p><pre>const element = &lt;img src={user.avatarUrl} /&gt;;</pre><h4>Specifying The React Element Type</h4><p>The first part of a JSX tag determines the type of the React element.</p><p>Capitalised types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX &lt;Foo /&gt;expression, Foo must be in scope.</p><h4>Choosing the Type at Runtime</h4><p>You cannot use a general expression as the React element.</p><p>For times when you don’t know the React element type ahead of time — say you want render a different component based on a prop — you should assign the expression that determines the type, to a capitalized variable first — and then used the variable name as the React element type in your JSX.</p><pre>import React from &#39;react&#39;;<br>import { PhotoStory, VideoStory } from &#39;./stories&#39;;</pre><pre>const components = {<br>  photo: PhotoStory,<br>  video: VideoStory<br>};</pre><pre>function Story(props) {<br>  // Wrong! JSX type can&#39;t be an expression.<br>  // return &lt;components[props.storyType] story={props.story} /&gt;;</pre><pre>  // Correct! JSX type can be a capitalized variable.<br>  const SpecificStory = components[props.storyType];<br>  return &lt;SpecificStory story={props.story} /&gt;;<br>}</pre><h4>User-Defined Components Must Be Capitalized</h4><p>When react encounters an element type starting with a lowercase letter, it thinks that the element it refers to is an HTML tag. So this example wouldn’t work as expected.</p><pre>import React from &#39;react&#39;;<br><br>// Wrong! This is a component and should have been capitalized:<br>function hello(props) {<br>  return &lt;div&gt;Hello {props.toWhat}&lt;/div&gt;;<br>}<br><br>function HelloWorld() {<br>  // Wrong! React thinks &lt;hello /&gt; is an HTML tag because it&#39;s not     capitalized:<br>  return &lt;hello toWhat=&quot;World&quot; /&gt;;<br>}</pre><p>As a result, you should capitalize your custom component names. Types that start with a capital letter like &lt;Bar /&gt; compile to React.createElement(Bar) and correspond to a component defined or imported in your JavaScript file.</p><pre>import React from &#39;react&#39;;<br><br>// Correct! This is a component and should be capitalized:<br>function Hello(props) {<br>  // Correct! This use of &lt;div&gt; is legitimate because div is a valid HTML tag:<br>  return &lt;div&gt;Hello {props.toWhat}&lt;/div&gt;;<br>}<br><br>function HelloWorld() {<br>  // Correct! React knows &lt;Hello /&gt; is a component because it&#39;s capitalized.<br>  return &lt;Hello toWhat=&quot;World&quot; /&gt;;<br>}</pre><h3>Props</h3><h4>Props Default to “True”</h4><p>If you pass no value for a prop, it defaults to true. These two JSX expressions are equivalent:</p><pre>&lt;MyTextBox autocomplete /&gt;</pre><pre>&lt;MyTextBox autocomplete={true} /&gt;</pre><p>The React docs discourage this, because it can be confused with the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015">ES6 object shorthand</a> {foo} which is short for {foo: foo} rather than {foo: true}. This behavior is just there so that it matches the behavior of HTML.</p><h4>Spread Attributes</h4><p>Do you already have props as an object, and you want to pass it in JSX? That’s dead simple too. You can use ... as a “spread” operator to pass the whole props object. These two components are equivalent:</p><pre>function App1() {<br>  return &lt;Greeting firstName=&quot;Ben&quot; lastName=&quot;Hector&quot; /&gt;;<br>}</pre><pre>function App2() {<br>  const props = {firstName: &#39;Ben&#39;, lastName: &#39;Hector&#39;};<br>  return &lt;Greeting {...props} /&gt;;<br>}</pre><p><strong>Tip:</strong> Mind you, JSX isn’t valid JavaScript. So while they look the same, the ... in the example above, is not JavaScript spread operator, but rather, JSX’s equivalent of it.</p><p>You can also pick specific props that your component will consume while passing all other props using the spread operator.</p><pre>const Button = props =&gt; {<br>  const { kind, ...other } = props;<br>  const className = kind === &quot;primary&quot; ? <br>    &quot;PrimaryButton&quot; : &quot;SecondaryButton&quot;;<br>  return &lt;button className={className} {...other} /&gt;;<br>};</pre><pre>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Button kind=&quot;primary&quot; onClick={() =&gt; console.log(&quot;clicked!&quot;)}&gt;<br>        Hello World!<br>      &lt;/Button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In the example above, the kind prop is safely consumed and <em>is not</em> passed on to the &lt;button&gt; element in the DOM. All other props are passed via the ...other object making this component really flexible. You can see that it passes an onClick and children props.</p><p>While useful, spread attributes make it easy to pass unnecessary props to components that don’t care about them or to pass invalid HTML attributes to the DOM. So, use this syntax sparingly.</p><h3>Children</h3><p>In JSX expressions that contain both an opening tag and a closing tag, the content between those tags is passed as a special prop: props.children. There are several different ways to pass children — namely <strong>string literals</strong>, <strong>JSX children</strong> and <strong>JavaScript expressions</strong>.</p><h4>String Literals</h4><p>As we’ve seen before, you can put a string between the opening and closing tags and props.children will just be that string. This is useful for many of the built-in HTML elements. For example:</p><pre>&lt;MyComponent&gt;Hello world!&lt;/MyComponent&gt;</pre><p>This is valid JSX, and props.children in MyComponent will simply be the string &quot;Hello world!&quot;. HTML is unescaped, so you can generally write JSX just like you would write HTML in this way:</p><pre>&lt;div&gt;This is valid HTML &amp;amp; JSX at the same time.&lt;/div&gt;</pre><p>Also worth noting, is that, JSX removes whitespace at the beginning and ending of a line. It also removes blank lines. New lines adjacent to tags are removed; new lines that occur in the middle of string literals are condensed into a single space. So these all render to the same thing:</p><pre>&lt;div&gt;Hello World&lt;/div&gt;</pre><pre>&lt;div&gt;<br>  Hello World<br>&lt;/div&gt;</pre><pre>&lt;div&gt;Hello     World&lt;/div&gt;</pre><h4>JSX Children</h4><p>You can also provide more JSX elements as the children. This is useful for displaying nested components</p><pre>&lt;MyContainer&gt;<br>  &lt;MyFirstComponent /&gt;<br>  &lt;MySecondComponent /&gt;<br>&lt;/MyContainer&gt;</pre><p>You can mix together different types of children, so you can use string literals together with JSX children. This is another way in which JSX is like HTML, so that this is both valid JSX and valid HTML:</p><pre>&lt;div&gt;<br>  Here is a list:<br>  &lt;ul&gt;<br>    &lt;li&gt;Item 1&lt;/li&gt;<br>    &lt;li&gt;Item 2&lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>A React component can also return an array of elements:</p><pre>render() {<br>  // No need to wrap list items in an extra element!<br>  return [<br>    // Don&#39;t forget the keys :)<br>    &lt;li key=&quot;A&quot;&gt;First item&lt;/li&gt;,<br>    &lt;li key=&quot;B&quot;&gt;Second item&lt;/li&gt;,<br>    &lt;li key=&quot;C&quot;&gt;Third item&lt;/li&gt;,<br>  ];<br>}</pre><h4>JavaScript Expressions as Children</h4><p>You can pass any JavaScript expression as children, by enclosing it within {}. For example, these expressions are equivalent:</p><pre>&lt;MyComponent&gt;foo&lt;/MyComponent&gt;</pre><pre>&lt;MyComponent&gt;{&#39;foo&#39;}&lt;/MyComponent&gt;</pre><p>This really comes in handy, when rendering lists of things inn your application. This example renders an HTML list:</p><pre>function Item(props) {<br>  return &lt;li&gt;{props.message}&lt;/li&gt;;<br>}</pre><pre>function TodoList() {<br>  const todos = [&#39;finish doc&#39;, &#39;submit pr&#39;, &#39;nag dan to review&#39;];<br>  return (<br>    &lt;ul&gt;<br>      {todos.map((message) =&gt; &lt;Item key={message} message={message} /&gt;)}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>JavaScript expressions can be mixed with other types of children. This is often useful in lieu of string templates:</p><pre>function Hello(props) {<br>  return &lt;div&gt;Hello {props.addressee}!&lt;/div&gt;;<br>}</pre><h3>Functions as Children</h3><p>Normally, JavaScript expressions inserted in JSX will evaluate to a string, a React element, or a list of things. However, props.children works just like any other prop in that it can pass any sort of data, not just the sorts that React knows how to render. For example, if you have a custom component, you could have it take a callback as props.children:</p><pre>// Calls the children callback numTimes to produce a repeated component<br>function Repeat(props) {<br>  let items = [];<br>  for (let i = 0; i &lt; props.numTimes; i++) {<br>    items.push(props.children(i));<br>  }<br>  return &lt;div&gt;{items}&lt;/div&gt;;<br>}</pre><pre>function ListOfTenThings() {<br>  return (<br>    &lt;Repeat numTimes={10}&gt;<br>      {(index) =&gt; &lt;div key={index}&gt;This is item {index} in the list&lt;/div&gt;}<br>    &lt;/Repeat&gt;<br>  );<br>}</pre><p>Children passed to a custom component can be anything, as long as that component transforms them into something React can understand before rendering. This usage is not common, but it works if you want to stretch what JSX is capable of.</p><h3>Booleans, Null, and Undefined Are Ignored</h3><p>false, null, undefined, and true are valid children. They simply don’t render. These JSX expressions will all render to the same thing:</p><pre>&lt;div /&gt;</pre><pre>&lt;div&gt;&lt;/div&gt;</pre><pre>&lt;div&gt;{false}&lt;/div&gt;</pre><pre>&lt;div&gt;{null}&lt;/div&gt;</pre><pre>&lt;div&gt;{undefined}&lt;/div&gt;</pre><pre>&lt;div&gt;{true}&lt;/div&gt;</pre><p>This can be useful to conditionally render React elements. This JSX only renders a &lt;Header /&gt; if showHeader is true:</p><pre>&lt;div&gt;<br>  {showHeader &amp;&amp; &lt;Header /&gt;}<br>  &lt;Content /&gt;<br>&lt;/div&gt;</pre><p>One caveat is that some <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">“falsy” values</a>, such as the 0 number, are still rendered by React. For example, this code will not behave as you might expect because 0 will be printed when props.messages is an empty array:</p><pre>&lt;div&gt;<br>  {props.messages.length &amp;&amp;<br>    &lt;MessageList messages={props.messages} /&gt;<br>  }<br>&lt;/div&gt;</pre><p>To fix this, make sure that the expression before &amp;&amp; is always boolean:</p><pre>&lt;div&gt;<br>  {props.messages.length &gt; 0 &amp;&amp;<br>    &lt;MessageList messages={props.messages} /&gt;<br>  }<br>&lt;/div&gt;</pre><p>Conversely, if you want a value like false, true, null, or undefined to appear in the output, you have to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#String_conversion">convert it to a string</a> first:</p><pre>&lt;div&gt;<br>  My JavaScript variable is {String(myVariable)}.<br>&lt;/div&gt;</pre><h4>Parting words</h4><p>I had hoped to leave you with a greater awareness and sense of appreciation of what JSX is really doing for you behind the scenes each time you use it. Hopefully, I’ve managed to do just that!</p><p>I hope you found this post useful. Any suggestions for improvements are very much appreciated !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9d96248fe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A gentle introduction to Refs in React]]></title>
            <link>https://medium.com/@mrewusi/a-gentle-introduction-to-refs-in-react-f407101a5ea6?source=rss-2d9bf80cb91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f407101a5ea6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Precious Nyarko]]></dc:creator>
            <pubDate>Sun, 21 Oct 2018 19:03:19 GMT</pubDate>
            <atom:updated>2018-10-21T19:03:19.740Z</atom:updated>
            <content:encoded><![CDATA[<p>In React, you generally should <strong>not</strong> be writing code that imperatively manipulates the DOM, but there are some situations where it’s necessary to do so. Refs exist, for just such occasions.</p><p>Refs provide a way access and manipulate DOM nodes and React elements , directly.</p><h4>When to use Refs</h4><p>When it’s okay to use refs? Well, the react <a href="https://reactjs.org/docs/refs-and-the-dom.html#when-to-use-refs">docs</a> provide some guidance. According to the docs, you should consider using refs when you need to:</p><ul><li>Manage focus, text selection, or media playback.</li><li>Perform imperative animations.</li><li>Integrate with third-party DOM libraries.</li></ul><p>This list isn’t meant to be exhaustive. For example, managing canvas and media elements are other good use cases. Whatever the case may be, it is important that you assess your needs to determine if refs are a good fit. Just keep in mind that they are essentially an escape hatch — a last resort of sorts — so don’t make it your go to thing. Always try to do things declaratively first.</p><h4>When to NOT use Refs</h4><p>In general, you avoid using refs for things that can be done declaratively. An example is updating the background colour of a div, in response to a click event.</p><p>In this scenario, you should pass a backgroundColour prop to your component, instead of exposing a changeBackground() method (which you then call via access to a Ref) on it.</p><p>Alrighty! Now that we know when to use refs, let’s discuss how to use them.</p><h4>Creating Refs — Using React.createRef()</h4><p>You can create refs using React.createRef() and attach them to React elements via the ref attribute. Essentially, you assign the Ref returned from React.createRef() to an instance property, when a component is constructed (aka, in the component’s constructor). This way, the Ref can be referenced throughout the component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZAwFAf2oSJGoQBuVIbOvQ.png" /></figure><h4>Creating Callback Refs</h4><p>Another way to set refs in React is to use <strong>callback refs</strong>. With this method, instead of passing a ref attribute created by createRef(), you pass a function that, when called, receives the React component instance or HTML DOM node as its argument, which can be stored and accessed elsewhere. Here’s what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8JB8K4ahTsjxc3E33V88Vg.png" /><figcaption>Example using callback refs</figcaption></figure><p>You may be wondering why we didn’t write the callback function line like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*x56bVmqXkjkbB7kp6ZxcnQ.png" /><figcaption>Ref callback as an inline function</figcaption></figure><p>Well, in most cases it shouldn’t matter, but, it’s useful to note that, React calls this function twice during updates, first with null and then again with the DOM node or React element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and setup the new one.</p><p>Defining the ref callback as a bound method on the class, allows us avoid this behaviour.</p><h4>When does the callback get called?</h4><p>We’ve talked of how the callback will get called with the appropriate element, but when exactly does this happen? Put differently, the question is, when can I expect that the ref, which in our example above, is inputRef will be set. Thankfully, the React docs are very clear on this:</p><blockquote>React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts. Refs are guaranteed to be up-to-date before componentDidMount or componentDidUpdate fires.</blockquote><h4>Accessing Refs</h4><p>How do you access a ref’s underlying DOM node or React element? Well, that depends on how you created the ref.</p><h4>Accessing Refs created with createRef()</h4><p>React.createRef() returns an object with a current property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*iMxhbw0PnRKQodpf3uA8vA.png" /><figcaption>The object returned by React.createRef()</figcaption></figure><p>You can retrieve the underlying DOM node or React element by accessing the object’s current property. You should note that, the underlying element will be a <strong>DOM node</strong> (if the ref was attached to an HTML element), or the <strong>mounted instance </strong>of the component (if the ref was attached to a custom class component).</p><p>Here’s an example to illustrate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lnQxYhO4Si31RO2O7j_P3Q.png" /><figcaption>Accessing refs created with React.createRef()</figcaption></figure><h4>Accessing Callback Refs</h4><p>Unlike the createRef() approach, when you a callback ref, the callback function you provide is called with the actual React component instance or HTML DOM node, as its argument.</p><p>Unlike when using createRef , we don’t receive an object with a current property. So you can store and access it directly without having to go through a current property to access it. Here’s an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xcdd2AcD5U1o89nOU7p_pg.png" /><figcaption>Accessing callback refs</figcaption></figure><h4>A quick note about functional components</h4><p>Remember how we said, that, when attached to your custom components, a ref’s current property receives the mounted instance of that component? Well, for functional components, this means that attaching a ref via the ref attribute won’t work, because functional components are, well, just functions and so there won’t be an instance to work with. The example below attempts to attach a ref to a functional component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSskgmFKhcNgucpTYnvBVg.png" /><figcaption>Attaching a `ref` to a functional component won’t work as expected</figcaption></figure><p>If you need a ref to a functional component, you should change the component to a class, just like you do when you need lifecycle methods or state.</p><h4>What if I want to access a child component’s DOM Refs from a parent component?</h4><p>In rare cases, you might want to access a child’s DOM node from a parent component. While not recommended, because it breaks component encapsulation, but it can occasionally be useful for triggering focus or measuring the size or position of a child DOM node.</p><p>If you find yourself in this position, you’ve got a few options depending on which version of React you’re on.</p><h4>With React 16.3 or higher</h4><p>If you use React 16.3 or higher, it is recommended that you use <a href="https://reactjs.org/docs/forwarding-refs.html">ref forwarding</a> — a technique for automatically passing a ref through a component to one of its children. This feature essentially allows a component to take a ref they receive, and pass it further down to a child.</p><p>It usesReact.forwardRef , which accepts a render function that receives props and ref parameters and returns a React node. In the example below, RedButton uses React.forwardRef to obtain the ref passed to it, and then forwards it to the DOM button that it renders:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeOYJml1c80Gg54jZ-6HyA.png" /><figcaption>Example using Ref forwarding</figcaption></figure><h4>Using ref forwarding with Higher Order Components (HOCs)</h4><p>The key thing to note here is, if you pass a ref to a HOC it will not get passed through to the wrapped component. Instead of referring to the wrapped component, the ref will refer to the outermost container component. This is because when React encounters a ref attribute on a component, it attaches the ref to the HTML element or component on which the attribute was set. This is <strong>not</strong> what we want. Although we are setting the ref on the HOC, we really want the ref to get forwarded down to the wrapped component, instead of being attached to the HOC.</p><p>Fortunately, we can explicitly forward refs to the wrapped component using the React.forwardRef API. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9PKBnx_o5lxjDP0BMCCaw.png" /><figcaption>Using ref forwarding with HOCs</figcaption></figure><h4>With React versions below 16.3</h4><p>React 16.2 and earlier doesn’t yet support <a href="https://reactjs.org/docs/forwarding-refs.html">ref forwarding</a>. If you need to expose a DOM ref to components above and can’t migrate to React 16.3+ yet, you can use the following approach instead.</p><p>You pass the ref to the child component as a differently named prop — really any name other than <strong>ref </strong>(e.g. <strong>buttonRef</strong> ) . The child component can then forward the prop to the DOM node via the ref attribute. This lets the parent pass its ref to the child’s DOM node through the component in the middle. This works both for classes and for functional components. Here’s what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yMRYme7eLCdCFY0VXA-FnQ.png" /></figure><p>In the example above, Parent passes its class property this.inputElement as an inputRef prop to the CustomTextInput, and the CustomTextInput passes the same ref as a special ref attribute to the &lt;input&gt;. As a result, this.inputElement.current in Parent will be set to the DOM node corresponding to the &lt;input&gt; element in the CustomTextInput.</p><p>Note that the name of the inputRef prop in the above example has no special meaning, as it is a regular component prop. However, using the ref attribute on the &lt;input&gt; itself is important, as it tells React to attach a ref to its DOM node.</p><h3>Conclusion</h3><p>Refs offer a great way to pass data down to a child instance, outside outside of the typical data flow. While really come in handy for situations where you really need to access and manipulate DOM elements, you should be careful not to overuse refs.</p><p>You should bear in mind that, refs manipulate the actual DOM as opposed to virtual DOM which is contradictory to the React ethos. So use them sparingly.</p><p>Hope this post has left you with a good understanding of refs<strong> </strong>along with its use-cases and caveats. If you found this post useful, do share it with good peeps around you. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f407101a5ea6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From jQuery to React]]></title>
            <link>https://medium.com/@mrewusi/from-jquery-to-react-6d518ab7999d?source=rss-2d9bf80cb91d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d518ab7999d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Precious Nyarko]]></dc:creator>
            <pubDate>Sun, 14 Oct 2018 18:57:07 GMT</pubDate>
            <atom:updated>2018-10-14T18:57:07.605Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a better credit card form at expressPay</h4><h4>Introduction</h4><p>I believe that paying for stuff online should be easy. That’s why, in my honest opinion, any bit of UI the user has to interact with on their way to that sweet confirmation page, has to either, be helping them get there faster or shouldn’t be there at all.</p><p>At expressPay, our service allows anyone to instantly send money to any bank account or mobile money number, buy airtime and pay for online services using, among other methods, their debit card. Our debit card form hadn’t changed in a long time. It got the job done, but, the way I saw it, could benefit from a makeover that focused on improving clarity, simplicity and user happiness.</p><p>My job was to design the credit card form, given a set of business requirements and constraints. This post is about the design considerations our team explored to arrive at the finished product.</p><h4>Preparation</h4><p>I knew from the get go, that I wanted to write the new form in React. Why? First off, I should mention that our current form was written with HTML, CSS and jQuery. Not only did this make the code sort of wonky, but IMHO, it made it incredibly painful to look at, and more importantly, to reason about. Secondly, I love how React made you think of your apps as you build them. React’s component driven paradigm also made it incredibly easy to write reusable components, that ultimately reduce the amount of code you write and allow you to build apps more efficiently.</p><h4>Starting at the basics</h4><p>At it’s most basic, a credit card form is essentially just a collection of <em>inputs</em> — emphasis here on <em>inputs</em> — that allowed a user to enter the different bits of information that make up their card details.</p><p>So my first order of business was to craft a simple, but versatile input component, that, with minimal effort, I could reuse to collect the different bits of information that made up the user’s card details.</p><h4>Building the input component</h4><p><strong><em>First came the question of styling — </em></strong>Although we wanted this component to be as generic as possible, there were still business requirements concerning how the input should look. This was after all an expressPay text input component, and our style guide had clearly prescribed the baseline look for text inputs used on our site. Here’s a visual of what that looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l1WxX46Ge2l9a6wqdhqoUw.png" /></figure><p>So, the takeaway here is that the input was going to come bootstrapped with with default styling that conformed to our style guide, but would still allow the consumer override these defaults if they wanted to.</p><p>Also, because we wanted to be able to take advantage of the full css spec when styling our components, we skipped inline styles and decided to go with <a href="https://github.com/Khan/aphrodite">Aphrodite</a>.</p><p><strong>Next came the question of state</strong> — specifically how much, if any, internal state should the component was was allowed to manage. Here, we decided that although we wanted to pass in as much as we could via props we also wanted the component to at least keep track of whether or not it had the focus, internally. This meant adding a hasFocus field to its internal state.</p><p>Now it came identifying the different constituent parts that together, make up the text input component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*a8VNSUG89k61Ma1GqcomGA@2x.png" /></figure><ol><li><strong>HTMLTextInput</strong> provides the actual input into which the user types</li><li><strong>InputIndicator</strong> an optional component, passed in via props, that if present will be rendered to the far right end of the bordered box. In the case of card number field, this <strong>InputIndicator</strong> could be used to show the card issuer’s logo.</li><li><strong>BorderedBox </strong>is a div with a solid border that contains <strong>HTMLTextInput</strong> and <strong>InputIndicator</strong> This is what the user perceives as the actual input, since it <strong>HTMLTextInput</strong> doesn’t render with a border.</li><li><strong>ErrorMessage </strong>renders an error message beneath the bordered box, if an error is present.</li><li><strong>InputContainer:</strong> is a div that contains all the above mentioned items</li></ol><p>With all the constituent parts laid out, I moved forward with the implementation. Let’s take a crack at it.</p><p>Here’s the <strong>TextInput</strong> Component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/435118bfdb1c6e6bb975a668769556e8/href">https://medium.com/media/435118bfdb1c6e6bb975a668769556e8/href</a></iframe><h4>Building more specialised input components</h4><p>With our generic <strong>TextInput</strong> component in place, we could now shift our attention to creating the more specialised components that our credit card form needed. In no particular order, these are <strong>CardCVVInput</strong>, <strong>CardExpiryInput</strong>, <strong>CardNumberInput</strong> and <strong>CardHolderNameInput</strong> respectively.</p><p>Here’s the <strong>CardNumberInput</strong> component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16b567c8b8e76b4223217f955a06ebf4/href">https://medium.com/media/16b567c8b8e76b4223217f955a06ebf4/href</a></iframe><p>Here’s the <strong>CardHolderNameInput</strong> component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9c07c87aae9af2dcae239f2678ecd1d/href">https://medium.com/media/f9c07c87aae9af2dcae239f2678ecd1d/href</a></iframe><p>Here’s the <strong>CardExpiryInput</strong> component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aa503feb6b7cdc548bf1d9cccdb63b4/href">https://medium.com/media/8aa503feb6b7cdc548bf1d9cccdb63b4/href</a></iframe><p>Here’s the <strong>CardCVVInput</strong> component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb9c8d588584d29bb212ed697c16e1ce/href">https://medium.com/media/bb9c8d588584d29bb212ed697c16e1ce/href</a></iframe><p>Oh — you’ll notice that components depend on functions and constants imported from ../utils . Here’s the contents of that file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd3396363bd128b45d6d526f7223f744/href">https://medium.com/media/cd3396363bd128b45d6d526f7223f744/href</a></iframe><p>Next on the agenda was, writing the <strong>CreditCardForm</strong> component itself. This component would bring everything together by doing the following:</p><ol><li>Visually combining the various input components we previously put together in such a way as to achieve our overarching objective — allowing users to enter their card information.</li><li>Holding all state necessary to capture the user’s card information, as well as the functions responsible for managing that state.</li><li>Passing down state (and the functions that manage that state) to the various input components it encloses.</li><li>Housing validation logic and handling errors</li></ol><h4><strong>A word on validations and error handling.</strong></h4><p>When it came to validations we knew we wanted to simplify as much as possible. Our objective was to prevent as much bad input as we could from being entered in the first place.</p><p>As a result, you’ll see that some of our more specialised input components include an onKeyDown function, containing logic to reject bad inputs, which they pass down to the underlying TextInput component. We felt that this approach reduced the amount of time we spent yelling at users via error messages while allowing us get them to success more quickly.</p><p>Secondly, we chose to trigger validation logic on blur because, by leaving an input, the user was more or less indicating that they were done providing that piece of information. We also chose to not lock the user into an erroneous field by preventing them from leaving it. The user is free to move to the next input, and come back later to fix any errors shown.</p><p>Without further ado, here’s the code for theCreditCardForm component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0477970d08417ee1e6bdbb1336330623/href">https://medium.com/media/0477970d08417ee1e6bdbb1336330623/href</a></iframe><p>And here’s what it looks like when rendered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GL1G2qQZOjeafu3rRmyoPw.png" /></figure><p>The full code, along with a <a href="https://codesandbox.io/s/vvrqjm7v07?view=preview">working demo</a> can be found here. Feel free to take it for a spin. If you find a bug, or have feedback or a criticism, it is all very welcome. I’d love to hear from you.</p><h4>Final Words…</h4><p>I had a lot of fun putting this together. The payments space is not exactly sexy, but learning and understanding the user interactions behind accepting a credit card payment was really fun.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d518ab7999d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>