React to React Native
Join my journey into exploring the world of React Native as a React JS developer. This post covers some basic quick start guide and free resources to quickly get started with Mobile Development using JavaScript, React and web technologies.
While I had been a ReactJS developer for a substantial period, last year I had an opportunity to work on a React Native project. Given my existing understanding of React, I quickly learned and got onboarded with building applications on React Native. This post goes into detail, documenting the learning process for quickly adapting to React Native, assuming prior knowledge of React JS.
To kickstart the journey, I found a concise and short YouTube crash-course that helped me quickly grasp the basics.
React Native Vs React
- Component Semantics: use a
<View />
element where a wrapper element like<div />
, <main /> etc is used. Like any other wrapper elements in JSX, It is meant to hold and lay out other elements or components .<View />
component is imported fromreact-native
package. - Text: text cannot be inserted directly; wrap it inside a
<Text />
component to maintain consistency across platforms. - Native Equivalent: React Native converts components to native equivalents of the respective OS.(e.g.,
<TextInput />
toExitText
in Android andUITextField
in iOS; ). - JavaScript Code and Logic: Functions, state logic, and any JavaScript logic run on a JS thread hosted by the React Native app in the native app built. The JavaScript logic written as a part of React Native codebase is not compiled to native equivalents, but instead its running on JS thread that is hosted by React Native App in the native app that was built. So, all UI components convert to native equivalents and all the JavaScript logic works as a JavaScript thread and not a native languague thread.
- React Navigation: Crucial for handling navigation in React Native. Understand setting up different navigators, such as Stack Navigator, Tab Navigator, and Drawer Navigator.
- Handling Platform Differences: React Native allows you to build for both iOS and Android, but there are platform-specific differences. Learn to handle variations in components, styling, and functionality for both iOS and Android.
- Testing Frameworks: The humble tools which we use for React Web like Jest, Enzyme, React Testing Library (Native) can also be used for testing React Native components.
- Camera Features: Numerous plugins cater to camera functionality in React Native, and I stumbled upon Vision Camera, which stands out for its comprehensive support of essential camera features.
React Native Semantics and Rules
<ScrollView />
is a scrollable<View />
component.- Use
<Button />
for native-styled buttons;<Pressable />
for custom buttons with style flexibility. - In case of
<Button />
component, since the styling on iOS and Android is different, thecolor
prop behaves likecolor
andbackground-color
respectively. - If we wish to make some element tappable, or in other words we wish to track the tap events, we will wrap those components inside
<Pressable />
. Thus, we can make a custom button using a<Pressable />
instead of using a<Button />
because<Button />
does not support astyle
prop. - There are other non-deprecated components like
<TouchableOpacity />
,<TouchableHighlight />
,etc but using<Pressable />
will make our codebase future proof (as per official documentation). - Use
<Modal />
for Lightbox, Overlays or Modals <Image />
for adding images- To add images, we should use the
<Image />
component. - The "status bar" is the zone, typically at the top of the screen, that displays the current time, Wi-Fi and cellular network information, battery level and/or other status icons. We can style the status bar to use a light or a dark mode, change visibility and even add transitions while it becomes visible or hidden using
<Status Bar />
component. - We can also add Animations, create Alerts, check if the application is in foreground or background using AppState and more.
React Native Styling
-
Inspired by CSS: The styling languague is inspired from CSS, but we do not have all the values we have in CSS. For instance, we can manually set text color using
color
property. -
Inline Styling: It is possible to write inline styles like in a normal React JS App, but generally not ideal due to code repetition.
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const MyComponent = () => {
return (
<View style={{ backgroundColor: 'blue', padding: 20 }}>
<Text style={{ color: 'white', fontSize: 16 }}>Hello, React Native!</Text>
</View>
);
};
export default MyComponent;
- StyleSheet Object: Use the
StyleSheet
object for optimized styling.
import React from 'react';
import { View, StyleSheet, Platform, Text } from 'react-native';
// Use the StyleSheet.create method to define your styles:
const styles = StyleSheet.create({
container: {
paddingVertical: Platform.OS === 'ios' ? 20 : 10,
},
text: {
fontSize: 16,
color: isDarkMode ? 'white' : 'black',
},
});
// Apply the styles to your React Native component.
const MyComponent = () => {
return (
<View style={styles.container}>
<Text style={styles.text}>Some Text here</Text>
{/* other components */}
</View>
);
};
export default MyComponent;
-
Flexbox Way of Styling: Every
<View />
usesdisplay: flex
by default and usesCSS Flexbox
way of aligning inner items. Default value forflexDirection
iscolumn
. By Default,<View />
element only takes as much space as its children components require unless we add properties likeflex
(Grow/Shrink),width
,height
, etc. -
Cascading Styles: Cascading nature of CSS does not work in React Native.The style properties won't cascade from parent to child components. For instance,
added inside will not cascade CSS properties, that is inherit properties like text color from component's style prop. -
Other Methods: Alternatively, We can also use CSS Modules and styled Components
import styled from 'styled-components/native';
const StyledText = styled.Text`
font-size: 16px;
color: ${(props) => (props.isBlue ? 'blue' : 'black')};
React Native Events
- Event Handling: Certain events like on input elements have similar event handlers as web but different names. For instance,
<TextInput />
usesonChangeText
instead ofonChange
,<Button />
usesonPress
instead ofonClick
, etc. - Gestures Galore: Master touch gestures using the
PanResponder
for advanced user interactions.PanResponder
reconciles several touches into a single gesture. It makes single-touch gestures resilient to extra touches, and can be used to recognize basic multi-touch gestures.
React Native Performance Optimisations
- Scroll View Vs FlatList: Using
<ScrollView />
to render a long list of items can cause performance issues as it renders all items, whether visible or not. To address this, opt for<FlatList />
for dynamic lists with numerous items. Unlike<ScrollView />
,<FlatList />
efficiently loads only the visible items, enhancing overall app performance. - React Performance Tricks: Use `useMemo` or `React.memo` for optimized performance.
- Alternatives to Memo: Dan Abramov wrote this article a while back discussing two basic techniques for improving rendering performance in React before resorting to memoization. Any state changes will cause the entire App to re-render, hence Dan suggests moving state down in the component hierarchy or lift content up based on whether a piece of state affects only a specific subtree or is used in a higher component. These approaches improve data flow and may enhance performance, with the added note that such optimizations should complement, not replace, memoization techniques like memo or useMemo. The author emphasizes the simplicity and underappreciated nature of these techniques, highlighting their potential benefits for future performance optimizations, such as with Server Components.
- Component Lifecycle: Understand the React Native component lifecycle for strategic optimizations.
- AsyncStorage: Leverage for efficient asynchronous data storage.
- Redux Integration: Explore Redux for state management in complex applications.
As we wrap up this comprehensive exploration into React Native, it's evident that the journey from ReactJS to React Native is not merely a transition but an evolution. From mastering the essential components like <View>
and <Text>
to unraveling the intricacies of touch gestures with PanResponder
, the more we write the code, more we embark newer nuances of this technology.
The incorporation of the StyleSheet
object for styling and strategic performance optimizations with techniques like useMemo
underscores the finesse required in this mobile landscape. The expert advice from luminaries like Dan Abramov serves as a guiding light, emphasizing foundational techniques that complement the ever-expanding realm of memoization strategies. Feel free to share your thoughts on Twitter and stay tuned for more of such content!