What I Wish I Knew Starting my First React Native Project
I first used React Native for a project for the Girls Who Code Hackathon 2020. The submission had to be a mobile app, so naturally, as a team of JavaScript developers, we decided to use React Native.
At first, going from React to React Native is confusing. Little things are different, and it takes time to figure out what they are. Understanding why helped me categorize the differences to make sense of React Native.
The React App
If you don’t want to manage the iOS and Android code yourself, you should be working with Expo. Expo — as they say on their site — handles the gritty parts. They provide create-react-native-app
, the React Native equivalent to create-react-app
. This handles all of the lower level code for you. Expo also has a great CLI tool and a mobile app that allows you to test your code on your mobile device by scanning a QR code.
Expo is set up to start with npm start
in the package.json. But when installing Expo-compatible React Native packages, you should use the Expo CLI tool instead of NPM. This helps Expo stay in control of the packages. Installing packages with npm install
rather than expo install
can cause errors.
The Environment
The main difference between React and React Native is the environment. React runs in the browser, and React Native code is compiled into native code for the operating system. This means that things that we rely on working in the browser, such as DOM elements and CSS aren’t available in React Native.
Instead of using div
and span
tags, you use View
and Text
elements. There are small differences. For instance, you can put text inside a div without wrapping it in a span
or p
tag. In React Native, all text must be wrapped in a Text
element, including text inside buttons.
Similarly, you cannot use CSS with React Native. Instead, you have to use the built-in Stylesheet API. This works largely like CSS in JS, but there are some gotchas. Without CSS, there is no cascade and no inheritance. That doesn’t just mean that your elements don’t inherit styles from their parent. This also means you cannot apply text styles to views or view styles to text. All styles must be on the element they are directly styling. In other words, if you put a fontSize
property on a View, it will cause an error.
The Components
When I first started working in React Native, I wrote code that was as similar as possible to my React code. As I’ve learned more about React Native, I’ve started writing smaller components. Component re-usability is always important, but between the React Native specifics and the Stylesheet API, components in React Native can grow unwieldy very quickly with a lot of repetitive code.
Working in React Native has forced me to write smaller components in an attempt to preserve the DRYness of my code . While I would not naturally break apart buttons or form elements in React, I have started to do so in React Native to eliminate re-writing styles.