You are on page 1of 57

REACT NATIVE-

COMPONENTS
Dieudonne U
• Components let you split the UI into independent, reusable pieces, and
think about each piece in isolation.
• Conceptually, components are like JavaScript functions. They accept
arbitrary inputs (called “props”) and return React elements describing
what should appear on the screen.
• In React Native, there are two main types of components that make
up an application: functional components and class components.
These are structured the same as they would be in a regular React
app for the web.
Class Components
• Class components are JavaScript ES2015 classes that extend a base
class from React called Component.
import React, { Component } from 'react';
import { Text } from 'react-native';

class App extends Component {


render() {
return (
<Text>Hello, I am your cat!</Text>
);
}
}

export default App;

This gives the class App access to the React lifecycle methods like render as well
as state/props functionality from the parent.
Functional Components
• Functional components are simpler. They don’t manage their own state or have
access to the lifecycle methods provided by React Native. They are literally
plain old JavaScript functions, and are sometimes called stateless components.

import React from 'react';


import { Text } from 'react-native';

const App = () => {


return (
<Text>Hello, I am your cat!</Text>
);
}

export default App;


Core Components and APIs

• React Native provides a number of built-in Core Components ready


for you to use in your app. They are categorized into
• Basic Components
• User Interface
• List Views
• Android-specific
• iOS-specific
• Others
Basic Components
• View
• Text
• Image
• TextInput
• ScrollView
• StyleSheet
User Interface
• Button
• Switch

List Views
• Flat List
• SectionList
Android Components and APIs
• Many of the following components provide wrappers for commonly
used Android classes.
• BackHandler
• DrawerLayoutAndroid
• PermissionsAndroid
• ToastAndroid

iOS Components and APIs


Many of the following components provide wrappers for commonly
used UIKit classes.
1. ActionSheetIOS
Button Component
• A basic button component that should render nicely on any platform.
Supports a minimal level of customization.
<Button
onPress={onPressLearnMore}
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
FlatList

• The FlatList component displays a scrolling list of changing, but


similarly structured, data. FlatList works well for long lists of data,
where the number of items might change over time. Unlike the more
generic ScrollView, the FlatList only renders elements that are
currently showing on the screen, not all the elements at once
• The FlatList component requires two props: data and renderItem.
data is the source of information for the list. renderItem takes one
item from the source and returns a formatted component to render.
Example
<FlatList
data={[
{key: 'Devin'},
{key: 'Dan'},
{key: 'Dominic'},
{key: 'Jackson'},
{key: 'James'},
{key: 'Joel'},
{key: 'John'},
{key: 'Jillian'},
{key: 'Jimmy'},
{key: 'Julie'},
]}
renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
/>
Section List

• If you want to render a set of data broken into logical sections, maybe
with section headers, similar to UITableViews on iOS, then a
SectionList is the way to go.
const DATA = [
{
title: "Main dishes",
data: ["Pizza", "Burger", "Risotto"]
}, {
title: "Desserts",
data: ["Cheese Cake", "Ice Cream"]
}
];
<SectionList
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
Activity Indicator
• Displays a circular loading indicator.
<View style={[styles.container, styles.horizontal]}>
<ActivityIndicator />
<ActivityIndicator size="large" />
<ActivityIndicator size="small" color="#0000ff" />
<ActivityIndicator size="large" color="#00ff00" />
</View>
Modal
• The Modal component is a basic way to present content above an
enclosing view.
Props in React native
• Most components can be customized when they are created, with
different parameters. These created parameters are called props,
short for properties.
• For example, one basic React Native component is the Image. When
you create an image, you can use a prop named source to control
what image it shows.
• Props are immutable
Example
import React from 'react';
import { Image } from 'react-native';

const Bananas = () => {


let pic = {
uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
};
return (
<Image source={pic} style={{width: 193, height: 110, marginTop:50}}/>
);
}

export default Bananas;


Custom Components and Properties
import React from 'react';
import { Text, View } from 'react-native';

const Greeting = (props) => {


return (
<View style={{alignItems: 'center'}}>
<Text>Hello {props.name}!</Text>
</View>
);
}
export default LotsOfGreetings = () => {
return (
<View style={{alignItems: 'center', top: 50}}>
<Greeting name='Rexxar' />
<Greeting name='Jaina' />
<Greeting name='Valeera' />
</View>
);
}
Using props in class component

import React, { Component } from 'react';


import { Text } from 'react-native';

class Car extends React.Component {


constructor(props) {
super(props);
}
render() {
return <Text>I am a {this.props.model}!</Text>;
}
}
React Native State
• There are two types of data state and props in React Native which
control the component. The component that uses the state is
mutable. They can be changed later on if required. The props
component is immutable, and it is fixed throughout the lifetime.
• The state is generally initialized in constructor and then
call setState when we want to change it.
Example
import React, {Component} from 'react';
import { Text, View } from 'react-native';

export default class App extends Component {


state = {
myState: 'This is a text component, created using state data. It will change or updated on clicking it.'
}
updateState = () => this.setState({myState: 'The state is updated'})
render() {
return (
<View>
<Text onPress={this.updateState}> {this.state.myState} </Text>
</View>
);
}
}
• In this example, we create a Text component with state data. The
content of Text component will be updated by clicking on it. The event
onPress call the setState, and it updates the state "myState" text.
Using functional component
export default function App(){
const[myState,updateState]=useState('Original State');
return(
<View style={styles.container}>
<Text onPress={()=>updateState('New
Message')}>The state is: {myState}</Text>
</View>
)
}
Major React Native Layout Properties
• flexDirection
• ‘column’/’column-reverse’/’row’/’row-reverse’
• Defines the direction of the main axis. Opposite to the web, React
Native default flexDirection is column which makes sense, most
mobile apps much more vertically oriented.
import React, { Component } from 'react';
const styles = {
import { View, Text } from 'react-native'; container: {
marginTop: 48,
export default class FlexDirectionBasics extends Component { flex: 1
render() { },
headerStyle: {
return (
fontSize: 24,
// Try setting `flexDirection` to 'column'/'column-reverse'/'row'/'row-reverse' textAlign: 'center',
<View style={styles.container}> fontWeight: '100',
<Text style={styles.headerStyle}>flexDirection: 'row-reverse'</Text> marginBottom: 24
},
<View style={[{flexDirection:'row-reverse'}, styles.elementsContainer]}> elementsContainer: {
<View style={{width: 50, height: 50, backgroundColor: '#EE2C38'}} /> flex: 1,
<View style={{width: 50, height: 50, backgroundColor: '#FAA030'}} /> backgroundColor:
'#ecf5fd',
<View style={{width: 50, height: 50, backgroundColor: '#32B76C'}} />
marginLeft: 24,
</View> marginRight: 24,
</View> marginBottom: 24
); }
}
}
}
Flex
• flex will define how your items are going to “fight” over the available
space along your primary axis. Most of the time you will want your app
container to be flex:1 to take all of the screen height. Space will be
divided according to each element flex property. In the following
example the red, yellow and the green views are all children in the
container view that got flex:1. The red view got flex:1 , the yellow view
got flex:2 and the green view got flex:3 . 1+2+3=6 which means that
red view will get 1/6 of the space, the yellow 2/6 of the space and the
red 3/6 of the space
justifyContent
• ‘flex-start’/’flex-end’/’center’/’space-between’/’spac
• e-around’
alignItems
• ‘flex-start’, ‘flex-end’, ‘center’, ‘stretch’
• Align items along the cross axis. So in a default view, it will control
the horizontal alignment of items.
• stretch wouldn’t work if you have a specific width
• If you don’t have a specific width flex-start and flex-end wouldn’t
understand what to do…
alignSelf
• ‘flex-start’, ‘flex-end’, ‘center’, ‘stretch’
• align an item along the cross axis overwriting his parent alignItem
property
flexWrap
• ‘wrap’, ‘nowrap’

• Controls whether flex items are forced on a single line or can be


wrapped on multiple lines.

<View style={[{flexDirection: 'column', flexWrap: ' wrap'},


styles.elementsContainer]}>
The default value is nowrap
alignContent
• ‘flex-start’/’center’/’flex-end’/’stretch’/’space-between’/’space-
around’

• So if you went with flexWrap:'wrap' you have multiple lines of items,


this property will help you align the lines on the cross-axis.
Position
• ‘relative’/’absolute’

• Think of your container as a line of people. And you are telling each
person to stand 5 meters behind the person in front of him
(marginTop: 5). If this person is set to relative he will respect the line
and will position himself relatively to the person in front of him. If this
person is set to absolute he will ignore all of the people in the line and
will position himself as if the line was empty, 5 meters from where the
line (his parent container) starts.
• The default value is relative
Z-Index
• You can control which components display on top of others. In the
following example the zIndex of the yellow square to 1.
Lifecycle of React Native Application
Component
Introduction
• Lifecycle methods are inbuilt methods. As a Mobile Application
developer, we have to take care of the Lifecycle of each
screen/activity/component because sometimes we have to load the
data accordingly. For example, if I want to initialize some connection
when the user opens the screen reader and closes it when the user
closes it; In both cases we have to have some knowledge about the
Lifecycle methods so that we can perform such actions.
The lifecycle of React Native Application
There are 4 types of Lifecycle methods available in React Native
1. Mounting methods
1. constructor()
2. componentWillMount() (Deprecated after RN 0.60)
3. render()
4. componentDidMount()
2.Updating methods
1. componentWillReceiveProps() (Deprecated after RN 0.60)
2. shouldComponentUpdate()
3. componentWillUpdate() (Deprecated after RN 0.60)
4. componentDidUpdate()
3.Unmounting methods
1. componentWillUnmount()
4.Error handling methods
1. componentDidCatch()
Description
1. Mounting Methods
constructor(): It is the first method called when we open a
screen, it is mostly used to create States.
constructor() {
super();
console.log('Constructor Called.');
}
2. componentWillMount():
It is called right after constructor(), used to call asynchronous
tasks or network calls.
componentWillMount() {
console.log('componentWillMount called.’);
}

3. render(): Render is the most important Lifecycle method because


it is used to render UI or we can say the main View of the screen.
render() {
return (
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Text>Language is: {this.props.name}</Text>
</View>
);
}
• 4. componentDidMount(): Is called after render method, It is used for
the network calls.
componentDidMount() {
console.log('componentDidMount called.’);
}
2. Updating methods
• Updating methods are used to update the value of Props or
State to React Native. These methods are called automatically
when a component re-renders.
1. componentWillReceiveProps(): It is called before the
component dose anything with new props, We would send
the next prop as an argument inside it.
componentWillReceiveProps(nextProp) {
console.log('componentWillReceiveProps called.', nextProp);
}
• shouldComponentUpdate(): It is called every time before the screen
or parent component re-renders. We can stop the re-rendering of the
screen by passing false in this method.
shouldComponentUpdate(nextProp, nextState) {
console.log('shouldComponentUpdate called.');
return true;
}
• 3. componentWillUpdate(): It is called before the re-rendering when
new state or props is received for updating. It does not allow the
this.setState({}) method.

componentWillUpdate(nextProp, nextState) {
console.log('componentWillUpdate called.');
}
• 4. componentDidUpdate(): It is called after the rendering, this method
is mostly used to interact with updated rendering values and execute
any post-render events.

componentDidUpdate(prevProp, prevState) {
console.log('componentDidUpdate called.');
}
3. Unmounting method
• 1. componentWillUnmount(): It is called when the component is
removed from the DOM, Users can clear any running timers, stop
network requests and cleaning any previously stored value in the
application in this method.

• componentWillUnmount() {
• console.log('componentWillUnmount called.');
•}
Error handling method
• 1. The componentDidCatch(): It is a part of the error handling
method. It is used to find errors between JavaScript code and handle
them by passing the correct message or argument. It will help us to
use any try /cache block to handle any error.

• componentDidCatch(error, info) {
• console.log('componentDidCatch called.');
•}
References
• https://www.freecodecamp.org/news/functional-vs-class-component
s-react-native/#:~:text=Class%20components%20are%20used%20as,u
ser%20interactions%20or%20state%20updates
.
• https://www.javatpoint.com/react-native-state
• https://medium.com/wix-engineering/the-full-react-native-layout-che
at-sheet-a4147802405c
• https://aboutreact.com/react-native-application-life-cycle-of/

You might also like