Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
(This article is part of an ongoing series on technical and soft skills from Nathan Thomas, a full stack software engineer studying and working at Lambda School based in Silicon Valley. Click here for part 5 in the series, an article about âThe Pursuit of Persistence and Grit.â)
Getting Started with React Native
Itâs time for another to-do app tutorial!
Just kidding.
I can guarantee that this walkthrough will be worth your time, much like double-stuff Oreos or a happy golden retriever puppy. Weâll be building out a simple weather app in React Native using MetaWeather, a free weather API. React Native is a library for building iOS, Android, and most recently Windows, tablets, and Xbox applications.
Hereâs an example of the finished product weâll be making. Iâve even thrown in a higher order component and some light styling for some extra seasoning so you can see that React Native isnât so crazy after all.
As always, I like to define my reader expectations up front; you need to be familiar with React, as I wonât be explaining concepts fundamental to it. In fact, your ability to quickly learn React Native from this article depends on us being able to compare what weâre doing to how we would normally use React. Additionally, you need to be familiar with Flexbox and the basics of CSS. Lastly, it would also be great if youâre used to working with APIs, but itâs not a requirement; Iâll hold your hand through that part and give you the code for everything.
With that out of the way, letâs go ahead and get started. I think youâre really going to have fun with this one.
âWe take better care of our smartphones than we do of ourselvesâââthe phones are always recharged!â
â Arianna Huffington
Letâs Make It Rain
There are just a couple things we need to do before we code anything. Iâll list them all out here:
- Go to the Expo website and sign up for a free account. Once you do, scroll down to the footer, look for a column labelled âBeginners,â and click on the âTry Expo Snackâ link. Snack is a free, online code-editing sandbox for React Native, and itâs what weâll be using today.
- I need you to go grab a cup of your favorite hot beverage. If weâre going to do this, weâre going to do it right. Weâre going to get comfortable.
When youâre done with both of those things, create a new, blank project in Snack. Your new boilerplate app should look something like this:
Snack makes up amazing names when you create a new application. Mineâs called âintelligent donut,â but yours might be something like âamused pistachioâ or âfrisky blueberries.â Go ahead and rename it if you want (although Iâd personally keep either of those last two names), and then hit the big âSaveâ button in the top right corner. Iâm going to call mine âReact Native App Demoâ for the sake of clarity during this walkthrough.
Go ahead and delete everything in App.js and paste in the following code:
This is instantly going to throw an error because we havenât created a HomeView component yet, but donât panic from the red screen of death Snack is going to throw us. Letâs take a moment to discuss whatâs going on with our code, and then weâll go fix it.
Notice how Iâve only imported the react dependency so far. If this doesnât prove to you that you can easily learn how to use React Native coming from a web background, I donât know what will. We are running full-blown React on a mobile device, and weâll supplement it in just a minute with the react-native dependency for anything else that needs to be tweaked to make it work.
With that little pep talk out of the way, go ahead and remove all the files in the existing components directory, add a container directory inside that one, and make a new HomeView.js file to go inside it. Paste in the following code (and then weâll discuss it):
Did you read through all of that? Good. You deserve a medal, high five, or at least a cookie đȘ from someone. Go ahead and take a quick mental break to swig some of that hot beverage youâre holding.
Okay, letâs discuss whatâs happening.
First off, we have the import line for react-native. It looks like this:
These named exports from the react-native dependency allow us to build out our mobile application on top of normal React. But donât be intimidated by them; they directly correlate to pretty much everything you already know about the web environment:
- Text is used the same way as the p, h1, h2, and all of those other sorts of text-containing tags.
- The View tag is used in much the same way as you would a div, section, header, footer, or other sorts of organizational tags in HTML.
- ScrollView is very much like View, but itâs extra fancy đ since it allows us to extend our container past the boundaries of the screen so that the user can swipe through content. Weâll see how this works in a bit.
- Finally, the StyleSheet import enables us to build out a complete stylesheet object inside of our application using CSSÂ styles.
Taking that knowledge, letâs work our way down the page and analyze the code. To start, hereâs the class in our HomeView.js component file:
As you can see, we have our class structured with a ScrollView as the overall container. This allows us to have a scrollable, fluid structure to the page that the user can drag through with their finger. Inside of that, we have our View and Text tags which contains some text content. Finally, the last thing to note here is that weâre using another Text tag inside of the first one; this functions (in this scenario) very much like if you had a span tag inside of a p tag in your JSX in normal React. It allows you to single out parts of the text for specific styling.
We have our StyleSheet below our class. As a reminder, this is what it looks like:
When we call StyleSheet's .create() method, we can pass in an object that contains multiple key-value pairs of styling objects. React Native connects these to our component and makes them accessible for reference there.
In the code snippet, the scrollContainer style is assigned the value of an object with many individual CSS styling properties inside of it. These are all camel-cased (i.e. marginBottom and justifyContent), and any text value is wrapped in quotation marks (i.e. "center", "spaceBetween", etc.).
Additionally, notice that all measurements lack the values (i.e rem, px, etc.) that you know and love (and maybe hate) from a web environment. This is because all measurements in React Native default to plain integers without a unit type ending. These represent pixel-density-independent proportions on the screen.
This is also a great moment to talk about how layout work in React Native. Iâve previously said that CSS is the technique you use to style everything, but youâll also be pleased to know that Flexbox is the module we use for all layouts. There are two significant differences with it that you need to know about right now, though:
- The CSS styling property of flexDirection in the Flexbox module defaults to column instead of row in React Native.
- The new flex property, shown in scrollContainer up above, sizes the element according to the number assigned to it. There is no way I can explain it in this small space better than the official documentation, so I highly recommend you give it a quick read.
As we previously said, the object passed into StyleSheet.create() applies to the component when it mounts. We then utilize the styles on it by writing style={styles.styleNameGoesHere} on the component in the code; hereâs the HomeView.js class again so you can see what Iâm talking about:
Pretty cool, right?
Now that we have a basic grasp on some of the React Native imports as well as how the default stylesheets work, letâs go ahead and rig up a higher order component, some presentational components, and make an axios call to our MetaWeather API.
âWhen we started work on the iPhone, the motivation there was we all pretty much couldnât stand our phones, and we wanted a better phone.â
â Jony Ive
When It Rains, It Pours
At this point, your app should have the following image on screen and file setup as shown below:
Weâre going to go ahead and build out the rest of this app. Iâm going to show you entire snippets of code to paste in, and weâll talk about anything unique before we move on to the next one. Sound good?
First, create a LoginView.js component inside your container directory and paste in the following code:
This only new thing I want to point out here is that we can import and use the prop-types dependency just like in normal React. We wonât be doing that in the rest of the application, but itâs important that you at least see it once. Now we have to go flesh out the rest of the app so that this component's buttonFunction will get passed in on props.
That code above is also going to throw a big red error due to the button import, so create a presentational directory inside the components one and make a Button.js file there. Paste in the following code:
In this code, I want you to notice what weâre importing from react-nativeâ TouchableHighlight is what allows React Native to respond properly to touches when wrapped around other tags. We have to supply it with an underlayColor prop and a hex color code (the last two numbers of the #0E30F050 above are the opacity percentage). If we donât supply this, the color will turn super funky when we press the button (read about why here).
Additionally, notice that we no longer have onClick events. Instead, weâre using onPress which seems super obvious if we stop to think about it. We are using smartphones, after all!
Our next step is to make one more file in your container directory. Weâll name it authenticate.js. This is a higher order component for an extremely simple pseudo-login process. Paste this code in:
The point of using a higher order component and some light currying is to show you that weâre flexing the exact same muscles as in normal React. React Native isnât that bad, and things are really starting to come together now!
Obviously, we need to complete the circle with our components, and you can probably see where this is going if youâre used to currying and higher order components in React; letâs go back to App.js and update it to look like this:
Right on! At this point, our file structure and application should look like this:
If you click that beautiful blue button, you will âloginâ to your application. Itâs time to make our call to the MetaWeather API and display our data to the screen!
Image by Alfred Twj on Unsplash
Excuse Me While I Kiss the Sky
First, go ahead and click on the package.json file. Delete all the code in there, and paste the following dependency list in:
Isnât it nice to know that we have ye olde package.json with us and along for the ride?
Next, go to HomeView.js and update the code to look like this:
We just imported the axios dependency along with the Button.js component, added a class constructor function, implemented a componentDidMount() lifecycle method, but some new text and a button in our component code, and added a weatherText style in our StyleSheet code. The axios call happening in our lifecycle method is currently coded to San Francisco, but you can tweak it using the information in the MetaWeather API documentation here.
Whew. đ°
That was a lot of work, but weâre all done! Poke your way around the application, and youâll find that you can log in, drag the ScrollView page from HomeView.js around, render the current weather to the screen, and logout using the button on the home screen.
Additional Resources for Your Journey
- React Native official documentationâââThese are really well-written, and you can basically search your way through building an app (with some light sprinkling of Stack Overflow thrown in).
- Expoâ This is the premier way of building out a React Native application. They made the Snack software we used in this article. I used Appleâs raw Xcode on my last project since Expo doesnât support React Hooks, and trust me, you should use Expo. There are some nice CLI tools to work locally on your computer so you donât have to use Snack in the future.
- React Router NativeâââThere are many choices out there for navigation in React Native, but this one is great since it uses the exact same syntax as React Router (except that it doesnât have a NavLink).
- Styled ComponentsâââYou can use this amazing styling library in React Native by installing the dependency styled-components and then importing styled-components/native anywhere in your app.
- React Native Shadow GeneratorâââA great resource for generating cool drop shadows for your apps. I used this to generate the shadow on the welcome card in this articleâs demo app.
Thanks for reading.
Nathan
(GitHub, LinkedIn, Twitter, Instagram, and Portfolio Site)
Building Your First React Native App was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.