<?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 Matan Kastel on Medium]]></title>
        <description><![CDATA[Stories by Matan Kastel on Medium]]></description>
        <link>https://medium.com/@zmtmaster?source=rss-7a11a2eb8325------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*peqVqTlVw6b325bEsw5qqw.png</url>
            <title>Stories by Matan Kastel on Medium</title>
            <link>https://medium.com/@zmtmaster?source=rss-7a11a2eb8325------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:31:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zmtmaster/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[React Native OTP Screen: A Journey Through Development and Challenges]]></title>
            <link>https://zmtmaster.medium.com/react-native-otp-screen-a-journey-through-development-and-challenges-d20e133f1e23?source=rss-7a11a2eb8325------2</link>
            <guid isPermaLink="false">https://medium.com/p/d20e133f1e23</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[otp-verification]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Matan Kastel]]></dc:creator>
            <pubDate>Sat, 18 May 2024 18:25:14 GMT</pubDate>
            <atom:updated>2024-05-18T20:30:00.406Z</atom:updated>
            <content:encoded><![CDATA[<p>My team and I recently developed an OTP (One-Time Password) screen using React Native. In this post, I will walk you through our approach, the challenges we encountered, and how we overcame them.</p><p>Before we dive in, a quick note: yes, our implementation does support automatic code retrieval, and I’ll explain more about that later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGH4w7VYpZNCh9GghAY7GA.png" /></figure><h3>Plain and simple</h3><p>First, we wanted a screen with six digits, so we created a straightforward implementation using an array to store each digit’s value. As the user interacts with the screen, we update these values.</p><p>We encountered two issues. The first was handling input focus: moving to the next input when a digit is entered and going back if the user presses backspace. To achieve this, we created a series of references and tracked the current index on each text change to adjust the focus accordingly.</p><p>The second issue was auto-submitting the code when the last digit is entered. This required joining the values from the array into a single string and ensuring the string’s length is correct before submitting. We also had to limit each input to one digit to prevent multiple digits in a single input field.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef4eee390d4098beca36a38fc631e29e/href">https://medium.com/media/ef4eee390d4098beca36a38fc631e29e/href</a></iframe><p>While managing this was code-intensive, it worked…</p><p>— Until the requirement changed to support automatic OTP insertion.</p><h3>Adapting to Automatic OTP Insertion</h3><p>Now that we need to support automatic OTP insertion, we aimed to add the necessary property for iOS. React Native conveniently provides an API to inject the SMS code for iOS devices using a neat prop.</p><p>However, this introduced a new challenge. What happens if the user presses the button to fill the code? Should we apply this property to all the inputs and then split the code among them during the change? This approach doesn’t work because we limited each input to a single digit to prevent users from entering multiple digits in one field.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F6ib6KPmkeAjDTxMxij%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExbHZhaThxM3IwOWx3NjFvNDAwNzA5eHZmNGtpdm9hYTB0dHByc2xkbCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F6ib6KPmkeAjDTxMxij%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExMTJxOHJhY2NkenI5dGtxa2Z1ZDVyYjRvanZpbXhldnJmcHptOHVxZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F6ib6KPmkeAjDTxMxij%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/549e8d285b663a0fdd5777402280a98c/href">https://medium.com/media/549e8d285b663a0fdd5777402280a98c/href</a></iframe><h3>The Revelation</h3><p>If you’re a web developer transitioning to React Native, like myself, you might remember a cool trick used on the web. When creating a custom checkbox, you’d hide the original input and use CSS to create a nicer version. We applied a similar concept here.</p><p>Instead of rendering six text inputs, we rendered six views and one hidden text input that actually controls the input. Each view is wrapped in a Pressable element, allowing us to shift the focus to the hidden input using references, enabling the keyboard to edit the value. This approach solved many problems:</p><ul><li>Moving to the next and previous inputs using references? Gone.</li><li>Limiting each text input to one digit? No longer an issue.</li><li>Handling auto-submit? We only need to manage one input, which still works seamlessly.</li><li>Supporting automatic OTP insertion? Just add the property we mentioned earlier. Done.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ad959c76e012e507638ad6d7d0443a3/href">https://medium.com/media/6ad959c76e012e507638ad6d7d0443a3/href</a></iframe><p>This method makes the code cleaner and more elegant, wouldn’t you agree?</p><h4>Handling Android</h4><p>Supporting Android devices is straightforward. We used Kotlin to register and handle the OTP code. It’s important to remember to unregister when you’re done retrieving the code to avoid any unnecessary overhead.</p><p>Once you receive the SMS and extract the OTP code, simply update the hidden input local state with the code, and that’s it! This ensures that our implementation works seamlessly across both iOS and Android devices.</p><p>To bridge the communication between the native side and the React Native component, we utilized a custom React hook and event listeners from the native side using events.</p><h3>Conclusion</h3><p>We encountered the challenge of creating a seamless OTP input screen in React Native while ensuring support for both iOS and Android devices. Through innovative thinking and adaptation of web development techniques, we devised a solution that not only met our requirements but also streamlined the implementation process.</p><p>By rendering six views instead of text inputs and utilizing a hidden input to control user input, we overcame various challenges, including handling input focus, limiting digit input, and enabling auto-submit functionality. This approach proved to be cleaner and more elegant, resulting in a more efficient implementation.</p><p>Furthermore, we successfully extended support to Android devices by leveraging Kotlin to register for SMS events and bridge communication with the React Native component. This ensured consistency and reliability across both platforms.</p><p>In conclusion, by combining creative problem-solving with effective collaboration between web and mobile development paradigms, we achieved our goal of creating a robust and versatile OTP input screen in React Native.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FnVHVMfcyITKFi%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExNmJrd2JnNWltYnFjcHUza2RlbnhzMDllNGVzbHFlZ25xMWswZTM4bCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FnVHVMfcyITKFi%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExdDMwcHh3MnJjY2IzaGdiNWl2dDh3ZnJ2YzE0YXJ1ejA1NWcxbmxyMSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FnVHVMfcyITKFi%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="246" frameborder="0" scrolling="no"><a href="https://medium.com/media/41f5842efce11e4888c01e5e3ae0c0ad/href">https://medium.com/media/41f5842efce11e4888c01e5e3ae0c0ad/href</a></iframe><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d20e133f1e23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Cookie Authentication]]></title>
            <link>https://javascript.plainenglish.io/react-native-cookie-authentication-83ef6e84ba70?source=rss-7a11a2eb8325------2</link>
            <guid isPermaLink="false">https://medium.com/p/83ef6e84ba70</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Matan Kastel]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 20:43:24 GMT</pubDate>
            <atom:updated>2024-08-01T16:56:01.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>How did I resolve an issue with cookies-based authentication in a React Native application.</h4><p>Before we start, a shout-out to @<a href="https://locastic.medium.com/?source=post_page-----80ee18f4c71b--------------------------------">Locastic</a> is required. This post is mostly based on <a href="https://medium.com/locastic/react-native-cookie-based-authentication-80ee18f4c71b"><strong><em>React Native cookie-based authentication</em></strong> </a>but contains more detailed code examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*VB-3vUjlH9DK-jCQXccsgA.png" /></figure><h3>Introduction</h3><p>Authenticating a user is single-handedly the most required feature when building a modern web or mobile app. It allows verifying users, user sessions, and most importantly it provides the base for implementing user authorization (roles and permissions).</p><p>So what is this used for? As frontend developers, we usually just develop a sign-in form and send a request to a server. If the server responds positively, the user is logged in. Sounds easy right? So far, so good.</p><p>But the server returned one more thing: some kind of user identification you need to pass together with the following requests to access certain endpoints. In addition, when the user closes the app without logging out, thanks to this we can keep him logged in and skip the login step every time the user opens the app.</p><p>It is either token-based authentication or session-based authentication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wccGR2fmBvWBws-xQoeLhA.jpeg" /><figcaption>Cookie Based Authentication</figcaption></figure><p>In cookie-based authentication, after successful login, the server creates the session and returns the session-id value as Cookie. Followed requests contain that cookie with session-id which is verified against session-id on the server to determine if the session is valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*uxcuj8S36lruurB1zG1neA.jpeg" /><figcaption>JWT Based Authentication</figcaption></figure><p>On the other hand, we have token-based authentication. After successful login server returns the signed token. That token is then usually stored in local storage. Following requests are sent together along with the saved token in the Authorization header. The server decodes the token and if it is valid, processes the request.</p><h3>Which one is better to use?</h3><p>In my personal opinion, if you have the ability to choose, use JWT. In most modern web applications, JWTs are widely used as it scales better than that of a session-cookie based. Because tokens are stored on the client-side while the session uses the server memory to store user data, and this might be an issue when a large number of users are accessing the application at once. However some companies still rather use cookie flow since they rely on legacy code. So if you are at a point, like me, where you can not choose and have to use the existing security authentication system placed in the organization, this post is for you.</p><p>In this post I will go through cookie-based authentication in React Native and here’s the catch — it is not as straightforward as you might think.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*De3uRIOfruS4Cz7c2_FxiQ.gif" /><figcaption>The Cookie Monster</figcaption></figure><blockquote>💡 Speed up your blog creation with <a href="https://differ.blog/differ-ai"><strong>DifferAI</strong></a>.</blockquote><blockquote>Available for <strong>free </strong>exclusively on the <strong>free and open blogging platform, </strong><a href="https://differ.blog/"><strong><em>Differ</em></strong></a><strong><em>.</em></strong></blockquote><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><h3>The Problem</h3><p>React Native relies on the native (Android and iOS) APIs written in Java and Objective-C. You may think the cookie usage is as straightforward as using it within the browser but unfortunately, it isn’t.</p><p>Native networking APIs <strong>are savin</strong>g the <strong>cookies by default</strong> and it may seem perfectly okay at the beginning, but some time later &amp; few requests made, requests can become inconsistent causing the server to deny the access. Because cookies we sent were invalid even though there is nothing wrong with them while debugging — when they initially were passed along the request. You can trust me when I say, you can spend hours to find out that the Authentication system is the reason you get those nasty 401s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*n6gQPNw-hZBAt8ERl6ZjFg.png" /></figure><p>Controlling the cookies set on Android is so complex the React Native team published a section on it on the official <a href="https://reactnative.dev/docs/0.61/network#known-issues-with-fetch-and-cookie-based-authentication">documentations</a>! It&#39;s a known issue, no matter which fetch library you decide to use in the frontend, the Native side will handle the cookies for you.</p><p><a href="https://github.com/facebook/react-native/issues/23185">Cookie based authentication issues aggregation · Issue #23185 · facebook/react-native</a></p><p>It has something to do with the way Java uses key-based value so when you receive a cookie key back, it overrides the previous one.</p><h3>Towards the Solution</h3><p>When you try to be brave about it you always go around it the following way. You think to yourself, “Hmm, I have a local storage, I can just set the cookie there, and for every API call, just pull it out and append it.”</p><p>So, after a successful login, the server responds with the status and cookies. Now, you try saving the cookies on the device (asynchronous storage, local storage or even using state management like Redux). Then each subsequent request Header is populated with the cookie from device storage.</p><p>But let’s analyze what’s really going on, shall we?</p><p>React Native has its own cookie management, meaning that when the server returns header Set-Cookie, the next API call will already have that cookie set on its header by default, so providing the cookie here will have to effect.</p><p>We implemented our own handlers but they have no actually native meaning since we use a fetch library (such as Axios) to build the API callbacks that handle the request and the response but the Native device is the one that actually sends the request itself. Overriding the cookie with our own was causing the same problems to appear, and in my case, it only happened on Android — go figure. 🤷‍♂️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*lGOupxR0r1u5jYm0xAp47Q.gif" /></figure><p>After some research, I came across <a href="https://github.com/react-native-cookies/cookies">react-native-cookies</a>. It’s a cookie management library for React Native that lets you manage cookies <strong>natively</strong>. Now there is actually a way to manipulate native cookie management, the approach with storing the cookie on the device can be further improved.</p><p>So let’s completely remove native cookies and work just with the ones stored on the device. The easiest way would be to just clean up the cookies stored natively.</p><h3>The Solution</h3><p>Luckily for me, I have a separation of concerns in my project. The network manager (which in my case is <em>Axios</em>, but it can be any other…) is created only once. Each time I want to make an API call I import the `fetcher` and make a network request.</p><p>Here is how I’d use it in my code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88bf1790170e98e297efe89a5bfbaa54/href">https://medium.com/media/88bf1790170e98e297efe89a5bfbaa54/href</a></iframe><p>A basic implementation of a network manager would look like something like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5362b1a824bca2deca298135ea550d49/href">https://medium.com/media/5362b1a824bca2deca298135ea550d49/href</a></iframe><p>So, using the cookie-manager we can update the network manger file to remove all cookies and re-assign then on the get request (as an example).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2e9a0590cdcfcc4584fab9bfeebe102/href">https://medium.com/media/b2e9a0590cdcfcc4584fab9bfeebe102/href</a></iframe><p>This way — anyone that is using the network manager (`<em>fetcher().get()</em>`) will get this cookie management out of the box without even them knowing about this cookie headache 😎</p><p>Notice that we did not need to change any usages to the components using the fetcher instances.</p><p>With natively stored cookies cleaned up before each request, it’s certain that the only cookies that are passed along the request are the ones stored manually on the device.</p><h3>Conclusions</h3><p>Using the updated network manager ensures us there are no more cookies interfering with each other while maintaining consistent sessions when using the application!</p><p>I hope I’ve made it a bit clearer — how’d you resolve this issue of cookie management on React Native. Feel free to contact me on Twitter <a href="https://twitter.com/MatanKastel">@matan.kastel</a> with any questions you might have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*gIjjlFaj-8iR9zaDwxHI1w.gif" /></figure><p>If you liked this post, you can check out my other ones such as <a href="https://zmtmaster.medium.com/my-react-native-style-building-blocks-f144a22cbcad"><strong><em>my React Native style building block</em></strong></a>, or <a href="https://medium.com/swlh/custom-tab-navigator-using-react-navigation-svg-b659b395a7c4"><strong><em>Custom Tab Navigator Using React Navigation &amp; SVG</em></strong></a><strong><em>.</em></strong></p><p>Until next time, take care! 😷</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83ef6e84ba70" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-native-cookie-authentication-83ef6e84ba70">React Native Cookie Authentication</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My React Native Style Building Blocks]]></title>
            <link>https://medium.com/swlh/my-react-native-style-building-blocks-f144a22cbcad?source=rss-7a11a2eb8325------2</link>
            <guid isPermaLink="false">https://medium.com/p/f144a22cbcad</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[style]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[style-guides]]></category>
            <dc:creator><![CDATA[Matan Kastel]]></dc:creator>
            <pubDate>Mon, 25 Jan 2021 21:15:01 GMT</pubDate>
            <atom:updated>2021-01-26T21:00:27.870Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post I will describe my styling workflow in a React Native project. I use Typescript in the code samples but you can still use JavaScript if you like it better 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-yJv8ee7OYxkpb0A.jpg" /></figure><h3>Atomic CSS</h3><p>So a little introduction. If you are coming from a web-based React background, you should be familiar with the concept of Atomic classes. This concept isn’t a new thing and it is with us since about 2016.</p><p>For those who do now know what that concept is - in short, it’s a bunch of classes where you can place them all together to create your own styling,</p><p>The most used CSS framework today is probably Bootstrap, where you have some class and by using them you can quickly build the UI you need. Although Bootstrap is considered old — many still use it today. A recent CSS framework is that is becoming popular is <a href="https://tailwindcss.com/"><em>tailwindcss</em></a>.</p><p>Taliwind uses heavily the concept of Atomic CSS where you have (a lot of) class names and by putting them all together you can create a complex UI in minutes.</p><h4><em>What&#39;s the different you wonder</em>?</h4><p>Well, let us take an analogy to demonstrate. In Bootstrap for the analogy you get a Bootstrap Kitchen, a Bootstrap Bedroom. I mean you have a premade rooms where you can then later customize the things you need, fix the color of the bed, or change the size of the dresser. On the other hand, in Taliwind, the classes are more specific — you get more of a control. Back to the analogy, Taliwind doorknob, a Taliwind floor , a Taliwind sink. Put them all together to construct our own Kitchen.</p><p>Another big and important different is the way the two differ is styling. In Taliwind you can work with a fixed sets (spacing, coloring etc) which makes it more agile and less complex for the develops to handle the possible class overrides needed.</p><p>Now that we understand the concept of Atomic classes. we can apply the same ideas to React Native.</p><h3>But wait? Classes in React Native?</h3><p>Well no, in React Native, of course, we do not use classes but Stylesheets or inline styles.</p><h4>So what can you do?</h4><p>Well, I’ve got inspired by <a href="https://github.com/Shopify/restyle">@shopify/restyle</a> package. But since I could not use it in my projects (licenses and lawyers, go figure 💼), I’ve needed to implement a simple type-safe system for me to use.</p><p>I start by defining the building blocks such as color palette, spacings and also text variants, which are some kind of grouping for text stylings. We can also set breakpoints sizes here as well if we need.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1d011218b32078a94aae13b688749fe/href">https://medium.com/media/d1d011218b32078a94aae13b688749fe/href</a></iframe><h3>Box &amp; Text where the magic is happing?</h3><p>Now that we have the theme, in React Native we commonly use View &amp; Text components. Instead, we are going to do use our Box &amp; Text components while doing so, we can provide the styling inline as props to these components.</p><p>First, we will interduce the code for both. Later, we can dive in a little further. I use use the Context API to consume the Theme wherever is needed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab2cbbda7b15686f469aa0638b0a5822/href">https://medium.com/media/ab2cbbda7b15686f469aa0638b0a5822/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bfafa8bbbcf886dd98d97882dbf9afb/href">https://medium.com/media/2bfafa8bbbcf886dd98d97882dbf9afb/href</a></iframe><h4>Okay, you are still here? so how would you use it? How would that look?</h4><p>Before we dive into the magic - lets first see an example of how we use these two components to design our UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2272a4e4ee4379cef2c6a8fc1b2a10f/href">https://medium.com/media/f2272a4e4ee4379cef2c6a8fc1b2a10f/href</a></iframe><p>See how clean the code is? No StyleSheet needed? Easy to understand? Am I right? We use the variants for the texts, and we provide a vertical padding using our theme system. We can also use flex-box — Isn’t it cool?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*6NKz_xGDtAKhK4LUqrtNRA.png" /><figcaption>A simple card</figcaption></figure><h3>More Complex ? We can still do it!</h3><p>So what happens in a real life scenario where the code is more complex? Well it turns out since we are using the Context API its not that complex. That’s the beauty of building blocks. We can just consume it wherever we need it- and provide it to any component we want that isn’t using a Box! We can always use a Box for the layout and provide theming using context.</p><p>In the following example the button component uses TouchableOpacity and we inject styling using the context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b2c2d0110c6138baded4c7214d6b779/href">https://medium.com/media/4b2c2d0110c6138baded4c7214d6b779/href</a></iframe><h3>So How does the magic works?</h3><p>If you came this far you would probably want to check the full code, but to keep it short and simple — basically we just have helper functions that transform the sizes to actual View &amp; Text props. For example, when you provide a Box component with padding “m” — we convert the “m” to the size set on the theme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*K5fAaCMjINh7lp0t2Cr3-A.png" /><figcaption>a helper function to convert theme to props</figcaption></figure><h3>Final Notes</h3><p>So this is how I use Box &amp; Text components to set the layout for my React Native applications making it super easy to build a clean UI. It’s easy to maintain and if you can use typescript, go for it, the auto-complete is great. In my projects when I need to support default font size or a default font or even fonts in the text variants, its super easy to update, just update the Text component or the Theme and <strong>Voilà</strong>!</p><p>By using the Context API we can also support <strong>dark and light </strong>modes, branding or anything else just by settings the theme to the provider. Everything else — <strong>stays the same</strong>!</p><p>Hope I inspire you to think outside of the box (get it? box? haha 😁)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*v0NIvSoLZLLNp0Qr.gif" /></figure><p>Here is the complete repository if you want to take a look</p><p><a href="https://github.com/zmtmaster/react-native-theme">zmtmaster/react-native-theme</a></p><p>If you want to read more about react native, here is a post about <a href="https://medium.com/swlh/custom-tab-navigator-using-react-navigation-svg-b659b395a7c4?source=your_stories_page-------------------------------------">Custom Tab Navigator Using React Navigation &amp; SVG</a> or you can also checkout my post about <a href="https://medium.com/swlh/the-heart-of-react-native-transform-e0f4995ebdb6?source=your_stories_page-------------------------------------">The Heart of React Native Transform</a>.</p><p>Until next time, take care ✌😷</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f144a22cbcad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/my-react-native-style-building-blocks-f144a22cbcad">My React Native Style Building Blocks</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Heart of React Native Transform]]></title>
            <link>https://medium.com/swlh/the-heart-of-react-native-transform-e0f4995ebdb6?source=rss-7a11a2eb8325------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0f4995ebdb6</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[transform]]></category>
            <dc:creator><![CDATA[Matan Kastel]]></dc:creator>
            <pubDate>Fri, 06 Nov 2020 10:32:25 GMT</pubDate>
            <atom:updated>2020-11-06T16:27:05.637Z</atom:updated>
            <content:encoded><![CDATA[<p>Before I start, a shoutout to <a href="https://medium.com/u/4bdbd6b3a30a">William Candillon</a> is required. If you are a React Native developer, and you haven’t seen it by now, go and check out his YouTube series “<a href="https://www.youtube.com/channel/UC806fwFWpiLQV5y-qifzHnA"><em>Can it be done in React Native</em></a>”, with a new season 4 released the past month.</p><p>This post is based on a video he posted “<a href="https://www.youtube.com/watch?v=0FVnzuyFNSE">The Heart of React Native Transform</a>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*DS7eXojcb9a75I6_WP4cUA.gif" /></figure><h3>Introduction</h3><p>Let’s start with some basics - mathematics. We have two axes, X and Y, describing the direction an object can move on a 2 dimensional (2D) canvas. What we want to do in the following example is to rotate a card. Since the <strong><em>transform </em></strong>prop of a &lt;view/&gt; component in React Native is an <strong>array</strong>, that probably means the<strong> order matters</strong> right? 👀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*TFGdMVsQDdim3NhX6i80bg.gif" /></figure><h3><strong>Not as You Think</strong></h3><p>The key is to understand transforms in general. Let’s break down what we want to do. We have some cards that we want to rotate but we want to rotate them on the one side — creating some kind of fan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*2t8JzghhCRdMG_s5fSfLNQ.png" /><figcaption>A fan of cards</figcaption></figure><p>If we just add <strong><em>rotate</em></strong> prop to the <strong><em>transform</em></strong> style prop, and add some angle, we’d immediately see that the origin of the rotation is the <strong>center </strong>of the card, and that is not what we want. We would like the center of the rotation to be on the bottom edge of the card.</p><p>We want to <strong>translate the origin</strong> of the transformation — so we need to add some <strong>translate </strong>props to the array <strong>before </strong>the <strong>rotation</strong> and then translate back <strong>afterwards w</strong>hich would probably work, in this case since it’s a simple transformation case - but do you understand why it would work and how? Let’s find out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c9c493781ed057304fe7ccfee2f8099/href">https://medium.com/media/9c9c493781ed057304fe7ccfee2f8099/href</a></iframe><h3>How does it really work</h3><p>This is where William explains it really well. I’ve used his example in the following images.</p><p>On the top right of the image you see the steps we want to do, but as we said before, the rotation is being done on the center of the card, so in this example we want to move the center of the rotation to the left of the card.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*R3HJ52eDo_VJCHwrnO88nA.png" /></figure><p>We break these three instructions one by one and understand what happens. Make sure you notice the axis system.</p><p>First, we translate on the x axis in order to change the center of the rotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*zhOQf-I5gBwGkByYwnMMlg.png" /><figcaption>Step 1: translate X to the left</figcaption></figure><p>Second, we do the rotate the cards.</p><p>Third, we translate the card back in the opposite length of the initial translate.</p><p>You’d think the following image is what happening but <strong>no , almost 😎.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*HH2eWtxVL_hixK42cbO_Uw.png" /><figcaption>Step 2: rotate, Step 3: translate X</figcaption></figure><p><strong>When you apply a rotation, the axis changes</strong> so what really happens is the axis rotates as well and once we translate, we translate on the <strong>updated coordinate system</strong> which is now rotated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*j_BrFeV_RnoT6gRNo_dCMA.png" /><figcaption>Step 3 — the right way: translate on x axis after applying rotate</figcaption></figure><p>Notice that the <strong>axis coordinate system is rotated</strong> as well, causing the next <strong>translate </strong>property to be applied on the updated coordinate system.</p><h3>Moving Forward</h3><p>This basic principle should come in handy where you need to implement more complex transforms. If you understand the primitive transforms (translate, rotate, scale) and understand that their order in the array matters, you can apply more complex mathematics to create more complex animations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*NteDdLfVYnjm1xD_CJ4KoQ.png" /><figcaption>Don’t be scared — it’s all about Math</figcaption></figure><p>What do I mean by that? 🧐</p><p>There are 3 dimensions that we can rotate an object in the real world. The axes are X, Y, Z. But when you look at React Native, the API does not provide you with translateZ style, how would you implement that?</p><p>We do have the <strong><em>perspective </em></strong>style prop. This property sets the camera location allowing us to see more of the view.</p><p>Using some mathematics trigonometry William came out with a <a href="https://wcandillon.github.io/react-native-redash-v1-docs/transformations#translatez">translate function</a> that was based off “<a href="https://en.wikipedia.org/wiki/3D_projection#Weak_perspective_projection">weak perspective projection</a>”.</p><blockquote>Convert a translateZ transformation into a scale transformation. This function is based on <a href="https://en.wikipedia.org/wiki/3D_projection#Weak_perspective_projection">weak perspective projection</a> and is not appropriate for every 3D transformations.</blockquote><p>We can apply it to create translateZ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8kHd7AAvIgJPKjedmgTaw.png" /><figcaption>translate z based off <a href="https://medium.com/u/4bdbd6b3a30a">William Candillon</a> video</figcaption></figure><p>So we can use it as such</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d196fcc1180e7855b688ceea6ce8a0a/href">https://medium.com/media/6d196fcc1180e7855b688ceea6ce8a0a/href</a></iframe><p>Keep in mind that usually we want to use it with some animations. If you are using <em>react-native-reanimated </em>package, you can use William Candillon’s package named <a href="https://github.com/wcandillon/react-native-redash"><strong><em>react-native-redash</em></strong></a> which is a collection of utility functions for <em>react-native-reanimated</em>. There he provides us with <strong>translateZ </strong>using react-native-reanimated under the hood.</p><h3>Final words</h3><p>Hope you got some tips from this post about transforms.</p><p>You can check out my other posts about <a href="https://medium.com/@zmtmaster/why-i-use-react-spring-daf04b00c757">Why do I use React Spring</a> for less complex animations running on the JS thread &amp; Creating <a href="https://medium.com/swlh/custom-tab-navigator-using-react-navigation-svg-b659b395a7c4">Custom Tab Navigator using React Navigation &amp; SVG</a> if you are interested.</p><p>I really recommend you start following the “<a href="https://www.youtube.com/channel/UC806fwFWpiLQV5y-qifzHnA"><em>Can it be done in React Native</em></a>” series where you can learn a lot of cool concepts by watching William re-creates popular applications.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FReImZejkBnqYU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FReImZejkBnqYU%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FReImZejkBnqYU%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/c540ef65a6306b0db981b29411155687/href">https://medium.com/media/c540ef65a6306b0db981b29411155687/href</a></iframe><p>Here is a link to the repository.</p><p><a href="https://github.com/zmtmaster/react-native-transforms">zmtmaster/react-native-transforms</a></p><p>Until next time,</p><p>Stay safe 😷✌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0f4995ebdb6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-heart-of-react-native-transform-e0f4995ebdb6">The Heart of React Native Transform</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Tab Navigator Using React Navigation & SVG]]></title>
            <link>https://medium.com/swlh/custom-tab-navigator-using-react-navigation-svg-b659b395a7c4?source=rss-7a11a2eb8325------2</link>
            <guid isPermaLink="false">https://medium.com/p/b659b395a7c4</guid>
            <category><![CDATA[tab-navigator]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Matan Kastel]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 20:13:55 GMT</pubDate>
            <atom:updated>2020-09-21T18:00:14.299Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve recently faced an issue at work where I needed to create a custom tab navigator. I would like to give a shout out to <a href="https://medium.com/u/4bdbd6b3a30a">William Candillon</a>. He has a great YouTube series called “<strong><em>Can It Be Done In React Native</em></strong>” where he demonstrates complex application animation using React Native.</p><p>Last year, he did a <a href="https://www.youtube.com/watch?v=6LsLgHeX500">live challenge</a> in which he had some parts of what I needed. I needed to create some similar things but without any animation for starters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gVMzqim9XJqcn6d4sRhcZw.gif" /></figure><h3>Introduction</h3><p>I am going to showcase the following custom tab bar. I’d like to point out that I use D3 &amp; React Navigation. If you want to read my post about using D3 &amp; React you can do so <a href="https://medium.com/@zmtmaster/react-d3-68f603a7021d">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZxzJ91nz1gd1m4rrJQ5ZA.png" /><figcaption><strong>UX -&gt; UI -&gt; DX</strong></figcaption></figure><h3>The Set Up</h3><p>We will be using <em>d3-shape</em> and <em>react-native-svg </em>packages. We are also going to use the React-Navigation package for the routing.</p><p>We’ll start by defining some routes to our application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96b42e8145df4bf94d0ecd4d2d5014e8/href">https://medium.com/media/96b42e8145df4bf94d0ecd4d2d5014e8/href</a></iframe><p>Note that we set the <em>tabBarVisible </em>to <em>false </em>to hide the provided BottomTabNavigator since we are going to make our own <strong><em>&lt;TabsUI /&gt;</em></strong> component. This will allow us to have complete control over animations, shapes, icons etc.</p><h3>The &lt;TabsUI/&gt;</h3><p>In order to achieve the required result .We will have few components, all working together.</p><p>We start by defining the shape using d3-shape. We will create a line by using a line generator. We’ll divide our shape to 3 parts: left, center and right. We’ll start off with the easy parts, left and right. We know the <em>tabWidth</em> is based on the screen width, divided by the number of tabs we want to place. Since we are using SVG coordinate system the [0,0] point of the shape is top left corner. Keep in mind that we will use a constant value to store the tab bar height.</p><p>For the <strong>left</strong> part we define a line going from [0,0] to about the center [tabWidth * 2, 0]. For the <strong>right</strong> part we start a little bit after the center tab [tabWidth * 3, 0] going to the end [width, 0] then we close the shape by going down to [width, height] and back to start [0, height] closing the shape.</p><p>For the <strong>center </strong>part we will create a V-like shape by providing the values, going a little bit continuing the x-axis while going down up to half of the height, then taking up the values on the y-axis to 0 again while going continuing the path on the x-axis.</p><p>There are many curve functions, that can help us smoothing the connection between the points. We’ll use a curve function from d3 here are some examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*z40KEU0sHbVJSrivVYzsAQ.png" /><figcaption>If you wish you can experiment with this nice <a href="http://bl.ocks.org/d3indepth/b6d4845973089bc1012dec1674d3aff8">example</a>.</figcaption></figure><p>Here is the code for the &lt;<em>TabShape /&gt; </em>Component using the described above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/381ef58ca464765739f113038684665e/href">https://medium.com/media/381ef58ca464765739f113038684665e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*gD8mK-e6z4zJCCPftLXOqw.png" /><figcaption>&lt;TabShape /&gt;</figcaption></figure><p>Now that we have a background all we have to do is overlay the icon for the navigation on top and we are done.</p><p>We’ll create a <strong><em>&lt;TabsHandler&gt;</em></strong> component for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/860d1d07e46c5cf9115aca6149bdd78d/href">https://medium.com/media/860d1d07e46c5cf9115aca6149bdd78d/href</a></iframe><p>Notice that for the middle larger icon we do not render the tab SVG with a text and use Logo component. This logo component will be drawn on center, instead of the middle tab position. It would be a separated component so we can add a opening animation if we want to, later.</p><h3>Put it all together</h3><p>We now combine both of the components and lay them one over the other.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45ef7fe5b546db8016b9ed96a9e9cc64/href">https://medium.com/media/45ef7fe5b546db8016b9ed96a9e9cc64/href</a></iframe><h3>That’s it!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*7ipsevazCA_6u0dXRt4DyQ.png" /></figure><p>We now have a custom tab navigator. If we need to animate it - we have a full control over the shapes. This is while having the functional navigation working.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fd5w5tJjb0NaGBaVSS2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Flego-ninjago-d5w5tJjb0NaGBaVSS2&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fd5w5tJjb0NaGBaVSS2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/440297cc7d2b0dd7f8ab462dd0a6132a/href">https://medium.com/media/440297cc7d2b0dd7f8ab462dd0a6132a/href</a></iframe><p><strong>We used D3 for the complex shapes but kept the logic for the tabs separated. </strong>This is decoupling, while working in a team, is very recommended in cases where not all team members understand D3. While one team member handles the animations &amp; creating the complex shapes of the tab bars, the other members can do the standard navigation functionality.</p><p>It is very important to know that I had a case where I needed to control the rendering completely. I needed to create some overlays that I could not done otherwise. If you don’t care for this and only want to render a custom tab you can use <em>&lt;Tabs.Navigator/&gt;</em> prop named <em>tabBar</em> where you can provide it with a render function that returns our updated <em>&lt;TabUI /&gt;</em> component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92c037584c10ba3a4c3bfdc1195f4476/href">https://medium.com/media/92c037584c10ba3a4c3bfdc1195f4476/href</a></iframe><p>You can find a working demo here, but keep in mind that it was slightly changed from the code snippets shown on the post. It is posted so you can have a general idea about routing.</p><p><a href="https://github.com/zmtmaster/react-native-svg-tabs">zmtmaster/react-native-svg-tabs</a></p><p>If you like this post, you are more than welcome to check my other posts about <a href="https://medium.com/@zmtmaster/react-d3-68f603a7021d">React &amp; D3</a>, or <a href="https://medium.com/@zmtmaster/why-i-use-react-spring-daf04b00c757">Why I use React Spring</a>.</p><p>If you have any questions you can contact me on <a href="https://twitter.com/MatanKastel">twitter</a> 🐦. I will try to get back to you.</p><p>Stay safe! ✌😷</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b659b395a7c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/custom-tab-navigator-using-react-navigation-svg-b659b395a7c4">Custom Tab Navigator Using React Navigation &amp; SVG</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I use React-Spring]]></title>
            <link>https://medium.com/swlh/why-i-use-react-spring-daf04b00c757?source=rss-7a11a2eb8325------2</link>
            <guid isPermaLink="false">https://medium.com/p/daf04b00c757</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-spring]]></category>
            <dc:creator><![CDATA[Matan Kastel]]></dc:creator>
            <pubDate>Tue, 07 Jul 2020 13:11:34 GMT</pubDate>
            <atom:updated>2020-11-06T09:02:58.995Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will be looking at an outstanding library called <a href="https://www.react-spring.io/"><strong>React Spring</strong></a> which makes it super easy to control component based animations. And yes, before you ask, it does support hooks which can turn any data into animated data, with a single line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*UaiztkX2asBvPv-K6oau_A.gif" /></figure><h3>What is React Spring?</h3><p>The whole point of using React Spring is to give you the upper hand in animations by providing you with a <strong>better experience</strong> as well as faster delivery with incredible performance.</p><p>Quotes from the <a href="https://www.react-spring.io/#intro-demos:~:text=react%2Dspring%20is%20a%20spring%2Dphysics%20based%20animation,cast%20your%20ideas%20into%20moving%20interfaces.">introduction</a> section on the official website:</p><blockquote><em>r</em>eact-spring is a spring-<strong>physics </strong>based animation library that should cover most of your UI related animation needs. It gives you tools flexible enough to confidently cast your ideas into moving interfaces.</blockquote><blockquote>It inherits animated’s powerful interpolations and <strong>performance</strong>, as well as react-motion’s ease of use. But while <strong>animated is mostly imperative </strong>and react-motion <strong>mostly declarative</strong>, <strong>react-spring bridges both</strong>. You will be surprised how easy static data is cast into motion with small, explicit utility functions that don’t necessarily affect how you form your views.</blockquote><p>If you want to understand about the differences of imperative vs declarative programming in this <a href="https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2">link</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fr5qmj8m6lq&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fr5qmj8m6lq&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fr5qmj8m6lq%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/dac1e0783daaaf71100377dd40a2b4d9/href">https://medium.com/media/dac1e0783daaaf71100377dd40a2b4d9/href</a></iframe><p>Using physics we no longer need to consider <strong>Duration</strong> or <strong>Easing Curves. </strong>Instead, we focus on actual physical properties. React Spring heavily uses this logic on all its animations which is why it is said to work like any other real-world property.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*px3RsH_1CRLd8XkGEihwFQ.jpeg" /></figure><p><em>Confused</em>? Imagine you are throwing a ball vertically downwards from a building, the ball <strong>won’t ask you about the time</strong> after which it should hit the bottom, right? Rather, we would let physics do the talking. <strong>Same applies to React Spring</strong>.</p><h3>The Use Case</h3><p>React Spring comes with some utility functions. Let’s see a use case that demonstrates how simple is it to use. Let’s use a real life example I have recently faced.</p><p>Assume we have a React Native project and in it we want to render a menu with items. Each item once the item is rendered, it should animate its’ entrance from one direction to another while on the same time the opacity changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*LxNqECHCghYyGKVH7lv87g.gif" /><figcaption>Animated Menu Items</figcaption></figure><p>Before we start using React Spring, let’s first use React Native.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0d28ef30c53141c1aab6af407f6b93d/href">https://medium.com/media/f0d28ef30c53141c1aab6af407f6b93d/href</a></iframe><p>We want to be performant - so, we will use <em>useNativeDriver </em>property for the animation, which tells React Native to handle outside the JS thread.</p><p>Now we face couple of issues</p><ul><li><strong>Animation properties</strong>. We are not able to animate the width property. We have to stick to the abilities provided by <em>Animated.View</em> which are Transform based (Scale, Translate, Rotate etc) and not Shape based (Width, Height etc). Note that in this simple example it’s still fine, we can certainty use translate-x to animate the desired effect. However, when we face a more complex animations it might not be the case.</li><li><strong>Developer Experience (DX)</strong>. While the User Experience (UX) is simple and elegant, by using the native animation code, we add more complex code which makes it hard to read and understand.</li></ul><h3><strong>React Spring to the rescue</strong></h3><p>Now we re-write out Item component using React Spring. Let’s see how it helps us resolve the issues mentioned earlier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bea67f95ed34cbd9db14c83884cd592/href">https://medium.com/media/7bea67f95ed34cbd9db14c83884cd592/href</a></iframe><p>We can now examine the differences:</p><h4><strong>1. Developer Experience (DX)</strong>.</h4><p>See ho much cleaner the API is? Even without knowing how useSpring hook works and what it returns you can easily read the component code and guess.</p><p>One way of working with useSpring hook is to provide it with an object, while the other way is to provide it with a function. Based on the input provided to useSpring, the returned value is provided for us to use.</p><p>Let’s see an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78460bc21dbd628039b9b8e9d5a35a5d/href">https://medium.com/media/78460bc21dbd628039b9b8e9d5a35a5d/href</a></iframe><p>Back to the Item component, we do not care for the duration of the animation, we don’t care of when it starts, we just want to it to animate &amp; get the job done. So in this case we use the first way pattern.</p><h4><strong>2. Animation properties</strong></h4><p>Notice that now we are not bound the properties supported on Animated from React Native (scale, translate, etc). We can animate any property of style we want (width, left, etc) and let React-Spring handle it for us.</p><h3>Cross Platform</h3><p><em>Eh? What do you mean by that?</em></p><p>I don’t mean iOS or Android, well yes, it will work on both, that’s not it.</p><p>Well it turns out that if we read <em>Item Component </em>the code again, we are not actually bound to the environment. Yes, we do use View &amp; TouchableOpacity components but regarding the animation part, it does not involve any environment bounding.</p><p>Ideally, we may use the same code for the animation with no changes to it at all. The only changes required are for another target environment are the nodes used. See the following example that uses the DOM with the same animations we defined earlier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50cb4094f982adf922bbcb1d8c203c7f/href">https://medium.com/media/50cb4094f982adf922bbcb1d8c203c7f/href</a></iframe><p>Since react-spring uses dependency injections internally, it can compile to multiple platforms.</p><ul><li><strong>Web </strong>(react-spring)</li><li><strong>React Native</strong> (react-spring/native)</li><li><strong>Canvas </strong>(react-spring/konva) [HTML5 Canvas]</li><li><strong>WebGL </strong>(react-spring/three) [Works great with <a href="https://github.com/react-spring/react-three-fiber">react-three-fiber</a>, that uses ThreeJS with React]</li></ul><p>This way if we re-use the animations logic on different targets.</p><h3>That’s it</h3><p>I want you to keep in mind that some more complex animations would be easier to implement using react-native-reanimated package. However if you are just looking for a small animation react-spring is a great solution.</p><p>All &amp; all I hope I’ve convinced you to consider using react-spring in the feature. You can read more about it on their <a href="https://www.react-spring.io/docs/hooks/examples">website</a>. They have a lot of complex examples for you to explore</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0HlSFMhjVbgyA32U%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0HlSFMhjVbgyA32U%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl0HlSFMhjVbgyA32U%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="290" frameborder="0" scrolling="no"><a href="https://medium.com/media/22d0d90fe0fbfe149e458e081683475c/href">https://medium.com/media/22d0d90fe0fbfe149e458e081683475c/href</a></iframe><p>Thanks for reading✌️. Stay safe😷!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=daf04b00c757" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/why-i-use-react-spring-daf04b00c757">Why I use React-Spring</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React & D3]]></title>
            <link>https://medium.com/swlh/react-d3-68f603a7021d?source=rss-7a11a2eb8325------2</link>
            <guid isPermaLink="false">https://medium.com/p/68f603a7021d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[d3]]></category>
            <category><![CDATA[graph]]></category>
            <dc:creator><![CDATA[Matan Kastel]]></dc:creator>
            <pubDate>Sun, 21 Jun 2020 12:01:57 GMT</pubDate>
            <atom:updated>2020-06-24T07:46:29.613Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Before we start, I recommend watching </strong><a href="https://sxywu.com/"><strong>Shirley Wu</strong></a><strong>, an experienced developer in the field of data visualization, explains the basics of SVG &amp; D3</strong> (<a href="https://youtu.be/rQroxWLZiCo?t=1504">link</a>).</p><p><em>The final code example for this article can be found on this </em><a href="https://github.com/zmtmaster/react-d3-graph"><em>repository</em></a><em>.</em></p><h3>The Different Ways</h3><p>There are several ways to figure out how React and D3 can work together.</p><p>One method is referred to as “hand off” which basically means we tell React to render the DOM elements and from that point we use D3’s methods to handle all the manipulations required.</p><p>Another method is to have D3 do the calculations needed based on the data and use React to handle the DOM manipulation.</p><p>In this article I am going to use the later approach.</p><h3>The Approach</h3><p>I am going to use the D3 methods to help with the calculations and with binding the events needed to the DOM. However, I am still going to rely on our good old friend React for handling all the DOM manipulations needed and the general application rendering. We will just use React awesome props &amp; hooks mechanism to our advantage.</p><h3>Introduction</h3><p>I will be building a simple chart. The Y axis represents the amount of a certain product while the X axis represents a month.</p><ul><li>The chart is interactive by the user</li><li>It displays an average line and it has zooming feature.</li><li>A fade animation occurs once the data is ready to be displayed.</li><li>The user can also hover over a single bar causing color opacity to be changed in order to emphasize focus over the column.</li><li>The user can always click on a bar to show the data below it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*bpmW3e-norYTddxI6wpLiA.gif" /></figure><h3>The data</h3><p>For this simple example we are going to assume that the data we receive is going to be minimal. You can always have more fields to the data as needed. The structure is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b7f14aec8d3756383ab0643f4095ec6/href">https://medium.com/media/2b7f14aec8d3756383ab0643f4095ec6/href</a></iframe><h3>The code</h3><p><em>Let’s assume we have size constants we want to follow for padding, maxWidth and maxHeight.</em></p><p>First we define a xScale &amp; a yScale. Scales just take inputs (domain) and scales them out to another output (range). There are many types of scales and here I use the linear scale (other scales could be scaleTime, scaleSequential etc).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c8782dbe736046f507eb1bf9593e5fb/href">https://medium.com/media/0c8782dbe736046f507eb1bf9593e5fb/href</a></iframe><p>Then we need to create and use a function that receives the data elements and scales as arguments and returns an object. That object will be the props values for a rendered SVG rectangle (x, y, height etc.).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39f7cd133842eb441fd658933b5f4235/href">https://medium.com/media/39f7cd133842eb441fd658933b5f4235/href</a></iframe><p>Now that we have scales and rectangles data, we set the stage for the render function. We create a bar component, that component will render a SVG rectangle with the animation we want.</p><p>In this example I used <a href="https://www.react-spring.io/">react-spring</a> to manage the state changes needed for transition &amp; fade effects (You can also use native CSS transitions as needed). The events we want to use (onClick etc) are defined here as regular React props.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/852553c6c8b67917ca227fc297208419/href">https://medium.com/media/852553c6c8b67917ca227fc297208419/href</a></iframe><p>Next we create the render function that will create the graph.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/603506dd8cd411ce07057c1c40b42d56/href">https://medium.com/media/603506dd8cd411ce07057c1c40b42d56/href</a></iframe><h3>The final touches</h3><p>At this point we have a functional graph that is based on the data provided by the props with hovering and clicking interactions. Clap Clap!!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Funripethoroughhalibut&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Funripethoroughhalibut-looney-tunes-warner-bros-space-jam&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FUnripeThoroughHalibut-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="960" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1789444ece35534a1438bbf71aa6027/href">https://medium.com/media/b1789444ece35534a1438bbf71aa6027/href</a></iframe><h3>Adding average line</h3><p>We will now add more features to our graph: zoom support &amp; average line to be displayed over the bars. These are some examples but you can create any behavior you would like using the help of D3 functions.</p><p>We’ll start with the simple average line. We will add a useState statement to hold the d attribute for a SVG path which the render function can use to render the path. The logic will be implemented on the effect we created previously.</p><p>Please note that this way of calculating the d attribute of SVG paths can be implemented for more complex graphs based on the data and using the scales.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/371e994c361f24300d039cc1576736f0/href">https://medium.com/media/371e994c361f24300d039cc1576736f0/href</a></iframe><h3>Adding zoom support</h3><p>Now that we added the average line, we can add zooming support based on D3 zooming behavior. The key part here is that D3 <em>event </em>contains the transform object which has a rescale function. Once we provide the original scale to the transformed scale we can re-calculate the bars based on the new <em>updatedScale</em>. Same goes for the x-axis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d14a090a84dbceb4ed7b822a083cecb/href">https://medium.com/media/2d14a090a84dbceb4ed7b822a083cecb/href</a></iframe><h3>That’s it</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2Fdesertedwhitedotterel&amp;display_name=Gfycat&amp;url=https%3A%2F%2Fgfycat.com%2Fdesertedwhitedotterel-lunnietines&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FDesertedWhiteDotterel-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="560" height="320" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e7aec9bc0b48a40a52971105e64f851/href">https://medium.com/media/4e7aec9bc0b48a40a52971105e64f851/href</a></iframe><p>Thanks for reading.</p><p>By reading I hope you feel more comfortable with this scary topic name D3, and can use it to your advantage in your React applications.</p><p>The full <a href="https://github.com/zmtmaster/react-d3-graph">repository</a> can be found here. If you need to use this in React Native there is this <a href="https://github.com/zmtmaster/react-native-d3-graph">repository</a>.</p><p><a href="https://github.com/zmtmaster/react-d3-graph">zmtmaster/react-d3-graph</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68f603a7021d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/react-d3-68f603a7021d">React &amp; D3</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a React Context Menu That Close When Clicking Outside Using Hooks]]></title>
            <link>https://zmtmaster.medium.com/create-a-react-context-menu-that-close-when-clicking-outside-using-hooks-ccfa8f0342b3?source=rss-7a11a2eb8325------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccfa8f0342b3</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[context-menus]]></category>
            <category><![CDATA[hooks]]></category>
            <dc:creator><![CDATA[Matan Kastel]]></dc:creator>
            <pubDate>Mon, 25 May 2020 15:59:44 GMT</pubDate>
            <atom:updated>2020-05-25T16:02:13.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create a React Context Menu That Closes When Clicking Outside</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*E7VoNYSFeQXEeZicfYr8xQ.png" /></figure><h3>The setup</h3><p>The first thing we would like to implement is a custom hook called <strong>useOutside</strong>, which handles the binding of the mouse click event. In this hook we would implement the logic to find out if the click has occurred outside the required reference or within the requested area thus opening the menu.</p><pre>import { useEffect } from &#39;react&#39;;<br><br>function useOutside(containerRef, contextMenuRef, callback = () =&gt; {}) {<br>  /**<br>   * if clicked on outside of element<br>   */<br>  function handleClickOutside(event) {<br>    if (containerRef?.current?.contains(event.target) &amp;&amp;<br>     !contextMenuRef?.current?.contains(event.target)<br>    ) {<br>      callback();<br>    }<br>  }<br><br>  useEffect(() =&gt; {<br>    // Bind the event listener<br>    document.addEventListener(&#39;mousedown&#39;, handleClickOutside);<br><br>    return () =&gt; {<br>      // Unbind the event listener on clean up<br>      document.removeEventListener(&#39;mousedown&#39;, handleClickOutside);<br>    };<br>  });<br>}<br><br>export default useOutside;</pre><p>Now that we have this <strong>useOutside </strong>hook, we can move to the next part of creating a <strong>OutsideContext</strong>. That context will be used later to inject the container reference.</p><pre>import { createContext } from &#39;react&#39;;<br><br>const OutsideContext = createContext(null);<br><br>export default OutsideContext;</pre><p>The next step is the actual Context Menu React component that uses the <strong>useOutside </strong>&amp; <strong>OutsideContext </strong>we’ve created before. We will be using some styled components to make the required styling but you can use any CSS you’d like. Our <strong>ContextMenu </strong>Component has some props. The left and top are used to position the menu, the ContextMenu component renders the children which allows to dynamically set the children.</p><pre>import React, { useContext, useRef } from &#39;react&#39;;<br>import PropTypes from &#39;prop-types&#39;;<br>import styled from &#39;styled-components&#39;;<br><br>import { OutsideContext } from &#39;app/contexts&#39;;<br>import { useOutside } from &#39;app/hooks&#39;;<br><br>const ContextMenuContainer = styled.div`<br>  position: absolute;<br>  z-index: 1;<br><br>  ${(props) =&gt; `<br>    top: ${props.top || 0}px;<br>    left: ${props.left || 0}px;<br>  `}<br>`;<br><br>function ContextMenu({<br>  children, top, left, close,<br>}) {<br>  const outerRef = useContext(OutsideContext);<br>  const contextMenuRef = useRef(null);<br><br>  useOutside(outerRef, contextMenuRef, close);<br><br>  return (<br>    &lt;ContextMenuContainer<br>      ref={ contextMenuRef }<br>      top={ top }<br>      left={ left }<br>    &gt;<br>      {children}<br>    &lt;/ContextMenuContainer&gt;<br>  );<br>}<br><br>ContextMenu.propTypes = {<br>  children: PropTypes.node,<br>  top: PropTypes.number,<br>  left: PropTypes.number,<br>  close: PropTypes.func,<br>};<br><br>ContextMenu.defaultProps = {<br>  children: null,<br>  top: 0,<br>  left: 0,<br>  close: () =&gt; {},<br>};<br><br>export default ContextMenu;</pre><p>We now need to handle setting up the context provider so we could have the <strong><em>outerRef</em> </strong>constant set. We can do so by creating a div in the top level. The following <em>div</em> allows us to compare the refs with the contain function used before at <strong>useOutside</strong>.</p><p>This is used in the root App component bu of course can be implemented anywhere in the application.</p><pre>import React, { useRef } from &#39;react&#39;;<br>import MyComponent from &#39;app/components/my-component&#39;;<br><br>function App() {<br> const containerRef = useRef(null);<br><br>  return (<br>    &lt;div ref={ containerRef }&gt;<br>      &lt;OutsideContext.Provider value={ containerRef }&gt;<br>        &lt;MyComponent /&gt;<br>      &lt;/&lt;OutsideContext.Provider&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>We are almost there, hang in there only a small phase to go.</p><h3>Making it work</h3><p>Now, we just need to render the ContextMenu component. We’ll set up some useState hooks for the component state along some functions that will implement the logic we want.</p><pre>import React, { useState, useCallback } from &#39;react&#39;;<br><br>export default function MyComponent() {<br>  const [contextMenuProperties, setContextMenuProperties] = useState({<br>    contextMenuVisibility: false,<br>    contextMenuTop: 0,<br>    contextMenuLeft: 0,<br>  });<br><br>  const onClose = useCallback(() =&gt; {<br>    setContextMenuProperties({<br>      contextMenuVisibility: false,<br>      contextMenuTop: 0,<br>      contextMenuLeft: 0,<br>    });<br>  }, [setContextMenuProperties]);<br><br>  const onRightClick = useCallback(({ event, selection }) =&gt; {<br>    setContextMenuProperties({<br>      contextMenuVisibility: true,<br>      contextMenuTop: event.clientY,<br>      contextMenuLeft: event.clientX,<br>    });<br>  }, [setContextMenuProperties]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;span&gt; some content &lt;/span&gt;<br>      {<br>        contextMenuVisibility &amp;&amp; (<br>          &lt;ContextMenuContainer<br>            top={ contextMenuTop }<br>            left={ contextMenuLeft }<br>            close={ onClose }<br>          &gt;<br>            &lt;div onClick={ onClose }&gt; Item 1 &lt;/div&gt;<br>            &lt;div onClick={ onClose }&gt; Item 2 &lt;/div&gt;<br>          &lt;/ContextMenuContainer&gt;<br>        )<br>      }<br>      &lt;div onContextMenu={onRightClick}&gt; some more content that displays the menu &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>That’s it! We now have a dynamic content menu component that is reusable across the application.</p><p>The code source for the examples above can be found <a href="https://github.com/zmtmaster/context-menu">here</a>, along side a running demo <a href="https://context-menu.herokuapp.com/">here</a>.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccfa8f0342b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>