Tutorials on React Native

Learn about React Native from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

Create a React Native Login

Here's a new YouTube tutorial for quickly getting started developing mobile apps with React Native . React Native helps you start developing Android and iOS apps without wasting any time learning the native programming languages for those platforms. The challenge is that many project examples assume a lot of knowledge and take plenty of time to work through. This tutorial helps complete beginners dive right in and start building an actual practical, featureful, React Native app. This tutorial is taught by my friend and newline instructor Tony Przybyl. Tony is a software engineer focused on React and React Native. He comes from a fullstack background and is the creator of the open source React Native libraries NativeForms , ReactNative Market , NativeSlides , and React Riddle . In the tutorial, Tony starts you from absolute basics and teaches you the fundamental React Native skills you will need to start developing your own ambitious apps. The tutorial will show you: If you want to learn more React Native concepts and techniques, you can take a look at Tony's full course: The newline Guide to Creating a React Native Login . The course simplifies learning React Native by hyper focusing on an end to end project that is simple enough for beginners yet teaches all the fundamentals so you can create production-ready React Native apps of your own.

Thumbnail Image of Tutorial Create a React Native Login

Building a Smooth Image Carousel with FlatList in React Native

Have you ever noticed how often image (and card) carousels appear within mobile applications? Carousels consolidate items within a single horizontally rotating widget. Users can scroll through items by dragging across right or left to preview subsequent or previous items. Displaying items this way preserves vertical screen real estate, and therefore, allows users to have quicker access to the bottom of the view without scrolling down endlessly. React Native comes with several built-in components, such as <FlatList /> and <ScrollView /> , that can be used to quickly implement an image carousel. Unlike ScrollView /> , <FlatList /> renders child components lazily. Since <FlatList /> only stores in memory the items that are about to appear (and removes from memory the items that disappear offscreen), this results in better performance from reduced memory consumption and processing resources. Below, I'm going to show you how to build an image carousel with React Native's <FlatList /> core component. Users will be able to scroll through the items by dragging along the items: Or by clicking an arrow button to move to the next or previous item: To get started, initialize a new React Native project using the TypeScript template : At the root of the project directory, create two new directories: Delete the contents of the App.tsx file, and replace it with the following: ( App.tsx ) The image carousel will showcase six high-quality Unsplash images of various flowers. At a minimum, each item of the carousel must have a unique ID ( id ), a URI to its corresponding image's location ( uri ) and a title for labeling the image ( title ). To enforce these properties, create a definition file to globally expose the ImageCarouselItem interface. ( types/index.d.ts ) Note : Inside of the tsconfig.json file, set the typeRoots compiler option to ["./types"] . Create a new file named ImageCarousel.tsx under the src/components directory: Inside of the src/components/IamgeCarousel.tsx file, define a new functional component named ImageCarousel that accepts the prop data : ( src/components/ImageCarousel.tsx ) data contains the items that will be rendered by the <FlatList /> component. The <FlatList /> component provides a virtualized list that is highly customizable via its many props. Coincidentally, it inherits most of these props from the <ScrollView /> component. At a minimum, the <FlatList /> component requires two props: Let's render a simple horizontal carousel using the least number of props possible. ( src/components/ImageCarousel.tsx ) Each item follows the same layout: a square-shaped cover image with its title overlaid above and positioned at the lower-right corner. Specify the horizontal prop to tell the <FlatList /> component to arrange the items horizontally rather than vertically. Hide the horizontal scroll indicator, and set a keyExtractor function to tell the <FlatList /> component which item property (or set of properties) it can use to track each item for caching and re-ordering purposes. Adjacent items are spaced away from each other by 30px (for each item, 15px of left- and right-margining). If you save these changes and run the React Native project inside of an iOS simulator, then you will see a basic image carousel: In fact, you can scroll through these items by horizontally dragging along them. Let's modify the carousel to snap items in place and translate an item upwards when it approaches the middle of the screen and downwards when it moves towards either edge of the screen. Currently, when the carousel loads the items, the first item begins at the far left end of the screen, not the middle. When you scroll all the way to the last item in the carousel, the last item ends at the far right end of the screen, not the middle. We're going to need two placeholder items, one at the beginning and another at the end of the carousel, to help position the first and last items in the middle of the screen when reaching either end of the carousel. ( src/components/ImageCarousel.tsx ) As we scroll through the items, the item approaching the middle of the screen should be translated upwards to put it front and center as the current item being visited. Inside of renderItem , define an interpolation that maps an item's x-position to its y-translation. ( src/components/ImageCarousel.tsx ) An item appears to move upwards when its y-translation ( CURRENT_ITEM_TRANSLATE_Y ) is smaller compared to other items' y-translations ( CURRENT_ITEM_TRANSLATE_Y * 2 ). This item ( (index - 1) * ITEM_LENGTH ) happens to be the one that appears in the middle of the screen, not the edges. clamp restricts the extrapolation to only within the boundaries of the specific range. For items to snap into place at the end of a scroll action, specify these additional props on the <FlatList /> component. ( src/components/ImageCarousel.tsx ) Putting it altogether... ( src/components/ImageCarousel.tsx ) Reload the application to preview the smooth animations! Let's introduce arrow controls to give users an alternative way to explore the carousel's items. The <FlatList /> component's reference comes with a scrollToIndex method, which tells the component which item in the carousel to scroll to based on the specified index. All we need to do is track the index of the item currently in the view. Increment it when we scroll right and decrement it when we scroll left. To figure out which item is currently in the view, we need to specify these two props on the <FlatList /> component: ( src/components/ImageCarousel.tsx ) For an item to be considered as currently in the view, it must be 100% visible to the user (no part of it hidden off screen). onViewableItemsChanged calls a handler function whenever the items currently in the view have changed and tells us which items are now 100% visible in the view (based on the visibility percent threshold). We'll track the current index via a React ref since we don't need to re-render the component whenever this index changes. ( src/components/ImageCarousel.tsx ) Define the handleOnViewableItemsChanged handler function. This function checks for the item currently in view and sets the ref's value to this item's index value. ( src/components/ImageCarousel.tsx ) Note : The placeholder items are technically 100% in the view when the user moves to the first or last item in the carousel. Therefore, we need to filter out those placeholder items. Note : Wrap the handleOnViewableItemsChanged function in a useCallback hook to avoid the following issue: Now, let's create the arrow controls. Add two flag variables, isNextDisabled and isPrevDisabled , to check whether or not the arrow controls should be disabled or not. For instance, the previous arrow control should be disabled when the current item is the first item in the carousel, and the next arrow control should be disabled when the current item is the last item in the carousel. ( src/components/ImageCarousel.tsx ) Obtain a reference to the <FlatList /> component to access the scrollToIndex method: ( src/components/ImageCarousel.tsx ) Implement the controls' functionality and style them: ( src/components/ImageCarousel.tsx ) For a consistent scrolling motion between adjacent items via the scrollToIndex method, specify the getItemLayout prop on the <FlatList /> component. Since we already know the fixed dimensions of the carousel's items, we should let the <FlatList /> component know these dimensions so that it doesn't need to dynamically measure the items' dimensions and have scrollToIndex always scroll to a target item correctly. ( src/components/ImageCarousel.tsx ) Altogether... ( src/components/ImageCarousel.tsx ) Reload the application. Here's how the carousel should look and behave: For the final version of this project, click this link for the GitHub repository. Try implementing your own image carousel with React Native's <FlatList /> component. For more about building apps with React Native, check out our new course The newline Guide to React Native for JavaScript Developer .

Thumbnail Image of Tutorial Building a Smooth Image Carousel with FlatList in React Native

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

Storyboarding - The right way to build apps

React Native is a platform for developing apps that can be deployed to multiple platforms, including Android and iOS, providing a native experience. In other words, write once, deploy multiple times . This tenet holds true across most aspects of app development. Take, for example, usability testing. In native development, teams would need to test business logic separately on each platform. With React Native, it only needs to be tested once. The code we write using React Native is good to go on both platforms and, in most cases, covers more than 90% of the entire code base. The React Native platform offers a plethora of options. However, knowing which to use and when comes from understanding how those pieces fit together. For example, do you even need a database, or is AsyncStorage sufficient for your use case? Once you get the hang of the ecosystem around React Native, building apps will become the easy part. The tricky parts are knowing how to set up a strong foundation that helps you build a scalable and maintainable app and using React Native the right way. If we look at the app as a product that our end users will use, we will be able to build a great experience , not just an app. Should that not be the principal aim of using a cross-platform tool? Let's try and break it down. Using React Native we are: Looking at the points above, it's clear that focusing on building our app as a product makes the most sense. Having a clear view of what we are looking to build will help us get there. It will also keep us in check that we are building the right thing, focusing on the end product and not getting lost in the technicalities or challenges of a platform. Storyboarding the app will help us achieve just that. I recommend a Storyboarding approach to build any front-end application, not just apps. This is not the typical storyboard that is created by the design teams, though the idea is similar. These storyboards can be a great way of looking at our app from a technical implementation point of view, too. This step will help us: To start, we will need to go through the wireframe design of the app. The wireframe is sufficient as we will not be focusing on colors and themes here. Next, we will go through every screen and break it down into reusable widgets and elements . The goals of this are multi-fold: For example, let's look at a general user onboarding flow: A simple and standard flow, right. Storyboarding can achieve quite a lot from the perspective of the app's development and structure. Let us see how. Visualize your app from a technical, design, and product standpoint As you will see, we have already defined eight or nine different elements and widgets here. Also, if elements like the search box, company logo, and the cart icon, need to appear on all screens, they can be put inside a Header widget. The process also helps us build consistency across the app. I would recommend building custom elements for even basic native elements like the Text element. What this does is make the app very maintainable. Say, for some reason, the designer decides to change the app's font tomorrow. If we have a custom element, changing that is practically a one-line change in the application's design system. That might sound like an edge case, but I am sure we have all experienced it. What about changing the default font size of the app or using a different font for bold texts or supporting dark mode? The Atomic Design pattern talks about breaking any view into templates, organisms, molecules, and atoms. If you have not heard about it, Atomic Design comes highly recommended, and you can read about it here . Taking a cue from the methodology, we will break down the entire development process into elements and widgets and list out all those that we will require to build the views. How do you do this? The steps are as follows: This process will help streamline the entire development process. You'll end up with a list of widgets and elements that you need to build. This list will work like a set of Lego blocks that will build the app for you. You may end up with a list like this for the e-commerce app: Looking at this list, we might decide to build a carousel widget that works like a banner carousel by passing banners as children, and as a category scroller by passing an array of category icons. If we do this exercise of defining every component for the entire app before we start building, it will improve our technical design and allow us to plan better. The process can also help iron out design inconsistencies as we will be defining all the elements, down to the most basic ones. If, for example, we were to end up with more than four of five primary buttons to define, that could indicate that we need to review the design from a user experience perspective. Source: Google Following this model will make the development approach very modular and set us up for the development phase. By now, we should also have a thorough understanding of: We also have an idea of how the layout of views will look from a technical standpoint: do we need a common header, how will transitions happen if there is animation, and so on. To summarize, we now have a wireframed plan in place that will give us a lot of confidence as we proceed with development.  To learn more about building apps with React Native, check out our new course The newline Guide to React Native for JavaScript Developer .

Thumbnail Image of Tutorial Storyboarding - The right way to build apps

Converting a React Native for macOS Application into a Menu Bar Application

The status menus (also known as menu bar icons) of a macOS menu bar let users quickly access status information and perform actions without launching an application inside a new, separate window. For example, upon installation, a popular desktop application like Dropbox automatically adds a status menu to the macOS menu bar for monitoring and reporting the status of uploads. With the single click of an icon/title, the status menu toggles open a condensed version of the Dropbox desktop application. You can get the latest uploads and share them immediately without having to change your active window. Status menus helps to maximize your workflow and keep you productive. They run in the background and periodically update with new notifications and content to avoid distracting you while you are focused on completing your work. With so many status bar applications available, you can customize this section of the macOS menu bar and arrange the items in any order to best complement your workflow. However, if you cannot find a status bar application that addresses a specific aspect of your workflow, such as aggregating and displaying relevant information about the status of jobs triggered by a CI build pipeline, then you can build your own status bar application with React Native for macOS . Unlike a desktop application, building a status bar application involves quite a few steps beyond the installation steps listed in the React Native for macOS documentation . Below, I'm going to show you how to convert a React Native for macOS application into a menu bar application. To get started, let's create a new React Native for macOS project from a standard React Native template. Verify that the project was initialized correctly by running it: The status bar application consists of two components: a status item and a popover. A status item is a clickable icon/title that sits in the system menu bar. A popover is a self-contained view that hovers over its surrounding context and displays content within a non-modal dialog. It is anchored to the element responsible for making it appear, which is indicated by the direction of its tooltip arrow. Both of these parts will be implemented in Swift. Unlike a pull-down menu, which simply lists options, the layout of a popover's content is flexible. This content will come directly from the React application whose root component <App /> is registered with AppRegistry inside of the project's index.js file. To transition to Swift, we must first remove the existing Objective-C code from the project. Delete the following files: Even if you delete these files inside of Finder or within your terminal, Xcode still references these from the project navigator. Therefore, open the project inside of Xcode by either... Then, delete those files manually from the project navigator. Keep Xcode opened for the remainder of this tutorial. To add a status bar item and popover into our application, let's first create two new files: Note : The casing of projectname must match the casing of the parent project directory's name. For example, if the project's directory name is rnmacmenubar (despite the project being named rnMacMenubar during initialization via npx react-native init ), then projectname will be rnmacmenubar . The <projectname>-macOS-Bridging-Header.h bridging header file exposes Objective-C libraries to Swift. For this project, the specified libraries provide APIs for integrating React Native into native code and rendering the React Native application within a UIView . ( <projectname>-macOS-Bridging-Header.h ) The AppDelegate.swift file serves as the application's initial entry file and defines a AppDelegate class, which handles application lifecycle events like applicationDidFinishLaunching and how the application responds to these events. ( AppDelegate.swift ) Inside of AppDelegate , define the properties popover and statusBarItem , which will reference the application's popover and status bar item respectively. An additional window property will be defined to reference a "development" window. ( AppDelegate.swift ) Once the application has launched, initialize the React Native application with RCTRootView , which displays the React Native application whose root component <App /> is registered inside of the project's index.js file (development environment) or from the compiled bundle (production build). This base view is embedded within a NSViewController . ( AppDelegate.swift ) Note : #if DEBUG is a pre-processor directive. Code inside of this directive are pre-processed before compilation. In the above code, we initialize the React Native bridge within this directive. Initialize the popover by setting its base dimensions to 700px by 800px and behavior to transient. Enable animation for its dismissal and emergence. Set its content to the NSViewController that has the React application embedded within it. ( AppDelegate.swift ) Initialize the status bar item by allocating 60px (in width) within the macOS status bar for it. Using the button property, we can customize the appearance and behavior of this item. Whenever the status item is clicked, the togglePopover method is called. The status item will be shown in the status bar via the project's name, not a typical icon, to make this example simpler. ( AppDelegate.swift ) The togglePopover dismisses the popover when its opened, and vice-versa. ( AppDelegate.swift ) Note : The @objc attribute marks the method as accessible and executable in Objective-C. The "development" window allows us to iterate upon the React application and immediately see changes without having to open the popover to see changes anytime they occur. Both the window and popover share the same rootViewController to avoid having two separate instances of the application. ( AppDelegate.swift ) Note : Once the popover opens, the window will no longer possess the controller, and the React application will only be rendered in the popover. For development, this is fine. applicationDidFinishLaunching tells the delegate when the application has launched. We will place all of the initialization code within the body of this instance method to execute this code once the application has launched. Altogether... ( AppDelegate.swift ) Note : Replace all instances of <projectName> with your project's name. This is the project name specified during initialization via npx react-native init . Drag and drop the <projectname>-macOS-Bridging-Header.h and AppDelegate.swift files from Finder into Xcode's project navigator (under <projectname>/<projectname>-macOS directory). When presented with the "Choose options for adding these files" modal, accept the default selected options. Inside of Xcode, check that the run destination is "My Mac" in the workspace toolbar. If not, then change the scheme to <projectname>-macOS . This is what the workspace toolbar should display: To avoid Swift linking errors, let's enable dead code stripping by visiting the project's build settings and switching the "Dead Code Stripping" setting to "YES." Now, let's tell Xcode to include Swift standard libraries in the final application bundle. To enable the DEBUG flag only when building and running the application from Xcode, search for the OTHER_SWIFT_FLAGS setting under the "User-Defined" section of the target <projectname>-macOS 's settings. Set the -DDEBUG flag only for the "Debug" mode, not for "Release." Otherwise, when you release the application to users, it will try to connect to the metro packager. If you encounter the following issue: Then resolve it by switching the "Don't Dead-strip Inits and Terms" project setting under the "Linking" section to "Yes" for both "Project" and "Target." To import Objective-C libraries from the Objective-C bridging header file <projectname>-macOS-Bridging-Header.h into Swift code, visit the project's build settings and set the "Objective-C Bridging Header" setting under the "Swift Compiler - General" section to the header file's path. Upon setting this path, SRCROOT and PROJECT_NAME are automatically substituted with their values. To inform the compiler of the AppDelegate.swift source file that must be compiled during the build process, add this source file as a "Compile Source" within the target's "Build Phase" settings. Click on project in project navigator. Clean the project by selecting "Product" from the upper menu and clicking the "Clean Build Folder" option. With the old AppDelegate class deleted (from the deleted AppDelegate.m file), we need to reselect AppDelegate class to ensure the new AppDelegate class (from the AppDelegate.swift file) is selected. Select the Main.storyboard file from the project navigator. Under "Application Scene" in the left-sidebar of the project editor. In the right-sidebar, select the "Attributes Inspector" tab and enter "AppDelegate" as the App Delegate class. Run the application via the shortcut CMD + r . This launches... If you click on the status item labeled with the project's name in the menu bar, a popover pops open and the development window no longer displays the React application. Inside of the popover is the React application. Click on the status item again and the popover is dismissed. The smaller window is an initial window that's automatically launched for the application (in the top-left corner of the above screenshot). The larger window is the development window (in the lower-right corner of the above screenshot). Since the development window shares the same rootViewController , if you resize this window, the content within the popover is also resized. Notice that the dock shows an icon for the application. To omit this icon from the dock when running the application, edit the project's Info.plist file. If you rebuild and rerun the application, then you will notice that the application's icon no longer appears in the dock. To hide the extra, initial (smaller) window, uncheck the "Is initial controller" checkbox in the storyboard's window controller. If you rebuild and rerun the application, then you will notice that this window no longer appears. To generate a release build, run the following command: If you encounter the following error... Then add the EXCLUDED_ARCHS build setting to the command and set it to arm64 . This excludes support for ARM-based simulators. Double-click the release build to verify that the application works properly. Now you can distribute this menu bar application to other macOS users! If you are stuck at any step of this tutorial, feel free to visit the final version of this project here . Try building your next menu bar application with React Native for macOS!

Thumbnail Image of Tutorial Converting a React Native for macOS Application into a Menu Bar Application

Building macOS Applications with React Native for macOS

Did you know Slack 's and Discord 's desktop clients are built with the Electron framework? Using Electron allows developers to bring their web applications to desktop faster without having to rewrite them completely as standalone, native clients that run on multiple operating systems. However, a major downside of building desktop applications with Electron is its high memory consumption and size because it packages the final build with a copy of Chromium, an open-source alternative of the Chrome browser, and Node.js to run an application written with HTML, CSS and JavaScript. At a high level, an Electron application behaves like a Chrome browser and loads and renders an HTML document inside of a window ( BrowserWindow ). To avoid the extra overhead of Chromium and Node.js and make the UI appear consistent with a platform's trademark design by rendering it with native APIs and components, consider using a different framework like React Native for Windows and macOS . Launched in 2019 and forked from Facebook's React Native project, React Native for Windows and macOS is an open source project maintained by Microsoft and allows developers to create Windows and macOS applications with a single React Native codebase. To interact with native APIs, the macOS port uses Objective-C or Swift while the Windows port uses C# or C++/WinRT. React Native for Windows and macOS comes with React components that are transformed into native components of each platform at runtime and can readily be imported from the react-native library. Composing an interface with native components instead of wrapping an entire web application inside of an application shell results in faster and smaller desktop applications. With all the tooling and CLI utilities provided by React Native for Windows and macOS, a developer can easily get started and deliver an application with a solid desktop experience. Below, I'm going to... Like any other piece of technology and library/framework, you need to decide whether React Native for Windows and macOS is appropriate for your particular use case by weighing its upsides against its downsides. Being aware of its strengths and weaknesses ensures our application best meets expectations. Here are several advantages for using React Native for Windows and macOS: Here are several disadvantages for using React Native for Windows and macOS: Remember. By spending a bit of time upfront to pick the best framework for your project, it will save you much more time during development. To get started with React Native for Windows and macOS, initialize a standard React Native project via the react-native init command. Specify the template version to match the latest minor version of React Native for Windows and macOS . Note : projectName cannot contain any spaces or hyphens; it must be alphanumeric and camelcased. Otherwise, the react-native CLI tool prints the following error message: error "<projectName>" is not a valid name for a project. Please use a valid identifier name (alphanumeric). During the initialization of the project, you may be prompted with the following question: CocoaPods (https://cocoapods.org/) is not installed. CocoaPods is necessary for the iOS project to run correctly. Do you want to install it? CocoaPods is a dependency manager for languages (Swift, Objective-C, etc.) that execute inside the Objective-C runtime. Select "Yes, with Homebrew" if you already have Homebrew installed on your machine. Otherwise, select "Yes, with gem (may require sudo)." Note : Make sure Homebrew and packages are up-to-date! Otherwise, you may eventually encounter the following error: dyld: Library not loaded . Inside of the new project, install the macOS-specific packages via the react-native-macos-init command: Note : Install Windows-specific packages via the react-native-windows-init command. This creates a macos directory at the root of the project directory, and it contains the macOS project. Run the macOS application (with hot-reloading) via the react-native run-macos command: Note : Run the Windows application via the react-native run-windows command. This may take some time as it needs to compile all the native code necessary to run the application. In the above screenshot, you may notice an additional terminal window that opens when running the application. This window contains Metro , the React packager. This window must be kept open for the application to work properly during development. If you run into the following error: Then inside of the macos/<projectname>-macOS/ViewController.m file, correct the casing of moduleName , which must follow the same casing as your project's name (camelcased), not lowercased. Anytime you modify the App.js file, watch those changes be automatically reflected in the application! ( App.js ) To build a release (a .app file) for distribution, add the following script to package.json : ( package.json ) Note : projectname is projectName , but lowercased. Here, the build configuration of xcodebuild is set to "Release." Also, the build takes a while to complete. Once completed, the path to the release is printed within the logs. When you double-click on the release, the application opens. Feel free send a copy of the application to other team members to test on their macOS machines. As opposed to Electron applications, React Native for Windows and macOS applications consume less memory and spawn less processes. If you run barebone applications built with these frameworks on the same machine and compared them side-by-side, then you will notice these differences. Here, we will compare three applications: When we run these three applications on the same macOS machine and open Activity Monitor, even though the Electron applications display static content, they each spawn four processes (one main and three helper processes based on Chromium's multi-process architecture ). Altogether, these processes consume more than twice the amount of memory consumed by the single React Native for Windows and macOS application's process. Similarly, if you run the top command, which displays CPU and memory utilization information, inside of a terminal, you will also make the same observation. Space-wise, the application built with React Native for Mac takes up significantly less space on your machine than the applications built with Electron. Download this repository with the source code of these applications to replicate these findings. Try building your next desktop application with React Native for Windows and macOS!

Thumbnail Image of Tutorial Building macOS Applications with React Native for macOS

Adding TypeScript to a React Native for macOS Project

Forked from Facebook's React Native project, React Native for Windows and macOS ships with Flow by default. When compared to TypeScript , Flow is way less popular, and there are fewer third-party library interface definitions written for Flow than TypeScript. If your project requires a static type checker, then pick TypeScript for its widespread support across many third-party libraries/frameworks and thriving ecosystem. Setting up TypeScript for the React Native codebase will improve code quality and readability by static type checking to verify type safety, identifying potential bugs in the code and explicitly annotating code with types. Plus, if you are coding within an IDE that features intelligent code completion (strongly integrated with TypeScript) like VSCode, then anytime you type in the editor, suggestions and info about variables, function signatures, etc. pop up inline to provide helpful hints and keep you productive. Below I'm going to show you how to... To get started, create a new React Native for macOS project by running these commands, as instructed by the official documentation : Inside of the project directory, delete the .flowconfig configuration file, which is installed by default. Since we will be integrating TypeScript into the project, there's no need to also support another static type checker. Install TypeScript and type definitions for React and React Native. To configure TypeScript, add a tsconfig.json file to the project. ( tsconfig.json ) If you have worked previously on a React project that involved TypeScript, then you should be familiar with most of these configuration options. Nevertheless, if are unclear with any of these configuration options, then consult the TypeScript documentation here . Delete the default App.jsx file and replace it with a App.tsx file. ( App.tsx ) Since the new App.tsx file exports the <App /> component via export const , we must change the import statement of this component from import App from './App' to import {App} from './App' . ( index.js ) Run the application to verify that everything is working properly. If haven't already created a React Native for Windows and macOS project, and you are about the begin one, then you can bootstrap it from the TypeScript-based React Native template . Pass the template name react-native-template-typescript to the react-native init command instead of the standard react-native . Then, run the same exact commands for scaffolding a new React Native for Windows and macOS project. Inside of the macos/<projectname>-macOS/ViewController.m file, correct the casing of moduleName , which must follow the same casing as your project's name (camelcased), not lowercased. For example, if your project name is rnMacTs , then this file will specify moduleName as rnmacts , which is incorrectly cased. Therefore, change this line... ( macos/rnmacts-macOS/ViewController.m ) to this... ( macos/rnmacts-macOS/ViewController.m ) Otherwise, you will encounter the following issue when you try to run the application: Here's the tsconfig.json file that's automatically generated from this template. It is loaded with helpful comments that describe each configuration option's purpose. You can uncomment some of the commented-out configuration options if you need additional checks by TypeScript. ( tsconfig.json ) Here's the App.tsx file that's automatically generated from this template. It's just a TypeScript version of the standard React Native template's App.jsx file. ( App.tsx ) Run the application to verify that everything is working properly. When you make a change within App.tsx , those changes will automatically be reflected in the application due to hot-reloading! Try building your next desktop application with React Native for Windows and macOS and TypeScript!

Thumbnail Image of Tutorial Adding TypeScript to a React Native for macOS Project

How to build React Native apps with GraphQL and Apollo

GraphQL is described as a query language for APIs. It is also considered as an alternative to REST and has been adapted more frequently in the last few years. Do you have a GraphQL endpoint already setup but you are looking forward to gaining some insight on how to gracefully consume this endpoint in a React Native app? Together, let us build a demo app that leverages an integration between Apollo Client, React Native and Expo . Apollo has an entire ecosystem based on to build GraphQL applications. It could be used to develop client-side and server-side apps separately. Apollo has more features and support than its open-source competitors in GraphQL for JavaScript world for now. The main objectives of this tutorial going to cover are: Before we get started, make sure you have installed the following on your local development machine. Do note that, to follow along with this tutorial, you need some basic knowledge of React Native and Expo SDK. You are also required to have Expo Client installed either on a simulator device or a real device. Throughout this tutorial, I am going to rely on and use the iOS simulator. The demo app we are constructing should work on Android devices as well. Create a new React Native/Expo app using the following command. Make sure to navigate to the directory once the project has generated. When generating an Expo app, you are prompted some questions by the cli interface as shown below. Make sure you choose expo-template-blank . The rest of the questions can have default answers as suggested. The next step is to install dependencies that we are going to use to build this app. You will learn about each individual dependency whenever necessary in the rest of the tutorial. Do note that, some of these dependencies are peer dependencies and you might not use them directly. Open a terminal window and install the following. After the dependencies have installed, open App.js file from the root of the project in your favorite code editor or IDE. Let us replace some of the default contents with some meaningful UI components such as custom header. To make sure everything works, open the terminal window. Execute the command expo start that triggers the Expo client app to run. Press i if you are using an iOS simulator or a if you are using an android emulator. When the App component renders for the first time, you are going to get the following output: With the base app running, you are ready to build further. Let us explore a way to configure the Apollo client in our app in this section. Create a new file called Client.js inside a directory src/graphql . The configuration part is going to fit inside this file. Import the following statements to begin the configuration process. Three different packages are being imported in the above code snippet. The apollo-client and apollo-cache-inmemory are used to integrate GraphQL client in a React or React Native app. Another package required to make it work is called apollo-link . But in our app, we are going to use a variant called apollo-link-rest . Why the variant? The reason being is that this package allows the app to use third-party APIs that do not have a GraphQL endpoint. That means, they tend to have a REST endpoint. One real-time API is NewsAPI . This package is going to help us transmit the query to the REST endpoint in a GraphQL query. In the Client.js file, start by adding a link from the constructor RestLink and pass the API key as field inside headers object. This object represents the value to be sent as headers on a request. Lastly, add the below configuration with the default cache and RestLink to complete the configuration of Apollo Client. Create a new file called Queries.js inside src/graphql directory. This file is going to contain the structure of the GraphQL query which is eventually going to fetch the result from the API. Start by importing gql from graphql-tag . Export a new query called Headlines as shown in the snippet below. This query is going to fetch top articles with fields such as title, the published location, the URL of the article and so on. Using the @rest directive, Apollo client knows how to parse the query. To use the previously created query, import it as well as the configured Apollo client inside the App.js file. Using the query Headlines the result should be fetched from the API whenever the component mounts as well as on the initial render of the app. This can be done by using the React Hook useEffect . Create a handler method requestHeadlines to invoke the query using Apollo Client. Invoking the query is simply done adding a promise. I am going to console.log the result from the query for now. With the Expo client, there is an option to Debug JS remotely. It opens the console tab in browser’s developer tools and lets you see results of log statements (just like in web development). Here is the result of the above query. When invoked, it fetches 20 headline objects in an array with all requested fields. In the last image, in the response, you will find a field called loading that indicates are the results being fetched or the response is complete. Using this can be helpful when adding an activity indicator to display the same message to the end-user in a real mobile app. Start, by importing the ActivityIndicator component from react-native. Also, to set a state for the loading indicator, import the hook useState . Inside the App component define the state for loading . Modify the return statement by adding an if-else statement based on the boolean value of the loading . After this step, you are going to get the following output: To make it stop and behave in the way the app requires, update the state of loading when the promise resolves inside the query handler method requestHeadlines . Refresh the Expo client and you will notice that after a few seconds, when the data is fetched, the loading indicator disappears and the screen UI is displayed as before. You are all set to display individual article component that is being fetched from the API endpoint. Add another state variable called articles . To render a list of data, let’s use the FlatList component from react-native. Update the articles state with the array from the response when the promise gets resolved inside the handler method requestHeadlines . The FlatList component requires three attributes to render a list of data items. Inside the src/components directory create a new file called Article.js . This component is going to display the title and source of each headline. The Article component is going to be a presentation component that receives everything from the App component as props. Add the following to the file. Import the Article component in App.js file for it to work. Go to the simulator or the device that is running the Expo client and you are going to see several headlines being fetched. That's it! Congratulations to you for sticking around till the end. I hope this post serves as the basis of your adventure in building React Native apps with GraphQL and Apollo.

Thumbnail Image of Tutorial How to build React Native apps with GraphQL and Apollo

Build an Ethereum Wallet with React Native

React Native has established itself as one of the leading frameworks for hybrid mobile development. According to statista.com the global average of mobile users is currently at 70% with mobile devices accounting for about half of web page views. Mobile apps are becoming (if not already) the means for us connecting with each other across the world, and thus this has serious implications for how we conduct our finance. Special thanks to fmsouza developing a scaffold for this implementation. Ethereum is a global, open-source platform for decentralized applications . On Ethereum, we can write code that controls digital value and essentially program our money . So let's jump right into it. 🚀 We are going to build React Native dApp that can For reference here's the repo : I am currently in the process of upgrading a number of packages that are old in this project, as well as migrating to React Hooks but in the interim, this should get people started. I will write a separate article with the refactored code. I'll be using react-native init to create this project. I am using React Native version 0.59.9 , because there have been issues integrating with React Native 0.6+. I will address those in a separate article. Run the following command this will, of course, add all the necessary dependencies to create a basic functioning react native app. I'll be using a variety of different packages to build this app, in particular: I will utilize other dependencies and dev dependencies which I will mention at particular snippets, but for the purposes of this article, I chose to highlight the main packages. So if you have any familiarity with redux then you may already understand what a store is, for those of of you who don't, The main responsibility of stores is to move logic and state out of your components into a standalone testable unit. You can read more here we use the @action decorator on any action that is going to modify an observable . Here we a variety of functions related to the manipulation of a particular instance of wallet's state. Here we deal with pending transactions, updating wallet history and reseting our stores. These make specific modifications on our state but are not directly called from components, which just adds another layer of modularization and follows general Flux architecture. Our Actions will be responsible for this. This store is responsible for dealing with our conversion to FIAT, here we set the various conversion rates that we would like to display to the user. These interact with our external providers, such as ethers.js or any http requests (to get our crypto rates or blockchain transactions), using axios , as well as persistent storage (for storing our private 🔑 . For example we get our prices and blockchain transactions from our api.js service, our getPrice gets the FIAT rates returned as a json object. Here's another example where we actually send the ether to another address. So these files wrap it all together, and are slightly distinguished from typical actions in a flux architecture in that these are responsible for changing state, calling services (which are more than likely asynchronous) and returning the result. They are called directly from components and I think it allows for more testable units when they are segregated in this way. Here's an example of how our transactions actions file. Here we handle sending ether to another wallet. As you can see we make calls to the @actions that we defined in our stores whilst making calls to our services such as TransactionsService which handles the actual sending of the ether from Address A to Address B using ethers.js as well as some other error handling. After we send that ether, we want to update our wallet to reflect that transaction in our history, and the wait for it to be confirmed i.e. for a Transaction receipt once the transactionHash has been mined, then notify our user that is has been confirmed. Here's an example now, of how this type of modularity makes testing easy I can call send a ether essentially from loading a wallet, creating a transaction and then awaiting it to be confirmed, and if I have issues I know that I won't have to debug my loadWalletFromPrivateKey or createTransaction function, nor the instantiation of a wallet. So as you can tell from the package.json I used NativeBase components to make life a bit easier, rather than completely solely custom components. On the home page, we want to load the wallets a user may have, but if they have not created any, then we want to prompt them to do so. We use a FlatList to list the existing wallets and our NoWallet component handles the initial step of the Wallet creation process. On ComponentDidMount we call the populate function which dispatches the loadWallets and getPrice functions, that will load the wallets and display their total unspent outputs or 'value' in FIAT. This component is pretty straightforward, we have a FAB to add a new wallet, which then takes them to the CreateWalletPage where we actually handle the creation of a wallet. This page handles the initial phase of creating a wallet, here we inform the user that they will be given a sequence of words known as mnemonic phrase which they will use to recover their wallet if they want to transfer it to another device. Here we use a utility function we built which relies on ethers to generate a mnemonic for the user that will be sufficiently strong to generate a binary seed which can be used for a deterministic wallet as well as easy enough to remember by a human, as outlined in bip-0039 spec . We then reveal it to the user, store it, and then request that the user confirm it on the ConfirmMnemonic page. Once they confirm it accurately, we store the mnemonic which can then use to create an HDNode Once the user has confirmed their mnemonic on the ConfirmMnemonic page , then we re-direct them to the wallets overview page so that they can see there newly created wallet! 🥳 Now we will go through the various pages involved in sending ether to another address from the wallet that has been created. The user would be on the WalletsOverview page, where they could then select a wallet, which would carry them to the WalletDetails page where they could then select the option to SendCoins which would then allow them to enter the amount, they then go to SelectDestination where they enter the recipient wallet's address (via manual or QR code) and then confirm the transaction. They enter the amount then ago ahead to select destination. Here the user may enter a destination address via a QR Code Input or select one of the Recently added addresses. The main component here is the custom Camera component which I will show below, which scans the QR Code then vibrates to let the user know it's successful. Once we have acquired the address we store it in the state so the user can then confirm the transaction. Now it's time for the user to confirm the transaction, then actually send the ether On ComponentDidMount we want to create a transaction so that if the user has confirmed that everything is ok, we call can call the onPressSend function which will call our TransactionActions to then send the ether to the recipient wallet. We want to generate a QR Code that another user may scan to send us Ether, and then this will be displayed to the user once the transaction hash is confirmed on the blockchain and loaded on our WalletOverview so our ReceiveCoins component handles this. We use react-native-qrcode-svg to generate this QR code and also allow the user to copy the address to their clipboard (in the case there is no QR Scanner) using Clipboard . And that's it! A very basic implementation of a wallet to get started building more complex dApps on React Native. Hope you enjoyed this tutorial and look out for more!

Thumbnail Image of Tutorial Build an Ethereum Wallet with React Native