React Native Text, View
import React, { Component } from 'react'
import { View, Text, Button } from 'react-native'
const books =[
{
id:1,
name:'Java Scripts'
},{
id:2,
name:'React Native'
},{
id:3,
name:'Node. js'
}
]
export default class App extends Component{
constructor(props){
super(props);
this.state ={
activeIndex:0
}
}
nextMethod=()=>{
const {activeIndex}= this.state
if(activeIndex < books.length -1){
this.setState({activeIndex: activeIndex +1})
}
else{
this.setState({activeIndex:0})
}
}
render(){
const data = books[this.state.activeIndex]
return(
<View style={{flex:1}}>
<Text style={{ fontSize:30}}>{data.id}.{data.name}</Text>
<View style={{ position:'absolute', bottom:30}}>
<Button title='Next' onPress={()=> this.nextMethod()}></Button>
</View>
</View>
)
}
}
................................................................................................................................................................................................................................
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder='Username'
autoCapitalize="none"
autoCorrect={false}
placeholderTextColor='white'
onChangeText={val => this.onChangeText('username', val)}
/>
<TextInput
style={styles.input}
placeholder='Password'
autoCapitalize="none"
secureTextEntry={true}
placeholderTextColor='white'
onChangeText={val => this.onChangeText('password', val)}
/>
<Button
title='Sign In'
onPress={this.signIn}
/>
</View>
)
}
}
const styles = StyleSheet.create({
input: {
width: 350,
fontSize: 18,
fontWeight: '500',
height: 55,
backgroundColor: '#42A5F5',
margin: 10,
color: 'white',
padding: 8,
borderRadius: 14
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
............................................................................................................................................................................................................................................
Eaxmple # 2
import React, { Component } from 'react'
import { View, Text, ImageBackground, StyleSheet, Image, TextInput, Dimensions, TouchableOpacity } from 'react-native'
import bgImage from './src/assets/hello.jpg'
import logo from './src/assets/logo.png'
import Icon from 'react-native-vector-icons/Ionicons'
const { width: WIDTH } = Dimensions.get('window')
const { height: HEIGHT } = Dimensions.get('window')
export default class App extends Component {
render() {
return (
<ImageBackground source={bgImage} style={styles.container}>
<View style={styles.logoContainer}>
<Image source={logo} style={styles.logo} />
<Text style={styles.logoText}>React Native</Text>
</View>
<View style={styles.inputContainer}>
<Icon name='md-person' size={25} color={'rgba(255,255,255,0.7)'} style={styles.inputIcon}/>
<TextInput
style={styles.input}
placeholder='Username'
placeholderTextColor='#fff'
underlineColorAndroid='transparent'
/>
</View>
<View>
<Icon name='md-lock' size={25} color={'rgba(255,255,255,0.7)'} style={styles.inputIcon}/>
<TextInput
style={styles.input}
placeholder='password'
placeholderTextColor='#fff'
secureTextEntry={true}
underlineColorAndroid='transparent'
/>
<TouchableOpacity style={styles.btn}>
<Icon name={'md-eye'} size={25} color={'rgba(255, 255, 255,0.7)'}/>
</TouchableOpacity>
</View>
<TouchableOpacity style={styles.login}>
<Text style={styles.text}>Login</Text>
</TouchableOpacity>
</ImageBackground>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: null,
height: null,
alignItems: 'center',
justifyContent: 'center'
},
logoContainer: {
alignItems: 'center',
marginBottom:50
}
,
logo: {
width: 120,
height: 120
},
logoText: {
color: '#eee',
fontWeight: 'bold',
fontSize: 20,
marginTop: 10,
opacity: 0.5
},
inputContainer:{
marginTop:10,
marginBottom:20,
}
,
input: {
width: WIDTH - 55,
height: 50,
borderRadius:25,
fontSize:20,
paddingLeft:50,
backgroundColor:'rgba(0,0,0,0.35)',
color:'rgba(255, 255, 255, 0.7)',
marginHorizontal:25
},
inputIcon:{
position:'absolute',
left:37,
top:8
},
btn:{
position:'absolute',
top:8,
right:37
},
login:{
width: WIDTH -55,
height:45,
borderRadius:25,
backgroundColor:'#432577',
justifyContent:'center',
marginTop:20,
},
text:{
textAlign:'center',
color:'rgba(255,255,255,0.7)',
fontSize:16
}
})
.....................................................................................................................................................................................................................................
Example 3
import React, { Component } from 'react'
import { View, Text, TouchableOpacity, KeyboardAvoidingView, AsyncStorage, TextInput, StyleSheet } from 'react-native'
import { createAppContainer, createStackNavigator } from 'react-navigation'
class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
}
}
componentDidMount() {
this._initialState().done()
}
_initialState = async () => {
var value = await AsyncStorage.getItem('user')
if (value !== null) {
this.props.navigation.navigate('Profile')
}
}
LoginMethod=()=>{
alert('its work')
}
render() {
return (
<KeyboardAvoidingView behavior='padding' style={styles.wrapper}>
<View style={styles.container}>
<Text style={styles.header}>Login</Text>
<TextInput style={styles.textInput}
placeholder='Enter userName'
placeholderTextColor='#eee'
onChangeText={(username) => this.setState({ username })}
underlineColorAndroid='transparent'
/>
<TextInput style={styles.textInput}
placeholder='Enter password'
placeholderTextColor='#eee'
onChangeText={(password) => this.setState({ password })}
underlineColorAndroid='transparent'
/>
<TouchableOpacity onPress={this.LoginMethod} style={styles.btn}>
<Text> Login</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
)
}
}
const Stack = createStackNavigator({
Home: { screen: Login }
}, {
defaultNavigationOptions: () => ({
header: null
})
})
const AppContainer = createAppContainer(Stack)
export default class App extends Component {
render() {
return (
<AppContainer />
)
}
}
const styles = StyleSheet.create({
wrapper:{
flex:1
},
container: {
flex: 1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'#2896d3',
paddingLeft:40,
paddingRight:40
},
header:{
fontSize:20,
marginBottom:60,
color:'#fff',
fontWeight:'bold'
}
,
textInput:{
alignSelf:'stretch',
padding:16,
marginBottom:20,
backgroundColor:'#eee'
},
btn:{
alignSelf:'stretch',
backgroundColor:'#01c853',
padding:20,
alignItems:'center'
}
})
....................................................................................................................................................................................................................................
Example : # 5
App.js
....................................................................................................................................................................................................................................
Example : # 6
....................................................................................................................................................................................................................................
marginVertical :2
....................................................................................................................................................................................................................................
paddingVertical
....................................................................................................................................................................................................................................
paddingleft input fields:
....................................................................................................................................................................................................................................
const { width, height} =Dimensions.get('window')
....................................................................................................................................................................................................................................
....................................................................................................................................................................................................................................
....................................................................................................................................................................................................................................
Example : # 7
Heading.js
import React, { Component } from 'react'
import { View, Text, StyleSheet } from 'react-native'
class Heading extends Component{
render(){
return(
<View style={styles.container}>
<Text style={styles.text}> PHOTOS</Text>
</View>
)
}
}
export default Heading
const styles = StyleSheet.create({
container:{
justifyContent:'center',
alignItems:'center',
borderBottomColor:'#ddd',
borderBottomWidth:5
},
text:{
fontSize:19,
fontWeight:'bold',
textAlign:'center',
margin:15
}
})
.........................................................................................................................................................................................................................................
PhotoList.js
import React, { Component } from 'react'
import { View, Text, StyleSheet, ScrollView , SafeAreaView} from 'react-native'
import PhotosSection from '../components/PhotosSection'
import datas from '../../data'
class PhotosList extends Component{
constructor(props){
super(props)
this.state={
datas:datas
}
}
getData=()=>{
return this.state.datas.map(d=>{
return <PhotosSection details={d} key={d.id}/>
})
}
render(){
return(
<ScrollView style={styles.container}>
{this.getData()}
</ScrollView>
)
}
}
export default PhotosList
const styles = StyleSheet.create({
container:{
flex:1,
}
})
.........................................................................................................................................................................................................................................
PhotoSections.js
import React, { Component } from 'react'
import { View, Text, StyleSheet, Image, TouchableWithoutFeedback } from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
class PhotosSection extends Component {
constructor(props) {
super(props)
this.state = {
heartIcon: 'ios-heart-empty',
like: false
}
}
toggleLike = () => {
this.setState({
like: !this.state.like
})
if(this.state.like) {
this.setState({
heartIcon:'ios-heart'
})
}
else{
this.setState({
heartIcon:'ios-heart-empty'
})
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.thumbnailSection}>
<Image source={{ uri: this.props.details.user_avatar}} style={styles.thumbnail} />
<Text style={styles.headerUsername}> {this.props.details.username}</Text>
</View>
<View>
<Image style={{ width: null, height: 250, borderRadius: 15 }} source={{ uri:this.props.details.image }} />
</View>
<View style={styles.heartContainer}>
<TouchableWithoutFeedback onPress={this.toggleLike}>
<Icon name={this.state.heartIcon} size={32} style={{color:this.state.heartIcon === 'ios-heart-empty' ? 'black' :'red'}} />
</TouchableWithoutFeedback>
</View>
<View style={styles.imageMeta}>
<Text style={styles.userName}>{this.props.details.username}</Text>
<Text>{this.props.details.caption}</Text>
</View>
</View>
)
}
}
export default PhotosSection
const styles = StyleSheet.create({
container: {
flex: 1,
margin: 10
},
thumbnailSection: {
flexDirection: 'row',
padding: 5,
alignItems: 'center'
},
thumbnail: {
width: 50,
height: 50,
borderRadius: 25
},
headerUsername: {
fontWeight: 'bold',
fontSize: 19,
marginLeft: 10
},
imageMeta: {
flexDirection: 'row'
},
userName: {
fontWeight: 'bold',
paddingRight: 10
},
heartContainer: {
paddingVertical: 10
}
})
.........................................................................................................................................................................................................................................
App.js
import React, { Component } from 'react'
import { View, Text, StyleSheet } from 'react-native'
import Heading from './src/components/Heading'
import PhotosList from './src/components/PhotosList'
class App extends Component {
render() {
return (
<View style={styles.container}>
<Heading/>
<PhotosList/>
</View>
)
}
}
export default App
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor:'#fff',
}
})
.......................................................................................................................................................................................................................................
data.js
let data
export default data = [
{
id:1,
username:"ML_Crusta",
user_avatar:"https://i.pravatar.cc/400?img=1",
image: "https://images.unsplash.com/photo-1553174241-0b28d763cafa?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80",
caption:"#holiday,#Roam "
},
{
id:2,
username:"Ever_Nes",
user_avatar:"https://i.pravatar.cc/400?img=2",
image: "https://images.unsplash.com/photo-1546596183-0aa5a36b03b9?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80",
caption:"#nightglow,#motel "
},
{
id:3,
username:"Sweety1",
user_avatar:"https://i.pravatar.cc/400?img=3",
image: "https://images.unsplash.com/photo-1560748369-d05f480b43bf?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80",
caption:"#GoodMorning,#seeme "
},
{
id:4,
username:"Jonny_124",
user_avatar:"https://i.pravatar.cc/400?img=4",
image: "https://images.unsplash.com/photo-1503185912284-5271ff81b9a8?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80",
caption:"#photoshoot, "
},
{
id:5,
username:"Angelina",
user_avatar:"https://i.pravatar.cc/400?img=5",
image: "https://images.unsplash.com/photo-1529626455594-4ff0802cfb7e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=634&q=80",
caption:"#beauty,#selfie "
}
]
.................................................................................................................................................................................................................................
display
.................................................................................................................................................................................................................................
Example : # 8
Header.js
import React from 'react'
import { Text, View, StyleSheet } from 'react-native'
const Header = () => {
return (
<View style={styles.container}>
<Text style={styles.text}> Basic Ui Demo</Text>
</View>
)
}
export default Header
const styles = StyleSheet.create({
container:{
backgroundColor:'#ff7550',
borderRadius:8,
elevation:6
},
text:{
textAlign:'center',
fontSize:15,
fontWeight:'bold',
marginVertical:15,
}
})
................................
App.js
import React from 'react'
import { View, Text , StyleSheet} from 'react-native'
import Header from './src/components/Header'
const App = () => {
return (
<View style={styles.container}>
<Header/>
</View>
)
}
export default App
const styles = StyleSheet.create({
container:{
flex:1,
padding:5
}
})
............................................
.............................................................................................................................................................................................................................
Example : #9
yarn add react-native-linear-gradient
........................................................................................................................................................................................................................................
import React, { Component } from "react";
import { StyleSheet, View, TextInput, Text, Button } from "react-native";
class App extends Component {
constructor(props){
super(props)
this.state = {
userName: "",
userPassword: ""
}}
uaserNameTextChange = (inputText) => {
this.setState({ userName: inputText })
}
uaserPasswordTextChange = (inputText) => {
this.setState({ userPassword: inputText })
}
userLogin = () => {
alert("User Name :-" + this.state.userName + "\n"
+ "Password :-" + this.state.userPassword + "\n")
}
render() {
return (
<View style={styles.container}>
<Text style={styles.txtLogin}>User Login</Text>
<TextInput
style={styles.textInputStyle}
onChangeText={this.uaserNameTextChange}
placeholder="Enter username"
placeholderTextColor="red"
/>
<TextInput
style={styles.textInputStyle}
onChangeText={this.uaserPasswordTextChange}
placeholder="Enter password"
placeholderTextColor="red"
secureTextEntry={true}
/>
<View style={{ margin: 25 }}>
<Button
title="Login"
color="green"
onPress={this.userLogin}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "flex-start",
alignContent: "center",
margin: 10
},
textInputStyle: {
borderColor: '#9a73ef',
borderWidth: 1,
height: 40,
marginLeft: 20,
marginRight: 20,
padding: 10,
marginTop: 8
},
txtLogin: {
padding: 20,
fontWeight: "bold",
fontSize: 20
}
})
export default App;
..............................................................................................................................................................................................................................
Example: #10
import React, { Component } from 'react'
import { View, Text, StatusBar, TextInput, StyleSheet, Button, KeyboardAvoidingView, Platform, SafeAreaView, ScrollView } from 'react-native'
class Home extends Component {
render() {
return (
<SafeAreaView style={{flexGrow:1}}>
<ScrollView style={{flexGrow:1}}>
<KeyboardAvoidingView behavior={Platform.OS =='ios' ? "padding":'padding'} enabled style={{flexGrow:1}}>
{/* <KeyboardAvoidingView behavior={Platform.OS =='ios' ? "padding":'height'} enabled style={{flexGrow:1}}> */}
<View>
<Text> --Login --</Text>
<TextInput style={styles.textInput}
placeholder='Username'
placeholderTextColor='#000'
/>
<TextInput style={styles.textInput}
placeholder='Email'
placeholderTextColor='#000'
/>
<TextInput style={styles.textInput}
placeholder='Email'
placeholderTextColor='#000'
/>
<TextInput style={styles.textInput}
placeholder='Email'
placeholderTextColor='#000'
/>
<TextInput style={styles.textInput}
placeholder='Email'
placeholderTextColor='#000'
/>
<TextInput style={styles.textInput}
placeholder='Email'
placeholderTextColor='#000'
/>
<TextInput style={styles.textInput}
placeholder='Email'
placeholderTextColor='#000'
/>
<TextInput style={styles.textInput}
placeholder='password'
placeholderTextColor='#000'
/>
<View style={styles.btn}>
<Button title='Submit' color='green'></Button>
</View>
</View>
</KeyboardAvoidingView>
</ScrollView>
</SafeAreaView>
)
}
}
class App extends Component {
render() {
return (
<View style={styles.container}>
<StatusBar barStyle='light-content' backgroundColor='red' />
<Home/>
</View>
)
}
}
export default App
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent:'center',
alignContent:'center',
paddingLeft:40,
paddingRight:40
},
textInput: {
borderBottomWidth: 2,
borderBottomColor: 'red'
},
btn:{
paddingTop:20
}
})
..............................................................................................................................................................................................................................
Example: #11
LoginPage.js
import React, { Component } from 'react'
import { View, TextInput, TouchableOpacity, Button, Text, StyleSheet } from 'react-native'
class LoginPage extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.textfields}>
<TextInput style={styles.input}
placeholder='username'
returnKeyType='next'
keyboardType='email-address'
autoCorrect={false}
autoCapitalize='none'
onSubmitEditing={() => this.passwordInput.focus()}
/>
<TextInput style={styles.input}
secureTextEntry
placeholder='password'
returnKeyType='next'
ref={(input) => this.passwordInput = input}
/>
<TouchableOpacity style={styles.buttonContainer}
onPress={() => this.props.navigation.navigate('Home')}>
<Text style={styles.buttontext}>Login</Text>
</TouchableOpacity>
<Text style={styles.text} onPress={() => this.props.navigation.navigate('Register')}>Register Here</Text>
</View>
</View>
)
}
}
export default LoginPage
const styles = StyleSheet.create({
container: {
padding: 20,
justifyContent: 'center',
alignItems: 'stretch',
backgroundColor: '#ecf0f1',
flex: 1
},
input: {
paddingLeft: 20,
borderRadius: 50,
height: 50,
fontSize: 20,
backgroundColor: 'white',
borderWidth: 1,
borderColor: '#1abc9c',
marginBottom: 20,
color: '#34495e'
},
buttonContainer: {
height: 50,
borderRadius: 50,
backgroundColor: '#1abc9c',
paddingVertical: 10,
justifyContent: 'center'
},
buttontext: {
textAlign: 'center',
color: '#ecf0f1',
fontSize: 20
},
text:{
color: '#1abc9c',
textAlign:'center',
fontSize: 20
}
})
..............................................................................................................................................................................................................
Register.js
import React, { Component } from 'react'
import { View, TextInput, TouchableOpacity, Button, Text, StyleSheet } from 'react-native'
class RegisterPage extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.textfields}>
<TextInput style={styles.input}
placeholder='Enter your name'
returnKeyType='next'
onSubmitEditing={() => this.emailInput.focus()}
/>
<TextInput style={styles.input}
placeholder='Enter your email'
returnKeyType='next'
autoCapitalize='none'
keyboardType="email-address"
autoCorrect={false}
onSubmitEditing={() => this.passwordInput.focus()}
ref={(input)=> this.emailInput=input}
/>
<TextInput style={styles.input}
placeholder='Enter your password'
returnKeyType='go'
secureTextEntry
ref={(input) => this.passwordInput = input}
/>
<TouchableOpacity style={styles.buttonContainer}
onPress={() => this.props.navigation.navigate('Login')}>
<Text style={styles.buttontext}>Sign Up</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
export default RegisterPage
const styles = StyleSheet.create({
container: {
padding: 20,
justifyContent: 'center',
alignItems: 'stretch',
backgroundColor: '#ecf0f1',
flex: 1
},
input: {
paddingLeft: 20,
borderRadius: 50,
height: 50,
fontSize: 20,
backgroundColor: 'white',
borderWidth: 1,
borderColor: '#1abc9c',
marginBottom: 20,
color: '#34495e'
},
buttonContainer: {
height: 50,
borderRadius: 50,
backgroundColor: '#1abc9c',
paddingVertical: 10,
justifyContent: 'center'
},
buttontext: {
textAlign: 'center',
color: '#ecf0f1'
}
})
..........................................................................................................................................................................................................................
Home.js
import React, { Component } from 'react'
import { View, Text } from 'react-native'
class Home extends Component{
render(){
return(
<View>
<Text> WelCome page!</Text>
</View>
)
}
}
export default Home
..............................................................................................................................................................................................................................
App.js
import React, { Component, Fragment } from 'react'
import { View, Text, StyleSheet, StatusBar, Button } from 'react-native'
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack'
import LoginScreen from './src/components/LoginScreen'
import RegisterPage from './src/components/Register'
import Home from './src/components/Home'
const StackNavigator = createStackNavigator({
Login: { screen: LoginScreen },
Register: { screen: RegisterPage },
Home:{ screen:Home}
})
const AppContainer = createAppContainer(StackNavigator)
class App extends Component {
render() {
return (
<AppContainer />
)
}
}
export default App
..............................................................................................................................................................................................................................
Example: #12
..............................................................................................................................................................................................................................
Example: #13 [ Validate Forms ]
import React, { Component } from 'react'
import { View, Text, TextInput, StyleSheet, Button } from 'react-native'
class App extends Component{
constructor(props){
super(props)
this.state={
email:'',
password:''
}
}
onValidate_fields =()=>{
const { email, password }= this.state
if(email == ''){
alert('Enter the Email fields')
return false
}
else if (password ==''){
alert ('Enter the password fileds')
return false
}
return true
}
onSubmit=()=>{
if(this.onValidate_fields()){
alert('Success full !')
}
}
render(){
return(
<View style={styles.container}>
<TextInput style={styles.input}
placeholder='Enter email'
onChangeText={(email)=>this.setState({email:email})}
onSubmitEditing={() => this.passwordInput.focus()}
/>
<TextInput style={styles.input}
placeholder='Enter password'
onChangeText={(password)=>this.setState({password:password})}
ref={(input) => this.passwordInput = input}
/>
<Button title='submit' color='green' onPress={this.onSubmit}>
</Button>
</View>
)
}
}
export default App
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignContent:'center',
padding:40,
},
input:{
height:50,
borderBottomColor:'#000',
borderWidth:2,
borderRadius:50,
marginBottom:20
}
})
..............................................................................................................................................................................................................................
Example: #14
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
StatusBar ,
TouchableOpacity
} from 'react-native';
export default class Login extends Component {
render() {
return(
<View style={styles.container}>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Don't have an account yet?</Text>
<TouchableOpacity onPress={this.signup}><Text style={styles.signupButton}> Signup</Text></TouchableOpacity>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container : {
backgroundColor:'#455a64',
flex: 1,
alignItems:'center',
justifyContent :'center'
},
signupTextCont : {
flex: 1,
alignItems:'flex-end',
justifyContent :'center',
paddingVertical:16,
flexDirection:'row'
},
signupText: {
color:'rgba(255,255,255,0.6)',
fontSize:16
},
signupButton: {
color:'#ffffff',
fontSize:16,
fontWeight:'500'
}
});
..............................................................................................................................................................................................................................
Example: #15
import React, { Component } from 'react'
import { View, Text, ActivityIndicator, FlatList, Image, TouchableOpacity, ToastAndroid } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
isLoading:true,
users: []
}
}
renderItem = ({ item }) => {
return (
<TouchableOpacity style={{flex:1, flexDirection:'row',}}
onPress={()=>ToastAndroid.show(item.title, ToastAndroid.SHORT)}
>
<Image source={{ uri: item. thumbnailUrl}} style={{ width: 100, height: 100 }} />
<View>
<Text>{item.id}</Text>
<Text>{item.title}</Text>
</View>
</TouchableOpacity>
)
}
ItemSeparatorComponent=()=>{
return(
<View style={{height:2, backgroundColor:'black', width:'100%'}}>
</View>
)
}
componentDidMount() {
//const url = 'https://randomuser.me/api/'
const url ='https://jsonplaceholder.typicode.com/photos/'
fetch(url)
.then(res => res.json())
.then(resJson => {
this.setState({
isLoading:false,
users: resJson,
})
})
.catch(error => {
console.log(error)
})
}
render() {
return (
this.state.isLoading
?
<View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<ActivityIndicator size='large' color='red' />
</View>
:
<FlatList
data={this.state.users}
keyExtractor={(item, index) => index.toString() }
renderItem={this.renderItem}
ItemSeparatorComponent={this.ItemSeparatorComponent}
>
</FlatList>
)
}
}
export default App
..............................................................................................................................................................................................................................
Example: #16 [StatusBar]
<StatusBar
backgroundColor='blue'
barStyle='light-content'
hidden={false}
translucent={true}
/>
Note - barStyle means text color will be changed
..............................................................................................................................................................................................................................
Example: #17 [Shadow]
import * as React from 'react';
import { Text, View, Image, StyleSheet } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
render() {
return (
<View style={[styles.container, styles.centerContent]}>
{/* First shadow variant */}
<View style={[styles.box, styles.centerContent, styles.shadow1]}>
<View style={styles.ball} />
</View>
{/* Second shadow variant */}
<View style={[styles.box, styles.centerContent, styles.shadow2]}>
<View style={styles.ball} />
</View>
{/* Third shadow variant */}
<View style={[styles.box, styles.centerContent, styles.shadow3]}>
<View style={styles.ball} />
</View>
</View>
);
}
}
function elevationShadowStyle(elevation) {
return {
elevation,
shadowColor: 'black',
shadowOffset: { width: 0, height: 0.5 * elevation },
shadowOpacity: 0.3,
shadowRadius: 0.8 * elevation
};
}
const styles = StyleSheet.create({
shadow1: elevationShadowStyle(5),
shadow2: elevationShadowStyle(10),
shadow3: elevationShadowStyle(20),
box: {
borderRadius: 8,
backgroundColor: 'white',
padding: 24
},
// supporting styles
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 24
},
centerContent: {
justifyContent: 'space-around',
alignItems: 'center'
},
ball: {
borderRadius: 128,
width: 128,
height: 128,
backgroundColor: 'lightblue'
}
});
..............................................................................................................................................................................................................................
Example: #18 [Shadow]
import React, { Component } from 'react';
import { Text, View, Image, StyleSheet } from 'react-native';
export default class App extends Component {
render() {
return (
<View style={{ marginVertical: 10 }}>
<View style={[styles.box, styles.shadow3, {marginBottom:10}]}>
<Text> Hello World!</Text>
</View>
<View style={[styles.box, styles.shadow3,{marginBottom:10}]}>
<Text> Hello World!</Text>
</View>
<View style={[styles.box, styles.shadow3,{marginBottom:10}]}>
<Text> Hello World!</Text>
</View>
<View style={[styles.box, styles.shadow3, {marginBottom:10}]}>
<Text> Hello World!</Text>
<Text> Hello World!</Text>
<Text> Hello World!</Text>
<Text> Hello World!</Text>
<Text> Hello World!</Text>
<Text> Hello World!</Text>
<Text> Hello World!</Text>
<Text> Hello World!</Text>
<Text> Hello World!</Text>
</View>
<View style={[styles.box, styles.shadow4]}>
<Text> Hello World new one!</Text>
</View>
<View style={{
}}>
<Text> Hello World! Span Kumar</Text>
</View>
</View>
)
}
}
// function elevationShadowStyle(elevation) {
// return {
// elevation,
// shadowColor: 'red',
// shadowOffset: { width: 0, height: 0.5 * elevation },
// shadowOpacity: 0.3,
// shadowRadius: 0.8 * elevation
// };
// }
function elevationShadowStyle(elevation) {
return {
shadowColor: '#000',
shadowOffset: { width: 5, height: 5 },
shadowOpacity: 0.8,
shadowRadius: 5,
elevation
};
}
const styles = StyleSheet.create({
shadow1: elevationShadowStyle(30),
shadow2: elevationShadowStyle(30),
shadow3: elevationShadowStyle(30),
shadow4: {
shadowOpacity: 0.3,
shadowRadius: 0.8,
shadowOffset: { width: 0, height: 0.5 },
},
box: {
borderRadius: 8,
backgroundColor: 'white',
padding: 24
},
// supporting styles
container: {
flex: 1,
// paddingTop: Constants.statusBarHeight,
backgroundColor: '#ddd',
padding: 24,
marginBottom: 10,
},
centerContent: {
justifyContent: 'space-around',
alignItems: 'center'
},
ball: {
borderRadius: 112,
width: 128,
height: 128,
backgroundColor: 'lightblue'
}
});
.........................................................................................................................................................................................................................
Example: #19 [Shadow]
import React, { Component } from 'react'
import { View, Text, StyleSheet, Dimensions } from 'react-native'
const { width, height}= Dimensions.get('window')
class App extends Component {
render() {
return (
<View style={styles.container}>
<View style={[styles.box,styles.shadows]}>
<Text style={{ fontSize: 40 }}> Hello... </Text>
<Text style={{ fontSize: 40 }}> Hello... </Text>
<Text style={{ fontSize: 40 }}> Hello... </Text>
</View>
</View>
)
}
}
export default App
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop:30,
},
box: {
borderRadius: 10,
backgroundColor: '#fff'
},
shadows:{
elevation:10,
shadowOpacity: 2.3,
shadowRadius: 50,
shadowColor: 'red',
shadowOffset: { height: 10, width: 10 },
}
})
Shadow generator
.............................................................................................................................................................................................................................
Example: #20 [Style ]
How do I hide the back arrow?
Solution:- Use headerLeft and set it to null
headerLeft: null
defaultNavigationOptions: {
headerLeft:null,
}
or
navigationOptions:
headerLeft:null
}
What if I do not want to show a header for some screens?
Solution: Set header to null
or
header: null
How do I add icons to my bottom navbar?
Solution: Use navigationOptions object tabBarIcon property.
import Icon from 'react-native-vector-icons/Ionicons'
const TabStack =createBottomTabNavigator({
Routes
},{
defaultNavigationOptions: ({ navigation }) => {
// navigationOptions: ({ navigation }) => {
tabBarIcon: ({ focused, tintColor }) => {
return <Icon focused={focused} name='md-menu' />
}
}
}
headerStyle: {
backgroundColor: 'black',
borderWidth: 1,
borderBottomColor: 'white'
}
headerTitleStyle: {
fontWeight: "bold",
color: "#fff",
zIndex: 1,
fontSize: 18,
lineHeight: 23,
fontFamily: "CircularStd-Bold"
}
How do I hide the back arrow?
Solution:- Use headerLeft and set it to null
headerLeft: null
code:-
defaultNavigationOptions: {
headerLeft:null
}
How do I hide the bottom tab bar for some detailed screens
which are sub screen’s of a parent tab?
code: -
<TouchableOpacity onPress={()=> this.props.navigation.navigate('OTP', {
hideTabBar: true
})}>
Inside navigationOptions of your createBottomTabNavigator
defaultNavigationOptions: ({ navigation }) => {
const { routes } = navigation.state;
let params = routes && routes[1] && routes[1].params;
return {
tabBarVisible:
params && params.hideTabBar != null ? !params.hideTabBar : true,
swipeEnabled:
params && params.hideTabBar != null ? !params.hideTabBar : true
}
}
Calling Custom Component
import React, { Component } from 'react'
import { View, Text, TouchableOpacity } from 'react-native'
import { createStackNavigator, createDrawerNavigator, createAppContainer } from 'react-navigation'
class Home extends Component {
static navigationOptions={
headerLeft:null,
}
render() {
return (
<View>
<Text>
Home Screen
</Text>
</View>
)
}
}
class Settings extends Component {
render() {
return (
<View>
<Text> Settings Screen </Text>
</View>
)
}
}
const About =()=>{
return(
<View>
<Text> About Screen </Text>
</View>
)
}
const Stack = createStackNavigator({
Home: {
screen: Home,
},
Settings: {
screen: Settings
},
About:{
screen: About
}
},{initialRouteName:'About',
defaultNavigationOptions:({navigation})=>({
headerRight:<TouchableOpacity onPress={()=> navigation.push('Home')}>
<Text>Home</Text>
</TouchableOpacity>,
headerStyle:{
backgroundColor:'grey'
}
})
})
const AppContainer = createAppContainer(Stack)
export default class extends Component {
render() {
return (
<AppContainer />
)
}
}
Happy Coding :)
...............................................................................................................................................................................................................................
BackgroundColor + Text enter
import React, { Component } from 'react'
import { View, Text, StyleSheet } from 'react-native'
class App extends Component {
render() {
return (
<View style={styles.container}>
<Text> Hello</Text>
</View>
)
}
}
export default App
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent:'center',
alignItems:'center',
backgroundColor:'#3e3f8f'
}
})
Happy Coding :)
...............................................................................................................................................................................................................................
import React, { Component } from 'react';
import { View, Text, TextInput, StyleSheet, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
class LogInScreen extends Component {
render() {
return (
<View style={styles.container}>
<View>
<Text style={{ color: '#fff', fontSize: 22, marginBottom: 10 }}>Code With Sapan</Text>
</View>
<View style={styles.logincontainer}>
<View style={styles.inputbar}>
<View style={{ height: 30, width: 30, marginTop: 4, alignItems: 'center', justifyContent: 'center', borderRightWidth: 1, borderRightColor: '#ebebeb' }}>
<Icon name="at" size={16} color="#4c4c4c" />
</View>
<TextInput
style={{
backgroundColor: '#fff',
color: '#000',
width: 300,
height: 40,
paddingTop: 5,
paddingLeft: 10,
paddingBottom: 5,
paddingRight: 10
}}
placeholder='Your Email Address'
/>
</View>
<View style={styles.seprator}></View>
<View style={styles.inputbar}>
<View style={{ height: 30, width: 30, marginTop: 4, alignItems: 'center', justifyContent: 'center', borderRightWidth: 1, borderRightColor: '#ebebeb' }}>
<Icon name="lock" size={16} color="#4c4c4c" />
</View>
<TextInput
style={{
backgroundColor: '#fff',
color: '#000',
width: 300,
height: 40,
paddingTop: 5,
paddingLeft: 10,
paddingBottom: 5,
paddingRight: 10
}}
placeholder='Your Password'
/>
</View>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<TouchableOpacity>
<Text style={{
backgroundColor: '#12132b',
color: '#fff',
fontSize: 16,
padding: 5,
width: 110,
height: 35,
textAlign: 'center',
marginRight: 20
}}> Register</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text style={{
backgroundColor: '#fff',
color: '#3e3f8f',
fontSize: 16,
padding: 5,
width: 110,
height: 35,
textAlign: 'center'
}}> Sign In</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
export default LogInScreen
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#3e3f8f'
},
logincontainer: {
padding: 5,
height: 90.8,
backgroundColor: '#fff',
marginBottom: 10
},
inputbar: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between'
},
seprator: {
borderBottomWidth: 0.8,
borderBottomColor: '#ebebeb',
marginBottom: 5,
marginTop: 5
}
});
Happy Coding :)
...............................................................................................................................................................................................................................
StatusBar
import React from 'react'
import { View, Text, StatusBar } from 'react-native'
const App = () => {
return (
<View>
<StatusBar backgroundColor='blue' barStyle='light-content'>
</StatusBar>
<Text> Hello </Text>
</View>
)
}
export default App
Tips dark : - content gives only white color battery or something.
import React from 'react'
import { View, Text, StatusBar } from 'react-native'
const App = () => {
return (
<View>
<StatusBar backgroundColor='blue' barStyle='dark-content'>
</StatusBar>
<Text> Hello </Text>
</View>
)
}
export default App
Tips dark : - content gives only black color battery or something
Happy Coding :)
...............................................................................................................................................................................................................................
Picker
import React, { Component, useState } from 'react'
import { View, Text, TouchableOpacity, Picker, } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import { createAppContainer, withNavigation, NavigationEvents } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack'
const HeaderRightMenu = withNavigation(({ navigation }) => {
const [language, setLanguage] = useState('java')
return (
<View style={{
flexDirection: 'row',
justifyContent: 'flex-end',
alignItems: 'center'
}}>
<Picker
selectedValue={language}
style={{ width: '100%', backgroundColor: 'transparent', marginHorizontal: 13, }}
onValueChange={(itemValue, itemIndex) => {
setLanguage(itemValue);
navigation.navigate('Profile')
navigation.navigate('Setting')
}}
>
<Picker.Item label="Java" value="java" />
<Picker.Item label="JavaScript" value="js" />
<Picker.Item label="Node.js" value="nj" />
<Picker.Item label="Express" value="es" />
</Picker>
<Icon name='ellipsis-v' size={25} style={{ position: 'absolute', right: 20 }} />
</View>
)
}
)
class Home extends Component {
render() {
return (
<View>
<Text> Home</Text>
</View>
)
}
}
class Profile extends Component {
render() {
return (
<View >
<Text> Profile</Text>
</View>
)
}
}
class Setting extends Component {
render() {
return (
<View >
<Text> Setting</Text>
</View>
)
}
}
const Stack = createStackNavigator({
Home: {
screen: Home,
navigationOptions: ({ navigation }) => ({
title: 'Home',
headerRight: <HeaderRightMenu />
})
},
Profile: {
screen: Profile,
navigationOptions: ({ navigation }) => ({
title: 'Profile',
})
},
Setting: {
screen: Setting,
navigationOptions: ({ navigation }) => ({
title: 'Setting',
})
}
},
{
headerLayoutPreset: 'center'
})
const AppContainer = createAppContainer(Stack)
class App extends Component {
render() {
return (
<AppContainer />
)
}
}
export default App
Happy Coding :)
...............................................................................................................................................................................................................................
Picker
import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet } from 'react-native'
class PickerExample extends Component {
state = {user: ''}
updateUser = (user) => {
this.setState({ user: user })
}
render() {
return (
<View>
<Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
<Picker.Item label = "Steve" value = "steve" />
<Picker.Item label = "Ellen" value = "ellen" />
<Picker.Item label = "Maria" value = "maria" />
</Picker>
<Text style = {styles.text}>{this.state.user}</Text>
</View>
)
}
}
const App = () => {
return (
<PickerExample />
)
}
export default App
const styles = StyleSheet.create({
text: {
fontSize: 30,
alignSelf: 'center',
color: 'red'
}
})
Happy Coding :)
...............................................................................................................................................................................................................................
Happy Coding :)
...............................................................................................................................................................................................................................
Happy Coding :)
...............................................................................................................................................................................................................................
Back Button
import React, { Component } from 'react'
import { View, Text, BackHandler, Button, Alert } from 'react-native'
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack'
class Home extends Component {
static navigationOptions = {
title: 'Home'
}
render() {
return (
<View>
<Text> Home</Text>
<View>
<Button title='Go to Profile' onPress={() => this.props.navigation.navigate('Profile')}></Button>
</View>
</View>
)
}
}
class Profile extends Component {
static navigationOptions = {
title: 'Profile',
headerLeft: null // no more available back arrow on the left corner
}
componentWillMount() {
this.back_Button()
BackHandler.addEventListener('hardwareBackPress', () => {
return true
})
}
componentWillUnmount() {
this.back_Button()
BackHandler.removeEventListener('hardwareBackPress', () => {
return true
})
}
back_Button = () => {
Alert.alert(
'Exit From App',
'Do you want to exit From App ?',
[
{ text: 'YES', onPress: () => BackHandler.exitApp() },
{ text: 'NO', onPress: () => console.log('no pressed') }
],
{ cancelable: false },
);
}
render() {
return (
<View>
<Text> Profile </Text>
</View>
)
}
}
const HomeStack = createStackNavigator({
Home: Home,
Profile: Profile
}, {
headerLayoutPreset: 'center',
headerMode: 'float'
}
)
const AppContainer = createAppContainer(HomeStack)
class App extends Component {
render() {
return (
<>
<AppContainer />
</>
)
}
}
export default App
.................................................................................................................................................................................................................................
React Native Picker
import React, { Component } from 'react'
import { View, Text, Picker } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
selectedLabel: ''
}
}
Show = (value) => {
this.setState({ selectedLabel: value })
}
render() {
return (
<View>
<Text> Hello World!</Text>
<Picker selectedValue={this.state.selectedLabel} onValueChange={this.Show}>
<Picker.Item label="Select a Course" value="0" color='red' />
<Picker.Item label="React" value="5000" />
<Picker.Item label="PHP" value="1000" />
<Picker.Item label="Java" value="8000" />
<Picker.Item label=".Net" value="9000" />
</Picker>
</View>
)
}
}
export default App
.................................................................................................................................................................................................................................
Get Value of TextInput Component in React Native
import React, { Component } from 'react'
import { View, Text, TextInput, Button } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
number: ''
}
}
Display = () => {
var N1 = this.state.number
alert(N1)
}
render() {
return (
<View>
<Text> Hello World!</Text>
<TextInput onChangeText={number => this.setState({ number })} />
<Button title='Click Here' onPress={this.Display} style={{ margin: 20 }} ></Button>
</View>
)
}
}
export default App
.................................................................................................................................................................................................................................
import React, { Component } from 'react'
import { View, Text, TextInput, Button } from 'react-native'
class App extends Component {
constructor(props) {
super(props)
this.state = {
number: ''
}
}
Display = () => {
var N1 = this.state.number
alert(N1)
}
render() {
return (
<View>
<Text> Hello World!</Text>
<TextInput style={{borderWidth:1, borderColor:'red', margin:10}} multiline={true} numberOfLines={2}/>
<TextInput style={{borderWidth:1, borderColor:'red', margin:10}} secureTextEntry={true}/>
<TextInput style={{borderWidth:1, borderColor:'red', margin:10}} keyboardType='number-pad'/>
<TextInput style={{borderWidth:1, borderColor:'red', margin:10}} defaultValue="React" editable={false}/>
<TextInput style={{borderWidth:1, borderColor:'red', margin:10}} maxLength={5}/>
<TextInput style={{borderWidth:1, borderColor:'red', margin:10}} value="Express"/>
<TextInput style={{borderWidth:1, borderColor:'red', margin:10}} defaultValue="React" editable={false}/>
<TextInput style={{borderWidth:1, borderColor:'red', margin:10}} defaultValue="React Native" editable={false}/>
</View>
)
}
}
export default App
.................................................................................................................................................................................................................................
LetterSpacing and Line Height
import React, { Component } from 'react'
import { View, Text, TextInput, Button } from 'react-native'
class App extends Component {
render() {
return (
<View>
<Text style={{letterSpacing: 20}}> Hello World!</Text>
<Text style={{lineHeight: 100}}> Hello World!</Text>
</View>
)
}
}
export default App
...................................................................................................
..............................................................................................................................
MAP
export const App = () => {
const data = {
cars: {
Nissan: [
{
model: 'Sentra',
doors: 4,
},
{
model: 'Maxima',
doors: 4,
},
{
model: 'Skyline',
doors: 2,
},
],
Ford: [
{
model: 'Taurus',
doors: 4,
},
{
model: 'Escort',
doors: 4,
},
],
},
};
const brands = Object.keys(data.cars);
return brands.map(brand => (
<View style={{padding: 20}}>
<Text style={{fontWeight: '700'}}> {brand} :</Text>
{data.cars[brand].map(model => (
<View style={{marginBottom: 10}}>
<Text> Model : {model.model}</Text>
<Text> Doors : {model.doors}</Text>
</View>
))}
</View>
));
};
.................................................................................................................................................................................................................................
import React, { Component } from 'react'
import { View, Text, ImageBackground, StyleSheet, ScrollView } from 'react-native'
import Home from './src/assets/components/Home'
class App extends Component {
render() {
return (
<ImageBackground
source={require('./src/assets/bg.jpg')}
style={styles.container}>
< View style={styles.overlayContainer}>
<View style={styles.top}>
<Text style={styles.header}> H O M E</Text>
</View>
<View style={styles.menuContainer}>
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
<Home itemImage={require('./src/assets/he.png')} />
</View>
</View>
</ImageBackground>
)
}
}
export default App
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
height: '100%'
},
overlayContainer: {
flex: 1,
backgroundColor: 'rgba(47, 163, 218, .3)'
},
top: {
height: '50%',
justifyContent: 'center',
alignItems: 'center'
},
header: {
color: '#fff',
fontSize: 28,
borderColor: '#fff',
borderWidth: 2,
padding: 20,
paddingLeft: 40,
paddingRight: 40,
backgroundColor: 'rgba(255,255,255,.1)'
},
menuContainer: {
height: '40%',
flexDirection: 'row',
flexWrap: 'wrap'
}
})
....
Home.js
import React, { Component } from 'react'
import { View, Text, StyleSheet, Image, ScrollView } from 'react-native'
class Home extends Component {
render() {
return (
<View style style={styles.container}>
<Image source={this.props.itemImage}
style={styles.img}
/>
</View>
)
}
}
export default Home
const styles = StyleSheet.create({
container: {
width: '33.3333%',
height: '50%',
padding: 20,
},
img: {
width: '100%',
height: '100%',
opacity: 0.8,
borderColor: '#fff',
borderWidth: 3
}
})
.................................................................................................................................................................................................................................
Border Radius Rounded
import React, { Component} from 'react'
import { View, Text, StyleSheet, Dimensions, TouchableOpacity } from 'react-native'
class App extends Component{
render(){
return(
<TouchableOpacity
style = {{
borderRadius: Math.round(Dimensions.get('window').width + Dimensions.get('window').height) / 2,
width: Dimensions.get('window').width * 0.9,
height: Dimensions.get('window').width * 0.9,
backgroundColor:'#f00',
justifyContent: 'center',
alignItems: 'center'
}}>
<Text> Hey, you can do that way </Text>
</TouchableOpacity>
)
}
}
export default App
.................................................................................................................................................................................................................................
PIXEL
..................................................................................................................................................................................................................................
import React from 'react'
import { View, Text, Platform, PixelRatio, Dimensions } from 'react-native'
const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window')
//iPhone 6s width 375 for
const scale = SCREEN_WIDTH / 375
function normalize(size) {
const newSize = size * scale
if (Platform.OS == "ios") {
return Math.round(PixelRatio.roundToNearestPixel(newSize))
} else {
return Math.round(PixelRatio.roundToNearestPixel(newSize)) - 2
}
}
const Home = ({ navigation }) => {
return (
<View>
<Text style={{ fontFamily: 'open-sans-bold', fontSize: normalize(22) }}> INDIARESULTS</Text>
</View>
)
}
export default Home
............................................................................................................................................................................................................................
HTTP Requests not Working in Android Pie React Native Issue Fix
First of all navigate to YourProject > android > app > src > main > res and create a folder named xml. Inside xml folder create a xml file named network_security_config.xml . Now copy paste the code given below to the file.
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors> <certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
The code given above allows all http requests. Now, refer the created xml file to Android Manifest file which is placed at YourProject > android > app > src > main > AndroidManifest.xml and add android:networkSecurityConfig property as given below.
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config"
... >
...
</application>
</manifest>
https://developer.android.com/training/articles/security-config
............................................................................................................................................................................................................................
react-native-raw-bottom-sheet
............................................................................................................................................................................................................................
NEWS Project
import React from 'react'
import { View, StyleSheet, Text, Image, Dimensions } from 'react-native'
const { width, height } = Dimensions.get('window')
const Home = ({item }) => {
return (
<View style={styles.cardView}>
<Text style={styles.title}> {item.title}</Text>
<Text style={styles.author}>{item.author} </Text>
<Image style={styles.image} source = {{uri: item.urlToImage}}/>
<Text style={styles.description}>{item.description}</Text>
</View>
)
}
const styles = StyleSheet.create({
cardView: {
backgroundColor: 'white',
margin: width * 0.03,
borderRadius: width * 0.05,
shadowColor: '#000',
shadowOffset: { width:0.5, height: 0.5 },
shadowOpacity: 0.5,
shadowRadius: 3,
elevation:10
},
title: {
marginHorizontal: width * 0.05,
marginVertical: width * 0.03,
color: 'black',
fontSize: 20,
fontWeight: 'bold'
},
description: {
marginVertical: width * 0.05,
marginHorizontal: width * 0.02,
color: 'gray',
fontSize: 18
},
image: {
height: height / 6,
marginLeft: width * 0.05,
marginRight: width * 0.05,
marginVertical: height * 0.02
},
author: {
marginBottom: width * 0.0,
marginHorizontal: width * 0.05,
fontSize: 15,
color: 'gray'
}
})
export default Home
...............................
Config/Api.js
import axios from 'axios'
export default axios.create({
baseURL:'https://newsapi.org/v2/'
})
...............................
App.js
import React, { useEffect, useState } from 'react'
import { View, Text, FlatList } from 'react-native'
import Home from './src/components/Home'
import Api from './src/configs/Api'
const Data = () => {
const [news, setNews] = useState([]);
useEffect(() => {
getNewsFromAPI()
}, [])
const getNewsFromAPI = async () => {
Api.get('top-headlines?country=us&apiKey=f5de4862c2e95aef')
.then(response => {
setNews(response.data);
})
.catch(error => {
console.log(error)
})
}
if (!news) {
return null
}
return (
<View>
<FlatList data={news.articles}
keyExtractor={(item, index) => 'key' + index}
renderItem={({ item }) => {
return <Home item={item} />
}}
/>
</View>
)
}
const App = () => {
return (
<View style={{ flex: 1 }}>
<Data />
</View>
)
}
export default App
............................................................................................................................................................................................................................
const deviceWidth = Dimensions.get('window').width
const deviceHeight = Dimensions.get('window').height
const calcHeight = x => PixelRatio.roundToNearestPixel((deviceHeight * x) / 100)
const calcWidth = x => PixelRatio.roundToNearestPixel((deviceWidth * x) / 100)
............................................................................................................................................................................................................................
<ScrollView style ={{ width :'100%'}>
<View>
</View>
</ScrollView>
............................................................................................................................................................................................................................
............................................................................................................................................................................................................................
How to rename the Package
Step: #1
react-native-rename
Installation
yarn global add react-native-rename
or
npm install react-native-rename -g
Tips
better to have back-up
or
Copy the two java files
android\app\src\main\java\com\normalpro
- Because the two java files willbe delete. so need to copy the java Files.
Example
react-native-rename "helloWorld"
In mycase project name is helloWorld.
Before
After
react-native-rename "helloWorld"
Now create a two Java File inside android\app\src\main\java\com\helloworld
1) MainActivity.java
2) MainApplication.java
............................................................................................................................................................................................................................
Display a modal prompting for app exit
// packages
import {Alert} from 'react-native';
const exitAlert = () => {
Alert.alert(
'Confirm exit',
'Do you want to quit the app?'
[
{text: 'CANCEL', style: 'cancel'},
{text: 'OK', onPress: () => BackHandler.exitApp()}
]
);
};
export {exitAlert};
............................................................................................................................................................................................................................
BACK BUTTON
import React, { useEffect } from 'react'
import { View, Text, Button, BackHandler } from 'react-native'
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack'
const Home = ({ navigation }) => {
return (
<>
<Text> Home Screen </Text>
<Button title='Go to About' onPress={() => navigation.navigate('About')}></Button>
</>
)
}
const About = () => {
const handleBackButton = () => {
return true;
}
useEffect(() => {
BackHandler.addEventListener('hardwareBackPress', handleBackButton)
return () => BackHandler.removeEventListener('hardwareBackPress', handleBackButton)
}, [])
return (
<>
<Text> About Screen </Text>
</>
)
}
const Stack = createStackNavigator({
Home,
About
})
const AppContainer = createAppContainer(Stack)
const App = () => {
return (
<AppContainer />
)
}
export default App
............................................................................................................................................................................................................................
Custom Fonts in React Native | Add Google Fonts
Step :#1
create a two folder
assets
fonts
Step :#2
download fonts and Extract it, and past the inside assets/fonts folder
https://fonts.google.com/?selection.family=Sacramento
Step :#3
App.js
import React, { Component } from 'react'
import { View, Text } from 'react-native'
class App extends Component {
render() {
return (
<>
< Text style={{ fontFamily: 'LobsterTwo-BoldItalic', fontSize: 20 }}> Hello World</Text>
<Text style={{ fontSize: 20 }}> Hello World</Text>
<Text style={{ fontSize: 20, fontFamily: 'Sacramento-Regular' }}>Hello World</Text>
</>
)
}
}
export default App
react-native link
or
npx react-native link
run the project
npx react-native run-android
Common Error
"rnpm": {
"assets": [
"./assets/fonts/"
]
}
Step: #1
Adding the Assets
As a first step, create an assets folder in the root of your project. Then create a fonts folder inside it. Finally, copy your font files into the fonts folder.
Step : #2
react-native.config.js
Create a file in the root folder of your project called
react-native.config.js, and add the following:
module.exports = {
assets: ['./assets/fonts/']
};
like that.
Then, run the following command in your terminal.
react-native link
You should be greeted with something similar to this.
Okay
Step : #3
This should take care of copying the assets and creating references for both iOS and Android.
On Android, it will copy the font files to
/android/app/src/main/assets/fonts.
On iOS, it will modify your
Info.plist file to include references to your fonts, similar to this.
<key>UIAppFonts</key>
<array>
<string>Ubuntu-Bold.ttf</string>
</array>
Step : #4
To reduce the risk of confusion, try to name your file the same way as it shows up in FontBook (macOS) when you double-click on it. Failing that, you can always use platform specific code, like this.
const styles = StyleSheet.create({
custom: {
fontFamily: Platform.OS === "ios" ? 'AsCalledByFontBook' : 'some_filename.ttf',
fontSize: 32
}
});
............................................................................................................................................................................................................................
............................................................................................................................................................................................................................
............................................................................................................................................................................................................................
............................................................................................................................................................................................................................
React Native [DOT ENV ]
Install
react-native-dotenv
yarn add react-native-dotenv
Folder Structure as below
Add one in side the babel.config.js
"module:react-native-dotenv"
....................................
.env
API_URL =https://example.com
............................................................................................................................................................................................................................
React Native [DOT ENV || PLATFORM SPECIFIC ]
.env
API_URL =https://localhost:3000
ANDROID_KEY=Android1234555555555
iOS_KEY =iOSKey123456789
................................
config.js
import { Platform } from 'react-native'
import { API_URL, ANDROID_KEY, iOS_KEY } from 'react-native-dotenv'
export default {
API_URL,
ANDROID_KEY,
iOS_KEY,
MAP_KEY:Platform.select({
ios: iOS_KEY,
android: ANDROID_KEY
})
}
....................................
App.js
import React from 'react'
import { View, Text } from 'react-native'
import config from './src/config/config'
const App = () => {
return (
<>
<Text> Hello World!</Text>
<Text>{config.API_URL}</Text>
<Text>{config.MAP_KEY}</Text>
</>
)
}
export default App
............................................................................................................................................................................................................................
React Native Document & PDF Viewer
yarn add react-native-webview
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
export default function App() {
return (
<WebView
source={{ uri: "https://reactnativemaster.com/wp-content/uploads/2020/02/React-native-document-viewer-pdf-sample.pdf" }} />
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
On Android
uri : '/sdcard/Download/test-pdf.pdf'
On IOS
uri: 'test-pdf.pdf'
Result
Happy Coding :)
............................................................................................................................................................................................................................
React Native Timeline Flatlist
npm i react-native-timeline-flatlist
App.js
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import Timeline from 'react-native-timeline-flatlist';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data:
[
{time: '09:00', title: 'BreakFast', description: 'I had breakfast from a wonderful restaurant and the food was super tasty.'},
{time: '11:00', title: 'Tea Break', description: 'I made a tea myself and drink it with a packet of biscuits.'},
{time: '13:00', title: 'Lunch', description: 'I ate lunch from nearby hotel but food was just okay.'},
{time: '16:00', title: 'Tea Break', description: 'Ate two snacks.'},
{time: '20:00', title: 'Dinner', description: 'This time I prepared dinner looking a youtube tutorial.'}
]
};
}
render() {
return (
<View style={styles.container}>
<Timeline
circleSize={20}
separator={true}
circleColor='blue'
lineColor='gray'
timeStyle={styles.time}
descriptionStyle={styles.description}
style={styles.list}
data={this.state.data}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor:'white'
},
list: {
flex: 1,
marginTop:20,
},
time: {
textAlign: 'center',
backgroundColor:'gray',
fontSize: 12,
color:'white',
padding:5,
borderRadius:13,
overflow: 'hidden'
},
description: {
color: 'gray'
}
});
............................................................................................................................................................................................................................
react native netinfo
import React, { Component } from 'react'
import { View, Text, Button, Platform } from 'react-native'
import NetInfo from "@react-native-community/netinfo";
class App extends Component {
constructor(props) {
super(props)
}
CheckConnectivity = () => {
if (Platform.OS === 'android') {
NetInfo.fetch().then(isConnected => {
isConnected ? alert("You are online!") : alert("you are offline!");
});
} else {
NetInfo.addEventListener("connection change", this.handleFirstConnectivityChange)
}
}
handleFirstConnectivityChange = isConnected => {
NetInfo.removeEventListener('Connection Change', this.handleFirstConnectivityChange);
isConnected ? alert("you are online") : ("you are offline")
}
render() {
return (
<View>
<Text> Hello world</Text>
<Button title='Check' onPress={() => this.CheckConnectivity()} />
</View>
)
}
}
export default App
.................................................................................................................................................................................................................................
.........................................................................................................................................................................................................................................
<KeyboardAvoidingView
behavior={Platform.OS == "ios" ? "padding" : "height"}
style={styles.container}
></Keyboard avoidingView>