<?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 Reginald Johnson on Medium]]></title>
        <description><![CDATA[Stories by Reginald Johnson on Medium]]></description>
        <link>https://medium.com/@reginald.johnson?source=rss-a7da9e7dc419------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1yM3mXERk3SnRW2o_hh_Kg.jpeg</url>
            <title>Stories by Reginald Johnson on Medium</title>
            <link>https://medium.com/@reginald.johnson?source=rss-a7da9e7dc419------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 08:52:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reginald.johnson/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[Sharing Code Between React Web and React Native Applications]]></title>
            <link>https://medium.com/react-native-training/sharing-code-between-react-web-and-react-native-applications-7f451af26378?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f451af26378</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Sun, 21 Oct 2018 13:57:58 GMT</pubDate>
            <atom:updated>2021-10-15T14:04:03.985Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using Render Props to Share Logic Across Platforms in React</h4><p>This story details a process that was created before the introduction of React hooks. Hooks and functional components greatly simplify sharing code, and that process is documented here: <a href="https://www.braingu.com/blog/share-react-component-logic">https://www.braingu.com/blog/share-react-component-logic</a></p><p>However, this process is still relevant for class components, or if you just want to learn more about using Higher-Order Components and render props.</p><h4>Introduction</h4><p>It can be desirable for a consumer facing product to exist on the web as well as on mobile. For example, many food delivery applications exist as both web and mobile applications.</p><p>These applications may even share significant functionality. In the before mentioned example, both the web and the mobile applications would let you place a food order. In fact, they may both perform the same business logic of gathering the order data and sending it to the same backend servers for processing. On the other hand, the two platforms may do some things differently. For example, the mobile application might request the user’s location using a platform specific API, while the web app would use the HTML5 <a href="https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API">Geolocation API</a>.</p><p>Also, lets not <a href="https://www.dictionary.com/browse/can-t-see-the-forest-for-the-trees">miss the forest for the trees here</a>. Occasionally using different APIs to accomplish the same functionality isn’t even the primary difference between the platforms. UI presentation and the flow of the UX are a very significant difference.</p><p>However, API and UI/UX differences don’t mean that you can’t share code between the platforms. The React mantra of <a href="https://reactjs.org/blog/2015/03/26/introducing-react-native.html">Learn Once Write Anywhere</a> still holds weight. Using the Render Props pattern to keep our platform specific primitive components like &lt;Views&gt; and &lt;divs&gt; away from component business logic enables significant code sharing across platforms.</p><h4>Purpose</h4><p>The purpose of this article is straight forward. In it, I will present a technique that allows you to share most of your code across between React Web and React Native applications.</p><h4>Design</h4><p><strong>Code Sharing Techniques</strong></p><p>First, let me begin by stating that there are several approaches to sharing code across React platforms. One way is to separate business logic into NPM packages to be imported by individual components. Another method using an SDK is covered in this article <a href="https://hackernoon.com/share-code-between-react-and-react-native-using-sdk-85c2dab552f8">here</a>.</p><p>Another technique is to create a JavaScript class that extended React.Component This parent class would contain all of the the components; non UI related code. The parent can then be extended by a child that contains the platform specific render method, and would inherit all the functionality of the parent.</p><p>The class technique could be somewhat mimicked using the RenderProps pattern. I’m not going to do a deep dive of Render Props (subsequently refereed to as RPs). To be frank, it took me a while to discover my use case for them. It wasn’t until I ran across some good explanations and examples that I realized how helpful they could be (I recommend <a href="https://www.youtube.com/watch?v=3ic-f1AYLWU">Scott Tolinski’s series of videos on the subject</a>)</p><p>Finally, there is no reason you can’t just put the business logic in separate functions to be imported and used by components. For example, all the API calls could exist in a file called APIUtilities.js. Then a component could import and use the methods contained in that file.</p><p><strong>The Case for RenderProps</strong></p><p>For my use case I wanted to avoid creating and maintaining a large number of NPM modules. In fact, one of my goals was to keep things as simple as possible. Both the class and RP method would satisfy my purposes. In the end, I settled on using RPs for the following reasons.</p><ol><li>It didn’t require maintenance of additional NPM packages</li><li>RPs have access to React life cycle methods, and I could share those methods across platforms</li><li>It was time for me to knuckle down and learn the RP pattern</li></ol><p><strong>Planning</strong></p><p>I would create separate folders for each platform as well as an additional folder for any shared items, and then importing and exporting functionality as needed.</p><p>The platform folders could contain platform specific code. The shared folder would contain any code that would be shared across the platforms. This is where the Render Prop components and my Redux store would live.</p><p>What made RPs useful for me was that it enabled separation of all the presentational aspects of a component from its business logic by passing the UI portion of the component as a property to a “wrapping” component. I’ll refer to this wrapping component as the Render Prop Component or RPC throughout the rest of this article.</p><p>My plan was to build RPCs to do all the component’s business logic and then pass it either a mobile or web UI component for rendering. Both UI components would possess the same “hooks” to interact with the logic the RPC contained, and would only (almost) differ in what they showed the user on their screen.</p><p>In addition to the RPCs the shared folder would also contain my applications Redux store. Since the store would be mostly the same across platforms, it made sense to keep it there.</p><p>Finally, I’d keep other shared utility functions in shared also.</p><h4>Implementation</h4><p>I began with a folder structure that would support my plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*ZqUoFl4uqwcYMmhwVcObcg.png" /><figcaption>A folder for each platform (mobile and web) as well as shared and media folders</figcaption></figure><p>Inside the web folder I created a new <a href="https://www.gatsbyjs.org/">GatsbyJS</a> project. Similarly, inside the mobile folder I created a new <a href="https://expo.io/">Expo</a> project. Both of these projects do a fine job of describing how to get up and running, so I’m not going to go over those details in this article.</p><p><strong>Configuration</strong></p><p>Both projects would have to reach into the shared folder, and needed a little “help” to make that happen. These issues are related to the React metro bundler’s ability to find files, and is discussed <a href="https://github.com/facebook/metro/issues/7">here</a>. An additional discussion pertaining to React Native version 0.57 can be found <a href="https://github.com/facebook/metro/issues/7">here</a>.</p><p>For the web application which was a GatsbyJS project I had to include the following code in the gatsby-node.js file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e205f218babcb566676d987805f032a/href">https://medium.com/media/0e205f218babcb566676d987805f032a/href</a></iframe><p>For the mobile application built using Expo I created a rn-cli.config.js file containing the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b946a4b7ac3ef7091107ad2d009780a/href">https://medium.com/media/2b946a4b7ac3ef7091107ad2d009780a/href</a></iframe><p>And then added the following line to the “packagerOpts” section of my app.json file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b9d6b80dfa7445e246bc5c4b67a63ae/href">https://medium.com/media/5b9d6b80dfa7445e246bc5c4b67a63ae/href</a></iframe><p><strong>Building Components</strong></p><p>For this use case, there are several distinct elements of a component.</p><ol><li>Platform specific wrapping component</li><li>Platform specific code</li><li>Common RPC</li><li>Platform specific render functions</li></ol><p>Conceptually, they can be though of according to the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*WjBI-U65uj2MRr0p2SHMZg.png" /><figcaption>Models of React Web and React Native components sharing code via a common Render Prop</figcaption></figure><p>Each element is described below.</p><p><strong><em>The Wrapping Component</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*Aau41IaOqFQ5T4Ribk3Itg.png" /><figcaption>Platform specific wrapping components</figcaption></figure><ol><li>The completed component wraps everything in a package suitable for use as a component. It is what we think of as a React component and is exported from its file and imported by other components as required.</li></ol><p><strong><em>Platform Specific Code</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*fUNh15eza_737E-Xu4ASNQ.png" /><figcaption>Each platform can contain platform specific logic in the component</figcaption></figure><p>2. The wrapping component contains any web specific code. For example, it may include a function that gets the user’s location. Different platforms have different APIs to access user location. These platform specific methods exist at this level.</p><p>It’s important to realize that just because this code is platform specific, it can still have interact with the common code in the RPC. Methods at this level can receive the renderProps as an argument which then gives them access to RPC methods. An alternative is to hoist renderProps to the wrapping component level shown in item number one using this.renderProps.</p><p>It can also include any platform specific lifecycle code.</p><p><strong><em>Common Render Prop</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*HSinduBDm53te-ggm1oDYg.png" /><figcaption>The render prop is common across all platforms</figcaption></figure><p>3. A common RPC (Render Prop Component) that contains common code. Let’s continue the location example from item two as an example of common code. We may want to do the same thing with the obtained location no matter how it was obtained. That functionality would exist at this level.</p><p>Additionally, the RPC can provide common reactions across platforms in response to lifecycle events.</p><p><strong><em>Platform Specific Render Functions</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*-D1iIHJU8QPDDjk4SrE2vA.png" /><figcaption>Each platform has a different render function to build and present the UI</figcaption></figure><p>4. Platform specific render functions make use of platform specific primitives like &lt;div&gt; and &lt;View&gt;, and (if required) UI libraries such as <a href="https://reactstrap.github.io/">reactstrap</a> and <a href="https://nativebase.io/">NativeBase</a> to present the UI to the user. It can also interact with the renderProp that it receives from the RPC to act on code within the RPC. Additionally, it can interact with any platform specific code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*WjBI-U65uj2MRr0p2SHMZg.png" /><figcaption>Bringing it all together</figcaption></figure><p><strong>Adding Redux</strong></p><p>Once I confirmed that both platforms could access code inside the shared folder, I set up my Redux store. To do this, I installed the redux NPM packaged to all three folders. I additionally installed react-redux to both platform folders. I then created the Redux store using from a file that kept in the shared folder, and exported it. Both platforms then imported that store to use in their provider component. Doing this allowed me to only maintain one version of the store across both platforms.</p><p>Similarly, I placed the Redux reducers and actions in the shared folder. From there the platform specific code was able to import them as needed.</p><p><strong>Working with Redux and the Renderprop Components</strong></p><p>Maintaining the separation of view and logic meant that my RPs would be responsible to writing to the store. Doing this had the benefit of writing “this.props.dispatch” one time vice doing it twice for each platform. I also knew that once I was satisfied with store manipulation on one platform, I’d likely be just as satisfied on other platforms.</p><p>However, while the store existed in the shared directory, it was imported by each platform separately and provided to each platforms root component using the &lt;Provider/&gt; component from react-redux. This resulted in the platform “owning” Redux’s dispatch and connect functionality. To summarize, the platform UI components would have to connect to the Redux store, not the RP component.</p><p>This problem can be solved by connecting the platform UI component, and then passing this.props.dispatch and actions to the RP as shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/320ceaf9f928bb23f8b5309c988520a0/href">https://medium.com/media/320ceaf9f928bb23f8b5309c988520a0/href</a></iframe><p>The shared RP can then dispatch actions and manipulate the store just like any other component.</p><p>Packages that required setup during runtime were handled in a similar manner. For example, Amazon Web Service’s Amplify service requires initialization at application start. Amplify was used in both the web and mobile apps, so it made sense to work with it via the RPs; however, the RPs do not automatically have access to the initialized, application specific Amplify instances. This problem can be solved by passing the relevant Amplify specific functions to the RP as shown below. In this case, passing the functions gives the RP the ability to make API calls for both platforms.</p><p><strong>NPM Package Installations</strong></p><p>One thing to keep in mind is the interaction of NPM packages between the various platforms and the shared directory. I ended up installing packages to each platform’s directory, and the shared directory as needed. For example, React Native specific testing libraries would be installed to the mobile platform only. Gatsby was installed to the web platform only. Packages that were required by the shared RPs or shared utilities were installed to the shared folder as required.</p><p>Bottom line: install packages as needed by each “branch” of the project; web, mobile, shared, etc.</p><h4>Conclusion</h4><p>So far the RP pattern has proven an effective way to share code and functionality across platforms. While it does take additional work to recall project organization, I’ve drastically cut down on the amount of code I’ve had to write and created a shared testing target for my most complicated code.</p><p>On the other hand, I’m sure there are some very experienced programmers that can tell me why this technique may not be the best idea. I realize that that some of the techniques described in this article may be sub-optimal. I look forward to hearing about those problems, and potential solutions in the comments below.</p><p><em>Reginald Johnson has maintained his passion for coding throughout his 20+ year career as an Officer in the United States Navy. He enjoys applying his training and experience in programming, Systems Engineering, and Operational Planning towards full stack software development. Follow him Twitter @reginald3, GitHub at </em><a href="https://github.com/reggie3"><em>https://github.com/reggie3</em></a><em>, and LinkedIn @</em><a href="https://www.linkedin.com/in/reggie3"><em>https://www.linkedin.com/in/reggie3</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f451af26378" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-training/sharing-code-between-react-web-and-react-native-applications-7f451af26378">Sharing Code Between React Web and React Native Applications</a> was originally published in <a href="https://medium.com/react-native-training">React Native Training</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Communication Between React Native WebViews and the Webpages they Render]]></title>
            <link>https://medium.com/react-native-training/improving-communication-between-react-native-webviews-and-the-webpages-they-render-792c8f7db3e5?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/792c8f7db3e5</guid>
            <category><![CDATA[leaflet]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[webview]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 09:11:42 GMT</pubDate>
            <atom:updated>2018-07-03T16:15:09.234Z</atom:updated>
            <content:encoded><![CDATA[<h4>Simplify Your Code by Making Your WebView and React Native Components Run Each Other’s Functions</h4><p>Programmers are frequently afflicted with what I call “there must be a better way” (TeMBaW) syndrome. TeMBaW frequently occurs when you successfully accomplish something new to you. However, after that initial sense of accomplishment, some nagging details start rearing their head like that tickling scratchiness in the back of your throat before you get sick. You may go back to the code you wrote, and start getting hints of the <a href="https://en.wikipedia.org/wiki/Code_smell">code smell</a> you previously ignored. Or, at some later point, you may just realize that some new skill you’ve acquired could offer significant improvement on previously “completed” projects.</p><p>My <a href="https://github.com/reggie3/react-native-webview-leaflet">react-native-webview-leaflet</a> package afflicted me with a severe case of TeMBaW. Sure, it did it’s job; it displayed a <a href="https://leafletjs.com/">Leaflet</a> map in a React Native component. It even did some things that the <a href="https://github.com/react-community/react-native-maps">react-native-maps</a> component didn’t do like provide support for CSS animation of markers, and customized markers including SVG and emojis. However, it suffered from what I felt were several problems, most of which existed because a lack of experience during its creation meant that I just didn’t know then what I know now.</p><p>And what I knew now (well, at least suspected) was that by using <a href="https://github.com/PaulLeCam/react-leaflet">react-leaflet</a> inside a React Native WebView along with some thoughtful function names, I could share state and functions between my React Native application and the Leaflet React component. It also occurred to me that this technique would be applicable to vanilla JavaScript pages.</p><p>This article will explain that technique. Specifically, I will show how the webpage rendered by a React Native WebView can “call” a React Native function and update the React Native component’s state. I will also show how the React Native component can call the webpage’s functions as well as update the webpage’s state.</p><h4>Problem</h4><p>The React Native WebView and the webpage need to communicate. This means they need to “speak” and “listen” to each other. The communication also needs to be meaningful, simple, and compact. The bottom line is that I don’t want to write a lot of code enable concise communication between the two components.</p><p>Though this problem was solved in my previous article, I felt there was a better way. That previous technique is detailed in <a href="https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-4-cb4f7c02c193">Accepting Payments in a React Native App,</a> so I won’t rehash it here. I will say that it involved a lot of “translation” in the WebView component to support communications between the webpage and the WebView’s parent. Eliminating this translation and minimizing the WebView’s middle man role were the primary goals of this new technique.</p><h4>Implementation</h4><p>Remember that the webpage is just that, a webpage. As such it has access to the document object in the HTML DOM. In order for the webpage rendered by the WebView to “hear”, we add an event listener to the document so that it can hear message events like this.</p><p>document.addEventListener(&#39;message&#39;, this.handleMessage)</p><p>To talk it uses the document.postMessage in response to component events. The sequence starting from handling an event to sending a message in shown in the GitHub gist below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf37ecf35906b93b1ffa04c9fc4ef10e/href">https://medium.com/media/bf37ecf35906b93b1ffa04c9fc4ef10e/href</a></iframe><p>On the other side of the conversation, the RN WebView hears via its onMessage prop which can call a function and pass the message as an argument. It talks by using the postMessage function that can be accessed by a ref to the WebView component, and takes the message as an argument.</p><p>There are two significant caveats to this conversation.</p><ol><li>All messages must consist of strings. Fortunately, JSON.stringify and JSON.parse simplify the process of converting objects to and from strings .</li><li>Other people use this communication path just like an old-fashioned <a href="https://en.wikipedia.org/wiki/Party_line_(telephony)">party line telephone system</a>. Just like then, we can include a prefix in our messages to ensure the components know what to listen for and what can be ignored.</li></ol><p>So, how do we call a function and how do we set state? First I’ll discuss webpage to RN WebView communication, then I’ll talk about the other direction.</p><h4>Webpage to WebView Communication</h4><p>We can make the WebView component react to an event emitted by the webpage through thoughtful use of event and function names. For example, a Leaflet map emits an onLoad even when it has completed loading. When that event occurs, the webpage builds an object that includes that event name, any parameters that may accompany that event, and an application specific prefix. Then we can use JSON.stringify to turn that message into a string, and send it to the WebView via a call to postMessessage.</p><p>The WebView then receives the message and applies JSON.parse to it in order to recreate the original object. Recall that this object has an event key that has the event’s name as it’s value. At that point, we can use the event value to call a function in the WebView component or even the parent component.</p><p>The first example below shows how to call a function in the component containing the WebView. This function has the same name as the event value that is contained in msgData.payload which is the parsed message object that was sent by our webpage. The second example calls a function in the eventReceiver component passed as a prop to the WebView.</p><p>this.[msgData.payload.event](msgData.payload)</p><p>this.props.eventReceiver[msgData.payload.event](msgData.payload)</p><p>Setting state works similarly. An absence of the event key in msgData can tell us that this message is not an event, and that it contains data that should be used to update state. Both of these concepts are shown in the GitHub gist excerpt below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/295b4050a9a5ffd1b0e84fa5b9d6c603/href">https://medium.com/media/295b4050a9a5ffd1b0e84fa5b9d6c603/href</a></iframe><h4>WebView to Webpage Communication</h4><p>On the other hand, let’s say that the eventReceiver component wants to communicate with the WebPage. In this situation, the eventReceiver is essentially using the WebView to do the talking by creating a ref to the WebView, and calling its postMessage function.</p><p>The ref is created like this:</p><p>ref={(component) =&gt; (this.webViewLeaflet = component)}</p><p>And a message can be sent like this (in this case, configuration options are being passed to a react-leaflet map).</p><p>this.webViewLeaflet.sendMessage({ zoom: 6, locations: this.state.locations, showAttributionControl: this.state.mapState.showAttributionControl, showZoomControl: this.state.mapState.showZoomControl });</p><p>At that point, the communication from the WebView to the webpage works essentially the same way as demonstrated in the above gist as long as you have a React component in your webpage.</p><p>One of the benefits of using React in your page is reactive to state, so a simple call to setState can have the same effect as multiple functions or can behave like an event thanks to the componentDidUpdate and getDerivedStateFromProps life-cycle functions.</p><p>Otherwise, if you’re using plain vanilla JS you can create functions in the WebPage’s code and then send messages with event keys corresponding to the name of functions.</p><p>Taken all together, the communication flow can be summarized by this diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-UrhoF02qgxUUYQE4K3qg.png" /></figure><h4>Conclusion</h4><p>This technique vastly simplified my code. It replaced the large switch statements I previously used to route communication with simple calls to functions with names that matched variables in the passed message. This improvement was a case where TeMBaW resulted in a better product, and easier path to creating similar components in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=792c8f7db3e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-training/improving-communication-between-react-native-webviews-and-the-webpages-they-render-792c8f7db3e5">Improving Communication Between React Native WebViews and the Webpages they Render</a> was originally published in <a href="https://medium.com/react-native-training">React Native Training</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convert Any* JavaScript Library into a React Native Component]]></title>
            <link>https://blog.expo.dev/convert-any-javascript-library-into-a-react-native-component-12a2aa11b007?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a2aa11b007</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Fri, 20 Apr 2018 21:29:06 GMT</pubDate>
            <atom:updated>2018-04-20T21:29:06.527Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating a Expo-friendly Reusable Component by Wrapping a JS Library into a React Component with No Native Code.</h4><h4>Introduction</h4><p>This post is a continuation and improvement of the techniques discussed in a <a href="https://blog.expo.io/how-to-combine-expo-gulp-and-webpack-to-create-and-publish-react-components-to-npm-baec7b6bb443">previous post</a>. In that article, I described a technique that combined Expo’s ease of development, Webpack’s packaging capability, Gulp’s task automation, and React Native’s WebView component in order to covert an UI oriented JavaScript library into React Native component. An advantage of using this technique is that it avoided any native code; making the component suitable for use with Expo.</p><p>While the previous post is not project-specific, I did implement the technique in my <a href="https://www.npmjs.com/package/react-native-webview-quilljs">react-native-webview-quilljs</a> and <a href="https://www.npmjs.com/package/react-native-webview-leaflet">react-native-webview-leaflet</a>packages.</p><h4>Problems</h4><p>While functional, this technique possessed several shortfalls. First, the JSfiles used by the HTML file that was displayed by the WebView were not included in the package bundle due to a limitation of the Expo bundling process. The bundler did not import anything that was included using a &lt;script src=&quot;myscripts.js&quot;&gt;&lt;/script&gt; tag. This limitation prevented the JS and CSS files relied on by the HTML file from being bundled in the Expo application.</p><p>While this may not be a problem for a regular NPM package, it prevented me from using the package with an Expo project since the bundler wouldn’t know to include the necessary files. This resulted in multiple errors ranging from the inability to find the JS files to file access denied errors.</p><p>The workaround described in the <a href="https://blog.expo.io/how-to-combine-expo-gulp-and-webpack-to-create-and-publish-react-components-to-npm-baec7b6bb443">previous post</a> was to download the required HTML, JS, and CSS files from the project’s GitHub repo prior to using them. This required file hosting, meant that the user had to have an Internet connection when the WebView was first used, and obligated filesystem access to write and read the downloaded files.</p><p>All this also meant that I needed to include error handling and tracking to prevent an error from occurring if there was no Internet connection. Additionally, I included the Expo filesystem API to read and write to the device filesystem. Unfortunately, this mean that Expo had to be included as an additional dependency when all I wanted was a subset of its impressive functionality.</p><h4>The Fix</h4><p>This post describes a technique to avoid those problems by in-lining JS and CSS into the HTML file the WebView loads. This has several advantages:</p><ol><li>Full off-line functionality since the files don’t need to be downloaded</li><li>A smaller NPM package since Expo no longer needs to be included</li><li>The ability to build the package and alongside an application created with Expo that can be used to test the package directly</li><li>The package can be used in apps that don’t include Expo as a dependency</li></ol><p>It also maintains the primary advantage of using this technique; the ability to wrap a JS library into a React Native component that is suitable for NPM publishing. In addition, this package is usable by Expo since it contains no native code.</p><h4>Design</h4><p>I was already using Webpack to bundle my JavaScript and CSS, so why not also use it to inline the JS and CSS?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*1leLrWPCH4WVoptbT5G88Q.png" /></figure><p>I ended up adding “inline the JavaScript” to the list of Webpack’s responsibilities which already included creating the HTML pages from a HTML template file, optimizing and bundling my JS and CSS, and placing source links in the resultant HTML files that imported the JS bundles.</p><h4>Implementation</h4><p>The above requirement was satisfied by adding the <a href="https://www.npmjs.com/package/html-webpack-inline-source-plugin">html-webpack-inline-source-plugin</a>plugin to my existing webpack.config.js file. The<a href="https://www.npmjs.com/package/html-webpack-inline-source-plugin">html-webpack-inline-source-plugin</a> does what its name implies; it places the JS and CSS source inline with the HTML. This way, if the WebView is able to load the HTML files, then it is guaranteed to be able to load the JS and CSS files.</p><p>Thanks to Webpack, I was able to create HTML files containing a nicely bundled chunk of JS and CSS. This file was now ready to use as a React Native WebView’s source. Webpack placed this file in the project’s build directory. I then used Gulp to copy that file from the build to the assets/dist directory. I ended up using Gulp because I couldn’t find a Webpack plugin that would delay copying until after packaging was complete.</p><h4>Test and Evaluation</h4><p>I tested and validated the file by getting the updated react-native-webview-quilljs package working in three different scenarios:</p><ol><li>Development mode in the Expo application that was built to test, and demonstrate the package.</li><li>In the Expo published version of the demonstration application</li><li>Imported as an NPM package into a completely separate application</li></ol><p>The first problem I encountered was at step one. Ensuring that the Webview was accessing the correct file wasn’t trivial. Although the correct location for my file was the project’s asset/dist folder. The logging excerpt from the Expo SDK shows that the program follows the assets/assets/dist path to find the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*BSNtEMVjJRgxCwARPeuwwA.png" /><figcaption>Notice the file path is “assets/assets/dist”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*eXEDezxZzKRtFr_0X_6cjQ.png" /><figcaption>Even though the desired file in in an “assets/dist” directory</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*xXFhwEBqIlBfXeAdGN3rrA.png" /><figcaption>Just import it from the actual folder location</figcaption></figure><p>While somewhat disorienting, this did not prevent the project from working. However, ensuring the correct file path will be my first debugging starting point if any issues pop up.</p><p>A technique to ensure that the correct HTML file is being found and loaded is to include some inconsequential text in the HTML. That way the file’s presence can be confirmed even if an error prevents the JS from loading. If the text is visible, then the page is loading, otherwise there is a problem preventing the page from being loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*AsQ9VFfGeOWdlVeSfPKdSA.png" /><figcaption>The “html” text confirms that the two WebViews were able to located and load the HTML files</figcaption></figure><p>Additional problems manifested once the WebView did display the content. For example, the text was too small on iOS devices. This was a relatively easy fix by adding scalesPageToFit={false} to the props of the WebView. Also, loading HTTP content from another source (for example, the map tiles required by Leaflet) may require setting the WebView prop mixedContentMode={‘always’}</p><p>Jumping to step two turned into an issue due to the difference in how file imports/requires are handled in Expo applications during development and and in production. This difference is described <a href="https://docs.expo.io/versions/latest/guides/assets.html#where-assets-live">here</a> in a section of Expo documentation that is aptly titled “Where assets live”. Bottom line is that the HTML files were not available to the production application because they were not bundled.</p><p>Fortunately, <a href="https://forums.expo.io/t/what-is-path-to-location-of-files-bundled-with-assetbundlepatterns-in-sdk-v25/7311">Expo forums</a> user Jesse pointed me towards the following code that, when added to the <a href="https://github.com/reggie3/react-native-webview-quilljs/blob/inline-javascript-3/app.json">app.json</a> file, ensures HTML files are bundled for production:</p><pre>&quot;packagerOpts&quot;: {<br> &quot;assetExts&quot;: [&quot;html&quot;]<br>},</pre><p>Another problem that may occur at this step is related to file access and can manifest itself with the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*tArXwyJSVA8ip9Am9zZN6A.jpeg" /><figcaption>File Access Error due to incorrect file location</figcaption></figure><p>This happened because the WebView attempted to access a file that wasn’t available, or was not in the expected location. Once again, confirm the HTML file’s path is as expected, and the import statement importing the file is looking in the correct place.</p><p>Finally; for step three, I imported the published package into another Expo application, and verified that the WebView did actually render the content as expected.</p><h4>Publishing</h4><p>I wanted to publish to NPM directly from the Expo test application’s project directory. To do this, I created a <a href="https://github.com/reggie3/react-native-webview-quilljs/blob/master/gulpfile.js">Gulp script</a> that updated the dependenciesand index in package.json to be suitable for NPM publishing. The script also bumped the version value, and performed my git operations. Finally, it reverted the dependencies and index to make the project suitable for use as an Expo application again.</p><h4>Summary</h4><p>In summary, use the <a href="https://www.npmjs.com/package/html-webpack-inline-source-plugin">html-webpack-inline-source-plugin</a> Webpack plugin to place JS and CSS source files inline with the HTML file. Additionally, use Gulp to automate publishing and git operations. Also, monitor the Expo XDE log to ensure the Webview is looking for the HTML file in the proper location. Finally, update your packagerOpts in app.json to include your HTML file in the published package bundle.</p><h4>Conclusion</h4><p>Including the JS and CSS in my main HTML file worked. It allowed me to create React Native components wrapping <a href="https://quilljs.com/">Quill</a> and <a href="http://leafletjs.com/">Leaflet</a> and publish them to NPM for successful use in a completely separate project.</p><p>The biggest downside is that the WebView component doesn’t load as fast as a native component. This is logical since the JS has to be executed inside the browser that is part of the WebView vice being recompiled in Swift of Java. It would be nice if there was a way to load and run the WebView, possible up to just prior to component rendering, and then cache the results; with the goal of doing any JS heavy lifting prior to displaying the component.</p><p>*This technique should be pretty flexible. However, I’m sure there are caveats that will prevent it from being a universal solution. And, while I wouldn’t bet that this technique allows every JS library to be turned into a React Native component, it did satisfy my requirement for these two libraries in particular, and will be a go-to technique in the future.</p><p><em>Curious? Follow our guest blogger Reginald Johnson on </em><a href="https://twitter.com/reginald3"><em>Twitter</em></a><em>, or connect with him on </em><a href="https://www.linkedin.com/in/reggie3/"><em>LinkedIn</em></a><em>. Reginald is a 20+ year military veteran who’s blogging, creating, and teaching his way through his transition into software development.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a2aa11b007" width="1" height="1" alt=""><hr><p><a href="https://blog.expo.dev/convert-any-javascript-library-into-a-react-native-component-12a2aa11b007">Convert Any* JavaScript Library into a React Native Component</a> was originally published in <a href="https://blog.expo.dev/">Exposition</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turn Any* JavaScript Library into a React Native Component]]></title>
            <link>https://medium.com/react-native-training/turn-any-javascript-library-into-a-react-native-component-e8ab0c710f12?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8ab0c710f12</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Wed, 11 Apr 2018 22:23:40 GMT</pubDate>
            <atom:updated>2018-04-11T23:08:18.301Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating a Reusable Component by Wrapping a JS Library in to a React Component with No Native Code</h4><h4>Introduction</h4><p>This post is a continuation and improvement of the techniques discussed in a <a href="https://blog.expo.io/how-to-combine-expo-gulp-and-webpack-to-create-and-publish-react-components-to-npm-baec7b6bb443">previous post</a>. In that article, I described a technique that combined Expo’s ease of development, Webpack’s packaging capability, Gulp’s task automation, and React Native’s WebView component in order to covert an UI oriented JavaScript library into React Native component. An advantage of using this technique is that it avoided any native code; making the component suitable for use with Expo.</p><p>While the previous post is not project specific, I did implement the technique in my <a href="https://www.npmjs.com/package/react-native-webview-quilljs">react-native-webview-quilljs</a> and <a href="https://www.npmjs.com/package/react-native-webview-leaflet">react-native-webview-leaflet</a> packages.</p><h4>Problems</h4><p>While functional, this technique possessed several shortfalls. First, the JSfiles used by the HTML file that was displayed by the WebView were not included in the package bundle due to a limitation of the Expo bundling process. The bundler did not import anything that was included using a &lt;script src=&quot;myscripts.js&quot;&gt;&lt;/script&gt; tag. This limitation prevented the JS and CSS files relied on by the HTML file from being bundled in the Expo application.</p><p>While this may not be a problem for a regular NPM package, it prevented me from using the package with an Expo project since the bundler wouldn’t know to include the necessary files. This resulted in multiple errors ranging from the inability to find the JS files to file access denied errors.</p><p>The workaround described in the <a href="https://blog.expo.io/how-to-combine-expo-gulp-and-webpack-to-create-and-publish-react-components-to-npm-baec7b6bb443">previous post</a> was to download the required HTML, JS, and CSS files from the project’s GitHub repo prior to using them. This required file hosting, meant that the user had to have an Internet connection when the WebView was first used, and obligated filesystem access to write and read the downloaded files.</p><p>All this also meant that I needed to include error handling and tracking to prevent an error from occurring if there was no Internet connection. Additionally, I included the Expo filesystem API to read and write to the device filesystem. Unfortunately, this mean that Expo had to be included as an additional dependency when all I wanted was a subset of its impressive functionality.</p><h4>The Fix</h4><p>This post describes a technique to avoid those problems by in-lining JS and CSS into the HTML file the WebView loads. This has several advantages:</p><ol><li>Full off-line functionality since the files don’t need to be downloaded</li><li>A smaller NPM package since Expo no longer needs to be included</li><li>The ability to build the package and alongside an application created with Expo that can be used to test the package directly</li><li>The package can be used in apps that don’t include Expo as a dependency</li></ol><p>It also maintains the primary advantage of using this technique; the ability to wrap a JS library into a React Native component that is suitable for NPM publishing. In addition, this package is usable by Expo since it contains no native code.</p><h4>Design</h4><p>I was already using Webpack to bundle my JavaScript and CSS, so why not also use it to inline the JS and CSS?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*1leLrWPCH4WVoptbT5G88Q.png" /></figure><p>I ended up adding “inline the JavaScript” to the list of Webpack’s responsibilities which already included creating the HTML pages from a HTML template file, optimizing and bundling my JS and CSS, and placing source links in the resultant HTML files that imported the JS bundles.</p><h4>Implementation</h4><p>The above requirement was satisfied by adding the <a href="https://www.npmjs.com/package/html-webpack-inline-source-plugin">html-webpack-inline-source-plugin</a>plugin to my existing webpack.config.js file. The<a href="https://www.npmjs.com/package/html-webpack-inline-source-plugin">html-webpack-inline-source-plugin</a> does what its name implies; it places the JS and CSS source inline with the HTML. This way, if the WebView is able to load the HTML files, then it is guaranteed to be able to load the JS and CSS files.</p><p>Thanks to Webpack, I was able to create HTML files containing a nicely bundled chunk of JS and CSS. This file was now ready to use as a React Native WebView’s source. Webpack placed this file in the project’s build directory. I then used Gulp to copy that file from the build to the assets/dist directory. I ended up using Gulp because I couldn’t find a Webpack plugin that would delay copying until after packaging was complete.</p><h4>Test and Evaluation</h4><p>I tested and validated the file by getting the updated react-native-webview-quilljs package working in three different scenarios:</p><ol><li>Development mode in the Expo application that was built to test, and demonstrate the package.</li><li>In the Expo published version of the demonstration application</li><li>Imported as an NPM package into a completely separate application</li></ol><p>The first problem I encountered was at step one. Ensuring that the Webview was accessing the correct file wasn’t trivial. Although the correct location for my file was the project’s asset/dist folder. The logging excerpt from the Expo SDK shows that the program follows the assets/assets/dist path to find the file</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*BSNtEMVjJRgxCwARPeuwwA.png" /><figcaption>Notice the file path is “assets/assets/dist”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*eXEDezxZzKRtFr_0X_6cjQ.png" /><figcaption>Even though the desired file in in an “assets/dist” directory</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*xXFhwEBqIlBfXeAdGN3rrA.png" /><figcaption>Just import it from the actual folder location</figcaption></figure><p>While somewhat disorienting, this did not prevent the project from working. However, ensuring the correct file path will be my first debugging starting point if any issues pop up.</p><p>A technique to ensure that the correct HTML file is being found and loaded is to include some inconsequential text in the HTML. That way the file’s presence can be confirmed even if an error prevents the JS from loading. If the text is visible, then the page is loading, otherwise there is a problem preventing the page from being loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*AsQ9VFfGeOWdlVeSfPKdSA.png" /><figcaption>The “html” text confirms that the two WebViews were able to located and load the HTML files</figcaption></figure><p>Additional problems manifested once the WebView did display the content. For example, the text was too small on iOS devices. This was a relatively easy fix by adding scalesPageToFit={false} to the props of the WebView. Also, loading HTTP content from another source (for example, the map tiles required by Leaflet) may require setting the WebView prop mixedContentMode={‘always’}</p><p>Jumping to step two turned into an issue due to the difference in how file imports/requires are handled in Expo applications during development and and in production. This difference is described <a href="https://docs.expo.io/versions/latest/guides/assets.html#where-assets-live">here</a> in a section of Expo documentation that is aptly titled “Where assets live”. Bottom line is that the HTML files were not available to the production application because they were not bundled.</p><p>Fortunately, <a href="https://forums.expo.io/t/what-is-path-to-location-of-files-bundled-with-assetbundlepatterns-in-sdk-v25/7311">Expo forums</a> user Jesse pointed me towards the following code that, when added to the <a href="https://github.com/reggie3/react-native-webview-quilljs/blob/inline-javascript-3/app.json">app.json</a> file, ensures HTML files are bundled for production:</p><p>&quot;packagerOpts&quot;: {<br> &quot;assetExts&quot;: [&quot;html&quot;]<br>},</p><p>Another problem that may occur at this step is related to file access and can manifest itself with the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*tArXwyJSVA8ip9Am9zZN6A.jpeg" /><figcaption>File Access Error due to incorrect file location</figcaption></figure><p>This happened because the WebView attempted to access a file that wasn’t available, or was not in the expected location. Once again, confirm the HTML file’s path is as expected, and the import statement importing the file is looking in the correct place.</p><p>Finally; for step three, I imported the published package into another Expo application, and verified that the WebView did actually render the content as expected.</p><h4>Publishing</h4><p>I wanted to publish to NPM directly from the Expo test application’s project directory. To do this, I created a <a href="https://github.com/reggie3/react-native-webview-quilljs/blob/master/gulpfile.js">Gulp script</a> that updated the dependencies and index in package.json to be suitable for NPM publishing. The script also bumped the version value, and performed my git operations. Finally, it reverted the dependencies and index to make the project suitable for use as an Expo application again.</p><h4>Summary</h4><p>In summary, use the <a href="https://www.npmjs.com/package/html-webpack-inline-source-plugin">html-webpack-inline-source-plugin</a> Webpack plugin to place JS and CSS source files inline with the HTML file. Additionally, use Gulp to automate publishing and git operations. Also, monitor the Expo XDE log to ensure the Webview is looking for the HTML file in the proper location. Finally, update your packagerOpts in app.json to include your HTML file in the published package bundle.</p><h4>Conclusion</h4><p>Including the JS and CSS in my main HTML file worked. It allowed me to create React Native components wrapping <a href="https://quilljs.com/">Quill</a> and <a href="http://leafletjs.com/">Leaflet</a> and publish them to NPM for successful use in a completely separate project.</p><p>The biggest downside is that the WebView component doesn’t load as fast as a native component. This is logical since the JS has to be executed inside the browser that is part of the WebView vice being recompiled in Swift of Java. It would be nice if there was a way to load and run the WebView, possible up to just prior to component rendering, and then cache the results; with the goal of doing any JS heavy lifting prior to displaying the component.</p><p>As for the asterisk in the title, this technique should be pretty flexible. However, I’m sure there are caveats that will prevent it from being a universal solution. And, while I wouldn&#39;t bet that this technique allows every JS library to be turned into a React Native component, it did satisfy my requirement for these two libraries in particular, and will be a go-to technique in the future.</p><p><em>Reginald Johnson is a 20+ year military veteran who is blogging, creating, and teaching his way through his transition into software development. You can follow him on Twitter at @reginald3, or connect with him on LinkedIn at https://www.linkedin.com/in/reggie3/</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8ab0c710f12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-training/turn-any-javascript-library-into-a-react-native-component-e8ab0c710f12">Turn Any* JavaScript Library into a React Native Component</a> was originally published in <a href="https://medium.com/react-native-training">React Native Training</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Combine Expo, Gulp, and Webpack to Create and Publish React Components to NPM]]></title>
            <link>https://blog.expo.dev/how-to-combine-expo-gulp-and-webpack-to-create-and-publish-react-components-to-npm-baec7b6bb443?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/baec7b6bb443</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Thu, 15 Feb 2018 18:20:56 GMT</pubDate>
            <atom:updated>2018-03-03T02:17:32.046Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using Expo, Gulp, and Webpack to Create and Publish React Components to NPM</h3><h4>Combining Tooling with Automation to Build Something that Contributes to the Community</h4><p>If you’ve read my previous posts, you’ve probably gathered that I’m working on some sort of side project. Hopefully, I will get to the point that I’m ready to release my creation, but for now I’ve been content to adjust and tweak as needed. For example, I’ve repeatedly gotten to the point where it made logical sense to break out significant pieces of functionality and place them in their own NPM modules.</p><p>Doing this provides multiple benefits. It allows other people to use, and help improve, the functionality the package provides. It also provides the benefit of improved reuse in another project (there’s always another project) by just doing an npm install (or yarn add if you prefer). Additionally, it would allow me to “<a href="https://www.pickthebrain.com/blog/how-to-eat-an-elephant/">eat the elephant one bite at a time</a>” vice being confronted with my entire project in one go. I still have a day job, so any ability to modularize my task helps contribute to its accomplishment.</p><p>It was with all this in mind that I created the <a href="https://github.com/reggie3/react-native-webview-quilljs">react-native-webview-quilljs</a> and <a href="https://github.com/reggie3/react-native-webview-leaflet">react-native-webview-leaflet</a> packages. In this post, I will go over the technique I used to build, package, and publish those components using <a href="https://expo.io/">expo.io</a>, <a href="https://webpack.js.org/">webpack</a>, and <a href="https://gulpjs.com/">gulp</a>. Specifically, I will cover how I built an application using Expo, used Webpack to package the files required by a React Native WebView component, and then used gulp to automate a build and publishing process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*Yq5UWxcAFLNwVVR1GM7lJA.png" /><figcaption>Gulp is going to take us there and bring us back</figcaption></figure><h4>Design</h4><p>This post assumes some familiarity with Expo, Webpack, Gulp and NPM so I’m only going to discuss the process required to go from an Expo project to published NPM package. This is a multiple step process:</p><ol><li>Use Expo to create an application containing the functionality you wish to publish</li><li>Separate that functionality into a separate component within the project</li><li>Use a Gulp task to automate the packaging and NPM publishing process.</li></ol><h4><strong>Creating an application with Expo</strong></h4><p>I previously discussed the use of react-native webviews to incorporate plain JavaScript functionality into a react-native application in my four-part series “Accepting Payments in a React Native App”. In particular, <a href="https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-4-cb4f7c02c193">Part Four: Building the Payment Client Using React Native and React</a> shows that using a Webpack pipeline to compile React results in a project that can be imported into a React-Native webview. Basically, as long as your pipeline delivers an html file that the webview can use as its source, you should have a working Expo project that can be run via the Expo XDE.</p><p>That project used Webpack to create a “dist” folder containing an HTML file and the associated JavaScript and CSS files needed to display the React Component that encapsulated the JavaScript library that I was attempting to run. For the above referenced project project, I created a WebView that used Braintree’s payment library.</p><p>However, an unanticipated and very ugly problem revealed itself when I finally attempted to run the project after publishing it to Expo: the HTML file (and its JavaScript and CSS files) required by the WebView was not packaged for publication. That’s because, at the time I am writing this article, Expo is only capable of bundling certain types of files with standalone applications. This limitation is discussed as part of the asset bundling guide in their <a href="https://docs.expo.io/versions/latest/guides/offline-support.html">offline support features</a>. However, I would not be surprised if Expo got around to including offline support for HTML, CSS, and JavaScript files at some point. Once they do, then a significant portion of this post will be a “moo” point…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*sSQOZMKTlx5Vo7h2." /><figcaption>Friends, creating unrealistic housing expectations for millions</figcaption></figure><p>This was a problem because the project would not work when published. It only worked in the development environment on the local computer. And without publication there is no demo project, and without a demo project there is not NPM package, and with no NPM package there is no glory!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*7aJ-w5arNSU79xL60zmrpg.png" /><figcaption>Or infamy, you know how the Internet is.</figcaption></figure><p>Predictably, this issue continued I published the package to NPM and used it in another project. The component in the NPM package itself contained a WebView that I had anticipated would be able to access the index.html file that was also located in the same NPM package. Unfortunately, that was not the case. The WebView rendered; however, it was not able to access the HTML file that was literally just a directory away.</p><p><strong>To summarize</strong>, a WebView with a source=require(‘./dist/index.html’) when “./dist/index.html” was in the same package wasn’t displaying anything. This problem is discussed more in depth in this <a href="https://github.com/facebook/react-native/issues/505">GitHub issue</a>.</p><p><strong><em>Update (16 Feb 2018)</em></strong></p><p><em>Expo SDK 25’s asset bundling provides support for including CSS, HTML, and JavaScript files in a published package. This means that the upload technique described below shouldn’t be necessary if you are using that version or newer. You can learn more about Expo asset bundling </em><a href="https://blog.expo.io/expo-sdk-v25-0-0-is-now-available-714d10a8c3f7"><em>here</em></a><em>. Now back to the original content.</em></p><p><strong><em>Update (2 Mar 2018)</em></strong></p><p><em>It looks like the Expo/React-Native ecosystem isn’t quite ready to bundle JavaScript files into published packages. My exploits trying to do this are documented in </em><a href="https://forums.expo.io/t/what-is-path-to-location-of-files-bundled-with-assetbundlepatterns-in-sdk-v25/7311/11"><em>this thread on the Expo forums</em></a><em>. I hope to find an alternative to the work-around described below, and will publish a new article when I do.</em></p><p>In addition to the work-arounds listed in the issue tracker, Expo forum user <a href="https://forums.expo.io/t/problem-with-webview-after-exp-publish/3859/4">burak</a> proposed the technique of uploading the necessary HTML, JS, and CSS files to the Internet and then download them to the mobile for use in the WebView. This is the technique I chose to follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*kDke_1xKh7zcaTWmdF9eJA.gif" /></figure><p>An online repository or <a href="https://www.incapsula.com/cdn-guide/what-is-cdn-how-it-works.html">CDN</a> will suffice for this as long as you have a URL that points to the file(s). Then, those files can be downloaded to the local device the first time the component containing the WebView is mounted, or if a version change is detected. This process is defined by the following steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcf85c10bc5641cc83bd0afcfff0eef6/href">https://medium.com/media/bcf85c10bc5641cc83bd0afcfff0eef6/href</a></iframe><p>At this point, the index.html file and its dependencies are available for the WebView to display.</p><p>This functionality is encapsulated in the versioned-file-downloader <a href="https://www.npmjs.com/package/versioned-file-downloader">NPM package</a> (here’s the <a href="https://github.com/reggie3/versioned-file-downloader">repo for that package</a>). This package uses the <a href="https://docs.expo.io/versions/latest/sdk/filesystem.html">Expo.FileSystem API</a> to download files to the device’s document directory. It looks for and downloads files into a folder structure that looks like this:</p><pre>[FileSystem document directory]/ [package name]/[version]/</pre><p>Once the file(s) have been successfully downloaded, they can be accessed using the WebView’s “source” prop like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fd08a02c2d5f7ebcb4fb8fb096bf12f/href">https://medium.com/media/7fd08a02c2d5f7ebcb4fb8fb096bf12f/href</a></iframe><p>At this point we have a way to obtain and display the files required by the WebView and the current situation can be summarized as follows…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*8aX3LemI8Xh8AueLsS9gqA.png" /><figcaption>Yes, it’s an old meme, but it checks out</figcaption></figure><h4><strong>Separating the Package from the Expo Project</strong></h4><p>Before extracting the files for publication, there needs to be a clean division between what will be the NPM package and the Expo application itself. The goal is to separate anything that might be reusable and place it into a file that will be imported. The desired goal is to have a file that exports a function that can be imported by another file. This function is then called with some number of arguments. Upon completion, it may or may not return something back to whatever called it initially.</p><p>Basically, create a function, throw it in a file, export it, and you have the start of a package.</p><h4><strong>Extracting the Package</strong></h4><p>There are a few distinct steps that have to be performed in order to extract the necessary files from the Expo Project and publish the NPM package:</p><ol><li>Webpack must be run whenever the files HTML, CSS, or JavaScript files used by the Webview are changed in order to create the updated files for use by the WebView.</li><li>The version number in package.json must be incremented prior to publishing the package.</li><li>A push to GitHub is required whenever we want to update the files that the WebView uses so that the WebView has access to the most up-to-date files.</li><li>Most insidiously, there are two changes that must be made to the “package.json” file and then reverted. Keep in mind that this file is used by Expo and NPM.</li><li>First is the “main” parameter in package.json. Remember, the files that will become an NPM package sit inside an Expo project. Expo projects require main to be equal to “node_modules/expo/AppEntry.js” in order to run as an Expo project. However, that won’t work for an NPM package which must be a JavaScript file contained in the package, and typically is set to “index.js”. This means that the “main” value must change prior to NPM publishing and then change again prior to running the Expo application that encompasses the package.</li><li>Next, the dependencies must be changed. Expo projects require an expo, react, and a special react-native dependency. Additionally, this WebView technique requires a react-dom dependency. However, none of those are requirements for the NPM package. In fact, I encountered breaking errors when I attempted to run the project with an NPM package that included those extraneous dependencies. This means that the dependency list must be different when publishing and running the Expo project</li></ol><p><strong>The bottom line</strong> is that the “main” and “dependencies” values in package.json must be one thing when publishing and something different when running the application. Since I still want to be able to run the application as an Expo project, I will have the change the values for main and dependencies to the appropriate values for publishing and then back to the correct values for an Expo project.</p><h4><strong>Automation with Gulp</strong></h4><p>Fortunately, these steps are predictable and repeatable, which means they are the perfect fit for a task runner like Gulp. A suitable gulpfile can be <a href="https://github.com/reggie3/expo-to-npm-gulpfile">found at this repo</a>. The primary tasks are “dev” and “prod” which can be run like any gulp task: “gulp dev” or “gulp prod”. The gulp dev task is show below that performs all those steps is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe80e3d450b77eeda3535faeb7fe7d1/href">https://medium.com/media/8fe80e3d450b77eeda3535faeb7fe7d1/href</a></iframe><p>The process accomplishes the cycle shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*tLABR4V6_e50Q81tWf57jw.png" /></figure><p>Running the gulp tasks results in a published NPM package suitable for use in other projects while still leaving a project suitable for running as an Expo project. Gulp is now the conductor of the publication workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*JNjN5UEXw_zyQWOUEHyJcw.gif" /></figure><h4>Conclusion</h4><p>As previously stated, this article is not meant to be a full-blown explanation of how to use all the tools it mentions. Each of the tools has significant amounts of documentation on their usage that I’d recommend familiarizing yourself with if you have questions.</p><p>Instead, this article is intended to describe a technique of combining multiple tools to achieve the desired goal; a published NPM package.</p><p>Expo provides the ability to quickly create and share mobile applications using React Native. React Native provides a WebView component that lets us display HTML, CSS, and JavaScript content inside our application. Webpack automates the build process and can create the necessary files for the WebView component to display. And finally, Gulp automates the processes that are required to have a working Expo project and a publishable NPM package.</p><p><em>Curious? Follow our guest blogger Reginald Johnson on </em><a href="https://twitter.com/reginald3"><em>Twitter</em></a><em>, or connect with him on </em><a href="https://www.linkedin.com/in/reggie3/"><em>LinkedIn</em></a><em>. Reginald is a 20+ year military veteran who’s blogging, creating, and teaching his way through his transition into software development.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=baec7b6bb443" width="1" height="1" alt=""><hr><p><a href="https://blog.expo.dev/how-to-combine-expo-gulp-and-webpack-to-create-and-publish-react-components-to-npm-baec7b6bb443">How to Combine Expo, Gulp, and Webpack to Create and Publish React Components to NPM</a> was originally published in <a href="https://blog.expo.dev/">Exposition</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Expo, Gulp, and Webpack to Create and Publish React Components to NPM]]></title>
            <link>https://medium.com/react-native-training/using-expo-gulp-and-webpack-to-create-and-publish-react-components-to-npm-2f66d9edef4c?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f66d9edef4c</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Thu, 15 Feb 2018 11:56:54 GMT</pubDate>
            <atom:updated>2018-08-24T14:34:37.734Z</atom:updated>
            <content:encoded><![CDATA[<h4>Combining Tooling with Automation to Build Something that Contributes to the Community</h4><p>If you’ve read my previous posts, you’ve probably gathered that I’m working on some sort of side-project. Hopefully, I will get to the point that I’m ready to release my creation, but for now I’ve been content to adjust and tweak as needed. For example, I’ve repeatedly gotten to the point where it made logical sense to break out significant pieces of functionality and place them in their own NPM modules.</p><p>Doing this provides multiple benefits. It allows other people to use, and help improve the functionality the package provides. It also provides the benefit of improved reuse in another project (there’s always another project) by just doing an npm install (or yarn add if you prefer). Additionally, it would allow me to “<a href="https://www.pickthebrain.com/blog/how-to-eat-an-elephant/">eat the elephant one bite at a time</a>” vice being confronted with my entire project in one go. I still have a day job, so any ability to modularize my task helps contribute to its accomplishment.</p><p>It was with all this in mind that I created the <a href="https://github.com/reggie3/react-native-webview-quilljs">react-native-webview-quilljs</a> and <a href="https://github.com/reggie3/react-native-webview-leaflet">react-native-webview-leaflet</a> packages. In this post, I will go over the technique I used to build, package, and publish those components using <a href="https://expo.io/">expo.io</a>, <a href="https://webpack.js.org/">webpack</a>, and <a href="https://gulpjs.com/">gulp</a>. Specifically, I will cover how I built an application using Expo, used Webpack to package the files required by a React Native WebView component, and then used gulp to automate a build and publishing process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*Yq5UWxcAFLNwVVR1GM7lJA.png" /><figcaption>Gulp is going to take us there and bring us back</figcaption></figure><h4>Design</h4><p>This post assumes some familiarity with Expo, Webpack, Gulp and NPM so I’m only going to discuss the process required to go from an Expo project to published NPM package. This is a multiple step process:</p><ol><li>Use Expo to create an application containing the functionality you wish to publish</li><li>Separate that functionality into a separate component within the project</li><li>Use a Gulp task to automate the packaging and NPM publishing process.</li></ol><p><strong>Creating an application with Expo</strong></p><p>I previously discussed the use of react-native webviews to incorporate plain JavaScript functionality into a react-native application in my four part series “Accepting Payments in a React Native App”. In particular, part four: <a href="https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-4-cb4f7c02c193">Building the Payment Client Using React Native and React</a> shows that using a Webpack pipeline to compile React results in a project that can be imported into a React-Native webview. Basically, as long as your pipeline delivers an html file that the webview can use as its source, you should have a working Expo project that can be run via the Expo XDE.</p><p>That project used Webpack to create a “dist” folder containing an HTML file and the associated JavaScript and CSS files needed to display the React Component that encapsulated the JavaScript library that I was attempting to run. For the above referenced project project, I created a WebView that used Braintree’s payment library.</p><p>However, an unanticipated and very ugly problem revealed itself when I finally attempted to run the project after publishing it to Expo; the HTML file (and it’s JavaScript and CSS files) required by the WebView was not packaged for publication. That’s because, at the time I am writing this article, Expo is only capable of bundling certain types of files with standalone applications. This limitation is discussed as part of the asset bundling guide in their <a href="https://docs.expo.io/versions/latest/guides/offline-support.html">offline support features</a>. However, I would not be surprised if Expo got around to including offline support for HTML, CSS, and JavaScript files at some point. Once they do, then a significant portion of this post will be a “moo” point…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*sSQOZMKTlx5Vo7h2." /><figcaption>Friends, creating unrealistic housing expectations for millions</figcaption></figure><p>This was a problem because the project would not work when published. It only worked in the development environment on the local computer. And without publication there is no demo project, and without a demo project there is not NPM package, and with no NPM package there is no glory!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*7aJ-w5arNSU79xL60zmrpg.png" /><figcaption>Or infamy, you know how the Internet is.</figcaption></figure><p>Predictably, this issue continued I published the package to NPM and used it in another project. The component in the NPM package itself contained a WebView that I had anticipated would be able to access the index.html file that was also located in the same NPM package. Unfortunately, that was not the case. The WebView rendered; however, it was not able to access the HTML file that was literally just a directory away.</p><p><strong><em>Update (16 Feb 2018)</em></strong></p><p><em>Expo SDK 25’s asset bundling provides support for including CSS, HTML, and JavaScript files in a published package. This means that the upload technique described below shouldn’t be necessary if you are using that version or newer. You can learn more about Expo asset bundling </em><a href="https://blog.expo.io/expo-sdk-v25-0-0-is-now-available-714d10a8c3f7"><em>here</em></a><em>. Now back to the original content.</em></p><p><strong><em>Update (2 Mar 2018)</em></strong></p><p><em>It looks like the Expo/React-Native ecosystem isn’t quite ready to bundle JavaScript files into published packages. My exploits trying to do this are documented in </em><a href="https://forums.expo.io/t/what-is-path-to-location-of-files-bundled-with-assetbundlepatterns-in-sdk-v25/7311/11"><em>this thread on the Expo forums</em></a><em>. I hope to find an alternative to the work-around described below, and will publish a new article when I do.</em></p><p><strong>To summarize</strong>, a WebView with a source=require(‘./dist/index.html’) when “./dist/index.html” was in the same package wasn’t displaying anything. This problem is discussed more in depth in this <a href="https://github.com/facebook/react-native/issues/505">GitHub issue</a>.</p><p>In addition to the work-arounds listed in the issue tracker, Expo form user <a href="https://forums.expo.io/t/problem-with-webview-after-exp-publish/3859/4">burak</a> proposed the technique of uploading the necessary HTML, JS, and CSS files to the Internet and then download them to the mobile for use in the WebView. This is the technique I chose to follow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*kDke_1xKh7zcaTWmdF9eJA.gif" /></figure><p>An online repository or <a href="https://www.incapsula.com/cdn-guide/what-is-cdn-how-it-works.html">CDN</a> will suffice for this as long as you have a URL that points to the file(s). Then, those files can be downloaded to the local device the first time the component containing the WebView is mounted, or if a version change is detected. This process is defined by the following steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcf85c10bc5641cc83bd0afcfff0eef6/href">https://medium.com/media/bcf85c10bc5641cc83bd0afcfff0eef6/href</a></iframe><p>At this point, the index.html file and its dependencies are available for the WebView to display.</p><p>This functionality is encapsulated in the versioned-file-downloader <a href="https://www.npmjs.com/package/versioned-file-downloader">NPM package</a>. The repo for that package can be found <a href="https://github.com/reggie3/versioned-file-downloader">here</a>. This package uses the <a href="https://docs.expo.io/versions/latest/sdk/filesystem.html">Expo.FileSystem API</a> to download files to the device’s document directory. It looks for and downloads files into a folder structure that looks like this:</p><pre>[FileSystem document directory]/ [package name]/[version]/</pre><p>Once the file(s) have been successfully downloaded, they can be accessed using the WebView’s “source” prop like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fd08a02c2d5f7ebcb4fb8fb096bf12f/href">https://medium.com/media/7fd08a02c2d5f7ebcb4fb8fb096bf12f/href</a></iframe><p>At this point we have a way to obtain and display the files required by the WebView and the current situation can be summarized as follows…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*8aX3LemI8Xh8AueLsS9gqA.png" /><figcaption>Yes, its an old meme, but it checks out</figcaption></figure><p><strong>Separating the Package from the Expo Project</strong></p><p>Before extracting the files for publication, there needs to be a clean division between what will be the NPM package and the Expo application itself. The goal is to separate anything that might be reusable and place it into a file that will be imported. The desired goal is to have a file that exports a function that can be imported by another file. This function is then called with some number of arguments. Upon completion, it may or may not return something back to whatever called it initially.</p><p>Basically, create a function, throw it in a file, export it, and you have the start of a package.</p><p><strong>Extracting the Package</strong></p><p>There are a few distinct steps that have to be performed in order to extract the necessary files from the Expo Project and publish the NPM package:</p><ol><li>Webpack must be run whenever the files HTML, CSS, or JavaScript files used by the Webview are changed in order to create the updated files for use by the WebView</li><li>The version number in package.json must be increased prior to publishing the package</li><li>A push to GitHub is required whenever we want to update the files that the WebView uses so that the WebView has access to the most up to date files</li><li>Most insidiously, there are two changes that must be made to the “package.json” file and then reverted. Keep in mind that this file is used by Expo and NPM.</li><li>First is the “main” parameter in package.json. Remember, the files that will become an NPM package sit inside an Expo project. Expo projects require main to be equal to “node_modules/expo/AppEntry.js” in order to run as an Expo project. However, that won’t work for an NPM package which must be a JavaScript file contained in the package, and typically is set to “index.js”. This means that the “main” value must change prior to NPM publishing and then change again prior to running the Expo application that encompasses the package.</li><li>Next, the dependencies must be changed. Expo projects require an expo, react, and a special react-native dependency. Additionally, this WebView technique requires a react-dom dependency. However, none of those are requirements for the NPM package. In fact, I encountered breaking errors when I attempted to run the project with an NPM package that included those extraneous dependencies. This means that the dependency list must be different when publishing and running the Expo project</li></ol><p><strong>The bottom line</strong> is that the “main” and “dependencies” values in package.json must be one thing when publishing and something different when running the application. Since I still want to be able to run the application as an Expo project, I will have the change the values for main and dependencies to the appropriate values for publishing and then back to the correct values for an Expo project.</p><p><strong>Automation with Gulp</strong></p><p>Fortunately, these steps are predictable and repeatable, which means they are the perfect fit for a task runner like Gulp. A suitable gulpfile can be <a href="https://github.com/reggie3/expo-to-npm-gulpfile">found at this repo</a>. The primary tasks are “dev” and “prod” which can be run like any gulp task: “gulp dev” or “gulp prod”. The gulp dev task is show below that performs all those steps is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe80e3d450b77eeda3535faeb7fe7d1/href">https://medium.com/media/8fe80e3d450b77eeda3535faeb7fe7d1/href</a></iframe><p>The process accomplishes the cycle shown in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*tLABR4V6_e50Q81tWf57jw.png" /></figure><p>Running the gulp tasks results in a published NPM package suitable for use in other projects while still leaving a project suitable for running as an Expo project. Gulp is not the conductor of the publication workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*JNjN5UEXw_zyQWOUEHyJcw.gif" /></figure><h4>Conclusion</h4><p>As previously stated, this article is not meant to be a full blown explanation of how to use all the tools it mentions. Each of the tools has significant amounts of documentation on their usage that I’d recommend familiarizing yourself with if you have questions.</p><p>Instead, this article is intended to describe a technique of combining multiple tools to achieve the desired goal; a published NPM package.</p><p>Expo provides the ability to quickly create and share mobile applications using React Native. React Native provides a WebView component that lets us display HTML, CSS, and JavaScript content inside our application. Webpack automates the build process and can create the necessary files for the WebView component to display. And finally, Gulp automates the processes that are required to have a working Expo project and a publishable NPM package.</p><p><em>Reginald Johnson is a 20+ year military veteran who is blogging, creating, and teaching his way through his transition into software development. You can follow him on Twitter at @reginald3, or connect with him on LinkedIn at </em><a href="https://www.linkedin.com/in/reggie3/"><em>https://www.linkedin.com/in/reggie3/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f66d9edef4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-training/using-expo-gulp-and-webpack-to-create-and-publish-react-components-to-npm-2f66d9edef4c">Using Expo, Gulp, and Webpack to Create and Publish React Components to NPM</a> was originally published in <a href="https://medium.com/react-native-training">React Native Training</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A React Native Sound Recorder and Player NPM Package]]></title>
            <link>https://medium.com/react-native-training/a-react-native-sound-recorder-and-player-npm-package-a5f9b3fc7eed?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5f9b3fc7eed</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Fri, 05 Jan 2018 20:31:42 GMT</pubDate>
            <atom:updated>2018-05-30T15:02:54.002Z</atom:updated>
            <content:encoded><![CDATA[<h4>Breaking up Project Functionality into Separate NPM Packages</h4><h4>May 2018 Update</h4><p>Now that I have learned more about using React Native and creating friendlier NPM packages, I’ve made some significant updates to the package detailed in this article.</p><p>The package is now called react-audio-player-recorder-no-linking. I chose this new name to emphasize that it includes separate Recorder and Player components vice just a single SoundRecorder component, and that the package does not require linking to native code. This lack of linking maintains the package’s safety to use with Expo.</p><p>Additionally, all UI (buttons, badges, etc) has been pulled out of the actually Player and Recorder components and are available as imports. The imported UI items can be provided to the Player and Recorder as props. More importantly, the user can provide their own UI items as props. This means the user can theme the components any way they want.</p><p>Finally, the GitHub repository has been change to reflect the new name. The package can now be found at <a href="https://github.com/reggie3/react-native-audio-player-recorder-no-linking">https://github.com/reggie3/react-native-audio-player-recorder-no-linking</a>.</p><p>All these changes result in significantly improved flexibility and functionality. However, it also means that the components mentioned in the article and the relevant props provided to components have changed significantly. Those changes should be covered by the readme.md file available in the GitHub repo mentioned above.</p><h4>Introduction</h4><p>A project that I’ve diligently worked on for several months had finally gotten to a point that I was ready to bolt in yet another piece of functionality. It was time to give my creation the ability to record and play back sound.</p><p>My project is built using <a href="https://expo.io/">expo.io</a>, and they provide <a href="https://docs.expo.io/versions/latest/sdk/audio.html">documentation</a> of their Audio API along with a <a href="https://github.com/expo/audio-recording-example">Github repo</a> containing an example project that can be <a href="https://expo.io/@community/record">run</a> using the expo app. With such a good foundation to work with, I diligently and methodically began to include the code from the example into my own project.</p><p>This approach was successful, but I began to realize that I was adding a significant piece of mostly independent functionality to an existing project at the cost of flexibility and testability. Flexibility would suffer because I would have to repeat the process if I wanted to add the same capability to a new project. Testability would deteriorate because I was already integrating this functionality in a non-functional manner by connecting it to my redux store and implementing every other good idea that popped in my head.</p><p>So, why not pull this capability out as an NPM package that would take some inputs, and provide me the audio clip information that I wanted? This would provide the testability that I desired, give me a ton of reuseability, and scope my work in by minimizing the number of input and output points that would connect to the final product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*yC15pk29C7YIXsJzMDR-bA.gif" /><figcaption>The final product</figcaption></figure><h4>Design</h4><p>First, I determined that all I really needed was a screen (or page, or whatever other metaphor you prefer) on which the user could push a button to start recording sound, push a button to stop recording sound, and then play, pause, stop, and replay said sound.</p><p>This UI would interact with the sample code provided in the expo.io documentation to actually performed the recording and playback.</p><p>Additionally, the UI would also require buttons to reset the audio clip in case the user wasn’t satisfied with it, and a button to do something when the user completed their task. This could be as simple as going back to the previous page. This leads into the final requirement; the package should return something allowing the calling component to get information about the completed sound clip. Since the expo documentation shows that a successful recording results in a file saved to the device, my goal would be to pass relevant file information back to the calling parent component via a callback function.</p><h4>Implementation</h4><p>Beginning with those desired ends in mind, I started creating the foundation of my NPM package. Thanks to previous experience with my <a href="https://github.com/reggie3/react-native-webview-braintree">react-native-webview-braintree</a> and <a href="https://github.com/reggie3/react-native-webview-quilljs">react-native-webview-quilljs</a> projects, I developed the following process for creating a project ready to turn into an NPM package.</p><p>First I created a blank project in Expo. This results in a working application along with an App.js file containing a react-native component called App to act as the “frame” for the component to be published. The App component renders the SoundRecorder component that will be the published product. One upside to using this technique is that I’ll get a working application out of it that can be easily shared via the expo client.</p><p>The App component also passes the relevant props to the SoundRecorder component like so.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97f368f2661f33d284d46d9b57ecea2d/href">https://medium.com/media/97f368f2661f33d284d46d9b57ecea2d/href</a></iframe><p>The list of props shown above is not comprehensive; see the documentation <a href="https://github.com/reggie3/react-native-sound-recorder-no-native">here</a> for the full list of available props.</p><p>The only required prop is a callback function that receives the recorded sound information from SoundRecorder. In addition to receiving the sound information, the callback also provides the ability for the calling component (in this case App) to perform some follow on action with the information that SoundRecorder provides. This action could be navigating to a different page, writing to a redux store, a UI change, etc. The great part is that SoundRecorder doesn’t care; its job is complete once it provides the sound file information to the calling component. Once the SoundRecorder completes its task, it executes the following onComplete callback function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e250dcf54be72be44ea4b98286445c2e/href">https://medium.com/media/e250dcf54be72be44ea4b98286445c2e/href</a></iframe><p>As previously stated, I heavily relied on the expo.io Audio SDK example application. The repository for that location is located on GitHub <a href="https://github.com/expo/audio-recording-example">here</a>. I added some customization to dictate the status of the record and play buttons. This involved setting component state variables to mandate conditional rendering of said buttons.</p><p>Finally, the ability to press a button and reset the recording was added as a convenience, as well as a button to finish the process so that the passed callback function can be called.</p><p>The final result can be seen below. Unfortunately, one limitation of the audio SDK means that I can’t record the sound of the app recording sound, so you’ll have to take my word that it does actually capture and playback audio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*yC15pk29C7YIXsJzMDR-bA.gif" /><figcaption>Application in action</figcaption></figure><h4>Conclusion</h4><p>Overall, I like the idea of separating out monolithic functionality into a separate NPM package. It supports separation of concerns and testability. It also helps me eat the elephant one bite at a time.</p><p>It also presents the opportunity to contribute to and receive input from a community of user to potentially create a better product.</p><p>The final results of this project are hosted on in the <a href="https://github.com/reggie3/react-native-sound-recorder-no-native">react-native-sound-recorder-no-native</a> repo on GitHub which also contains NPM installation and usage instructions.</p><p>You can scan the following QR code to run this app if you have the expo.io client installed on your Android or iOS device:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*CpKddZa-RnPNBWfEVMvX0Q.png" /><figcaption>Try this project for yourself</figcaption></figure><p>This component was successfully tested on an Android and iPhone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5f9b3fc7eed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-training/a-react-native-sound-recorder-and-player-npm-package-a5f9b3fc7eed">A React Native Sound Recorder and Player NPM Package</a> was originally published in <a href="https://medium.com/react-native-training">React Native Training</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing react-native-webview-quilljs]]></title>
            <link>https://medium.com/@reginald.johnson/introducing-react-native-webview-quilljs-e6ca0d13c45c?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6ca0d13c45c</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Sun, 19 Nov 2017 23:36:35 GMT</pubDate>
            <atom:updated>2017-11-19T23:43:54.314Z</atom:updated>
            <content:encoded><![CDATA[<p>A Quill.js Component for React-Native Applications with no Native Code</p><h4>Introduction</h4><p>In the process of finding a text editor capable of creating richly styled text for one of my projects, I stumbled upon <a href="https://github.com/quilljs/quill">Quill.js</a>, “… a modern rich text editor built for compatibility and extensibility”. Based on this statement, it seemed perfect for my needs. I also came across <a href="https://github.com/quilljs/quill">react-quill</a>, a React Quill.js component, which wraps vanilla Quill.js for use in React web applications.</p><p>Thanks to my past experience developing the <a href="https://www.npmjs.com/package/react-native-webview-braintree">react-native-webview-braintree</a> component, I already knew that wrapping React components in a React-Native webview for use in React-Native apps was a viable option for projects that needed to avoid using native code; for example, projects made using <a href="https://expo.io/">Expo.io</a>.</p><p>The react-native-webview-quilljs component uses the same techniques discussed in <a href="https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-4-cb4f7c02c193">this post</a> in order to make Babel compile the react-quill component and an index file into an index.html file to be imported by a <a href="https://github.com/R1ZZU/react-native-webview-messaging">react-native-webview-messaging</a> &lt;WebView/&gt; component. The react-native-webview-messaging component simplifies communication between the react-quill component and it’s wrapping React Native webview.</p><p>Both the <a href="https://github.com/reggie3/react-native-webview-quilljs">github </a>and <a href="https://www.npmjs.com/package/react-native-webview-quilljs">npm </a>pages contain instructions on how to use the component. Also, in addition to the actual project, I create a <a href="https://github.com/reggie3/react-native-webview-quilljs-test-app">test application</a> to demonstrate the usage of the editor and view components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*Lx39uBk3Hvl5FUZ-qWz0cw.gif" /></figure><h4>Issues</h4><p>To note, there is one issue I continue to encounter in using WebViews to wrap React components or even vanilla JS; the wrapped item must be loaded. This is not an instantaneous process, and can take several seconds in some cases. This component shows an activity indicator during the loading process. However, it would be very desirous to preload or stage the component in some way that it is immediately available for use when called upon. Hopefully, someone reading this has some suggestions that they can post in the comments.</p><h4>Conclusion</h4><p>I hope whoever uses this component finds it useful, and I would love to hear back from you if you do. I’d also like to hear back from you if you can suggest any improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6ca0d13c45c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accepting Payments in a React Native App (Part 4)]]></title>
            <link>https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-4-cb4f7c02c193?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb4f7c02c193</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[expo]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Thu, 05 Oct 2017 12:40:09 GMT</pubDate>
            <atom:updated>2018-01-07T22:24:47.144Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Building the Payment Client Using React Native and React</strong></h4><p><strong>Background</strong></p><p>This is the fourth and final article in a series of posts about integrating Braintree payments into a JavaScript only (no native code) React Native mobile application. The GitHub repository for this project is located <a href="https://github.com/reggie3/payment-example-client/tree/braintree_react_component">here</a>.</p><p>Additionally, this project is available as the <a href="https://www.npmjs.com/package/react-native-webview-braintree">react-native-webview-braintree</a> npm package for you to use in your own projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*K7WONvKknlQ7bDUwh_nkUw.png" /><figcaption>Part 3: “The Reactining:</figcaption></figure><p>This article discusses building the final version of the client using React Native, React, JavaScript, and the version 3 of the <a href="https://developers.braintreepayments.com/start/hello-client/javascript/v3">Braintree JavaScript SDK</a>. Since this technique builds on the previous articles in this series this post is going to be relatively short. It also means it will seem incomplete if you haven’t read the other articles prior to this one.</p><p>Those other articles can be found here:</p><p>1. <a href="https://medium.com/@reginald.johnson/accepting-payments-in-a-react-native-app-part-1-9cb09a271f59">Project Introduction</a>. This section may not sound like much, but it’s a good explanation on how everything will fit together.</p><p>2. <a href="https://medium.com/@reginald.johnson/accepting-payments-in-a-react-native-app-part-2-b8927487ea9c">Application Server</a> using Amazon Web Services. This portion explains how to interact with Braintree’s server in a secure manner.</p><p>3. <a href="https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-3-c22828ecab13">Initial Version Using Vanilla-JavaScript</a> discusses building an application that can receive payments.</p><p>4. <a href="https://medium.com/@reginald.johnson/accepting-payments-in-a-react-native-app-part-4-cb4f7c02c193">React Component Based Version</a> is about putting React inside a React Native application.</p><p><strong>Introduction</strong></p><p>In part 3 of this series, I presented design and implementation of an application that displayed a Braintree payment UI to the user and allowed them to enter their credit card information to make a purchase. The implementation was done completely in JavaScript. This time I will use React to create a webpage containing the payment UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*HhACpBNTbbDvSN4q.jpg" /><figcaption>Lets do this!!</figcaption></figure><p><strong>Design</strong></p><p>The biggest difference between this design and the one shown in the previous article is the use of React to create the HTML and JavaScript that is presented in the &lt;WebView/&gt; component.</p><p>Instead of using webpack to package and bundle JavaScript, I used it to package and bundle React JSX. This involved the typical React pattern of creating an HTML file with a &lt;div&gt; element that serves as the “target” to place the compiled React JSX into. This creates a bundle.js file which is compiled into an index.html file which is then imported by the React &lt;WebView/&gt; component for rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*lzz6HA1NpYE0XRzLb3ncVg.png" /><figcaption>From React to React Native Webview</figcaption></figure><p>So, one may ask, why go through the trouble of even using React inside a React Native webview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*IOVYyonnFyUYJ2BM.jpg" /><figcaption>I promise, I’m not using React just because of this</figcaption></figure><p>For one, I did it because I thought that taking advantage of the reactive nature of React in both the React and React Native portions of my project would lead to cleaner, understandable, and more maintainable code; some of the primary reasons for using React in the first place. Additionally, it meant that I could follow the same pattern for creating both components. Since this version of the project uses <a href="https://github.com/R1ZZU/react-native-webview-messaging">react-native-webview-messaging</a> just like the previous version, I could set up listeners and fire messages same way both the React and React Native sides.</p><p>This change represents the most significant differences between this and previous versions of this article.</p><h4>Implementation</h4><p>Since I’m assuming that you’ve read my previous article in this series, I will be focusing on the React code and packaging it for use by react-native-webview-messaging.</p><p>Once again, I relied on webpack to convert the JSX into HTML that my &lt;WebView&gt; could use as it’s source prop.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d97262cd4903850724750d81af75e942/href">https://medium.com/media/d97262cd4903850724750d81af75e942/href</a></iframe><p>Again, it’s very similar to my previous version. The most import part is line 29 which tells babel to transpile any JSX it finds into JS. Line 6 tells babel to begin working in the braintreeReact.js file which contains the React code, and line 41 tells babel which html file to combine with braintreeReact.js to create the final index.js that will be imported by the react-native-messaging-webview.</p><p>Next, I’ll walk through the code in braintreeReact.js. Don’t worry if it seems like a lot of code. For one thing, I like white-space. Additionally, I’ll go though the important parts line by line below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ac5d604f5fb5ac55c662894eaa84514/href">https://medium.com/media/6ac5d604f5fb5ac55c662894eaa84514/href</a></iframe><p>On lines 3 and 4 I manually import a downloaded version of React. I encountered errors attempting to use the version of React in my node modules directory. I attributed this to version conflicts due to using Expo, which has it’s own specific React dependencies.</p><p>Line 8 imports glamorous which I used for styling in lines 12 to 36.</p><p>The PrintData function on line 40 is used for debugging. Debugging a &lt;WebView/&gt; can be difficult since you can’t rely on console logs and breakpoints. To get around this, the PrintData function prints passed objects and strings to a &lt;div&gt; element in the index.html.</p><p>Line 52 is where the actual BraintreeHTML component starts. It initially has one state variable, currentPaymentStatus which is used to conditionally render feedback to the user throughout the payment process.</p><p>The componentDidMount function provides an opportunity to register listeners for interaction with the parent component.</p><p>The createCreditCardUI function does exactly the same thing as before. It places the Braintree UI inside of a &lt;div&gt; element on the index.html. It then saves the Braintree instance object in the component’s state for later use.</p><p>Next, the handler handleSubmitPurchaseButtonClicked function does exactly what it’s name suggests. It is fired once the user clicks the button that submits purchase information, at which point it sets the currentPayementStatus state variable to “PAYMENT_PENDING” and emits a “RETRIEVE_NONCE_PENDING” message to the parent so that it can display an &lt;ActivityIndicator/&gt; component. It then requests a nonce using the Braintree API’s requestPaymentMethod of and submits either a message indicating success or failure to the parent component.</p><p>Several things are happening inside the render function. First, the components created with glamorous are used to format individual elements. More importantly, renderIf from the <a href="https://github.com/ajwhite/render-if">render-if</a> library is used to conditionally render either the payment UI, a message thanking the user for their purchase, or a message informing the user that their was a problem with their payment. The value of the component state variable currentPaymentStatus determines which of the three are rendered.</p><h4>Conclusion</h4><p>This post shows that it is possible to use React to create the content of a React Native &lt;WebView/&gt; . It also demonstrated a method to communicate between the &lt;WebView/&gt; and the HTML created by the React. Additionally, it demonstrated a technique to show useful debugging information from the HTML which itself has no access to the console or the debugger.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb4f7c02c193" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-4-cb4f7c02c193">Accepting Payments in a React Native App (Part 4)</a> was originally published in <a href="https://medium.com/react-native-training">React Native Training</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accepting Payments in a React Native App (Part 3)]]></title>
            <link>https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-3-c22828ecab13?source=rss-a7da9e7dc419------2</link>
            <guid isPermaLink="false">https://medium.com/p/c22828ecab13</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Reginald Johnson]]></dc:creator>
            <pubDate>Mon, 25 Sep 2017 20:40:24 GMT</pubDate>
            <atom:updated>2017-10-05T12:50:01.413Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building the Payment Client Using React Native and JavaScript</h4><h4>Background</h4><p>This article is part 3 of a series on integrating Braintree payments into a JavaScript only (no native code) React Native mobile application. The GitHub repository for this project is located <a href="https://github.com/reggie3/payment-example-client/tree/braintree_javascript">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*-uM98iYJS9p8tzqa6MmorA.png" /><figcaption>This is where we are in the movie</figcaption></figure><p>This article will cover building the first version of the client using React Native, JavaScript, and the version 3 of the <a href="https://developers.braintreepayments.com/start/hello-client/javascript/v3">Braintree JavaScript SDK</a>.</p><p>The other articles can be found here:</p><p>1. <a href="https://medium.com/@reginald.johnson/accepting-payments-in-a-react-native-app-part-1-9cb09a271f59">Project Introduction</a>. This section may not sound like much, but it’s a good explanation on how everything will fit together.</p><p>2. <a href="https://medium.com/@reginald.johnson/accepting-payments-in-a-react-native-app-part-2-b8927487ea9c">Application Server</a> using Amazon Web Services. This portion explains how to interact with Braintree’s server in a secure manner.</p><p>3. <a href="https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-3-c22828ecab13">Initial Version Using Vanilla-JavaScript</a> discusses building an application that can receive payments.</p><p>4. <a href="https://medium.com/@reginald.johnson/accepting-payments-in-a-react-native-app-part-4-cb4f7c02c193">React Component Based Version</a> is about putting React inside a React Native application.</p><h4>Introduction</h4><p>In part 2 of this series, I presented the my of the Braintree payment flow:</p><ol><li>Mobile Application (the app) gets client token from our server</li><li>Server gets token from Braintree and sends it back to our mobile application</li><li>App uses that token in order to request a payment form UI element from Braintree</li><li>Braintree provides a secure UI component for the mobile application to display</li><li>The app displays that UI component to the user so that user can input payment information and commit the actual purchase at which point the payment information is sent to Braintree</li><li>Braintree then provides a nonce (think of it as an authorization ticket) to the app that basically says “Okay, that user is good to make this purchase. Give this nonce to your server along with the purchase amount.</li><li>The app then does just that. It sends the nonce to your server along with purchase information such as price, user name, etc.</li><li>Your server’s primary step here is to send the nonce and sales information to Braintree which will in turn transfer money if the nonce is legitimate. It’s at this point that your serve will also record transaction data to a database, but that really has nothing to do with Braintree.</li></ol><p>This article presents the design and creation of of an application that does steps 1, 3, 5, and 7.</p><h4>Design</h4><p>The mobile application will require a UI to interact with the user. It will also need to retrieve the client token from and post the purchase information to the application server and Braintree’s server.</p><p>The UI will will use the Braintree Drop-in UI component to provide the user with a secure form to input payment information. However, the catch is that the Drop-in UI interacts with the DOM. It requires a DOM &lt;div&gt; element to place it’s own UI in. This means a webpage is required since one can’t just stick a &lt;div&gt; into a RN &lt;View&gt; element. While I can’t force a &lt;div&gt; into a &lt;View&gt; , I can put an RN &lt;WebView&gt; into a &lt;View&gt;. And since the &lt;WebView&gt; is really just a browser, a &lt;div&gt; is an acceptable child element. The bottom line is that the mobile app will have a &lt;View&gt; that contains a &lt;WebView&gt; component that will encompass a &lt;div&gt; that the Drop-in UI will place the payment form in.</p><p>The &lt;WebView&gt;is capable of accepting and rendering an HTML file that is passed to it as prop. For ease of use, I’ll keep the JS separate from the HTML and use webpack to create a bundled file to pass to the &lt;WebView&gt; for rendering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*Oqv1lntqpe8GZ_PQQBiLuA.png" /><figcaption>webpack bundles a template html file and its imported JavaScript to create an indexl.html to be used by RN webview</figcaption></figure><p>Since the &lt;WebView&gt;&#39;s parent element will need to retrieve the client token upon mounting, I need some way to communicate that token to the Drop-in UI so that it can be used to request a nonce from the server.</p><p>It would be just as valid to avoid some &lt;WebView&gt;to RN communication by retrieving the client token in the JS file that contains the Drop-in code. However, there will have to be some communication between &lt;WebView&gt;and RN at some point. For example, we have to display purchase success or failure to the user. The communication problem can’t be avoided, so its best to get that out of the way early. Also, this separation of concerns will allow me to create a standalone component at some point.</p><p>The following diagram depicts the flow and component responsibilities described above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*WwqzIkMIEdx2LW69HypUCg.png" /><figcaption>Data flow between React Native parent component and it’s child webview</figcaption></figure><h4>Implementation</h4><p>A picture is worth a thousand words, and it’s the best way to describe the relationships between components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*34vpdxjkhKmJWI8DuONpZA.png" /></figure><p>The implementation starts off with a parent component in the BraintreePaymentScreen.js. This component is responsible for obtaining the client token from Braintree’s servers. It displays an &lt;ActivityIndiator/&gt; component until while the client token request is being processed. Once the token is received, it next passes the client token to the &lt;BraintreeWebView/&gt; component and displays that same component, while simultaneously hiding the &lt;ActivityIndicator/&gt; component. In addition to the client token, the &lt;BraintreeWebView/&gt; is also passed three other props</p><p>nonceObtainedCallback: a function that is executed one the nonce is received, which allows the BraintreePaymentScreen to make a purchase call to the server</p><p>paymentAPIResponse: holds the pending, and success or failure state of the response from Braintree once the nonce is sent to their servers. This allows us to pass that information to the webview and display feedback to the user</p><p>navigationBackCallback: an optional callback that is used to navigate to a different screen. A button on the webview activates this callback allowing the user to navigate to away from the webview to a screen of our choice</p><p>The &lt;BrainTreeWebView/&gt; component is a a custom component whose primary functions are to render a <a href="https://github.com/R1ZZU/react-native-webview-messaging">react-native-webview-messaging</a> (rnwm) &lt;WebView/&gt; component that displays the a web page as its source, and to implement communications between that web page and BraintreePaymentScreen. I decided to use the rnwm component because it greatly simplified communication between the HTML rendered inside the webview and the BraintreePaymentScreen. All that is required is setting up listeners in the rnwm &lt;WebView&gt; and inside the JavaScript of the HTML that it renders. Then those two items can send events, strings, and even JSON objects to each other.</p><p>The use of rnwm’s &lt;WebView/&gt; component is similar to the standard React Native &lt;WebView/&gt;. It requires a source of HTML to display. In this case, I chose to do this by using a require statement. The require statement imports the index.html file created by webpack for use as the value for the &lt;WebView/&gt; source property.</p><p>The code for BraintreePayementWebview is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acd415a84418fe7d40b4a8d8a393dfd7/href">https://medium.com/media/acd415a84418fe7d40b4a8d8a393dfd7/href</a></iframe><p>I’ll be the first to admit that my webpack skills are probably not as strong as they should be. Fortunately, rnwm has an <a href="https://github.com/R1ZZU/react-native-webview-messaging/tree/master/examples/expo">example </a>that demonstrates how to combine an HTML file with JavaScript to create a bundled HTML file that can be included in the &lt;WebView/&gt; component. I recommend following the techniques shown in the example.</p><p>The index.js file contains all the JavaScript required to actually display the drop-in UI, retrieve a nonce from the Braintree server’s, send that nonce back to the parent component, and display payment processing feedback to the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50d0d7a9f6cb38893e0f062ddbb50588/href">https://medium.com/media/50d0d7a9f6cb38893e0f062ddbb50588/href</a></iframe><p>The biggest problem I’ve encountered while using these techniques is that any changes made to the index.js file break Expo’s hot reloading. This means that every change requires repackaging the entire project. I hope that somebody reading this article can help me figure out a way to fix or avoid this issue. Please leave a comment below.</p><p><strong>Conclusion</strong></p><p>That’s it. In this article I demonstrated a non-native, purely JavaScript technique to display Braintree’s Drop-In UI to make payments in a React Native application.</p><p>In the next article in this series, I will replace the vanilla JS in index.js with React. I think you know what that means…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/0*HhACpBNTbbDvSN4q.jpg" /><figcaption>This one just wrote itself</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c22828ecab13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/react-native-training/accepting-payments-in-a-react-native-app-part-3-c22828ecab13">Accepting Payments in a React Native App (Part 3)</a> was originally published in <a href="https://medium.com/react-native-training">React Native Training</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>