Adding background image to create-react-native project - javascript

I am trying to insert a background image into my create-react-native project. I would like to be able to add this image: https://i.pinimg.com/736x/80/29/a9/8029a9bf324c79b4803e1e5a2aba25f3--costume-makeup-iphone-wallpaper.jpg. I have tried applying it to the stylesheet but it is not accepting the background-image tag. I am very new at react.
import React from 'react';
import { StyleSheet, Text, View, TextInput, Button} from 'react-native';
import ListItem from "/Users/Westin/assignment5/ListItem";
export default class App extends React.Component {
state ={
thing: "",
things: [],
};
thingValueChanged = value =>{
//alert(value);
this.setState({
thing: value
});
}
onClickingAdd = () =>
{
if(this.state.thing === "")
{
return;
}
this.setState(prevState => {
return {
things: prevState.things.concat(prevState.thing)
};
});
}
render() {
const thingsOut = this.state.things.map((thing,i) => (<ListItem key = {i} thing={thing} />))
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>My Favourite Things</Text>
</View>
<View style={styles.input}>
<TextInput
value={this.state.thing}
placeholder="Add your favourite things"
style={styles.inputbox}
onChangeText={this.thingValueChanged}
/>
<Button
title="Add"
style={styles.addButton}
onPress = {this.onClickingAdd}
/>
</View>
<View>
{thingsOut}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#e6eeff',
alignItems: 'center',
justifyContent: 'flex-start',
paddingTop: 30,
},
header: {
padding: 10,
},
headerText: {
fontSize: 30,
color: '#003cb3',
},
inputbox: {
borderWidth: 1,
height: 40,
width: "70%",
},
addButton: {
width: "30%"
},
input: {
flexDirection: "row",
width: '100%',
justifyContent: "space-evenly",
alignItems: "center",
}
});
This is the code I tried to run
import React from 'react';
import { StyleSheet, Text, View, TextInput, Button, Image } from 'react-native';
import ListItem from "/Users/Westin/assignment5/ListItem";
const remote = 'https://i.pinimg.com/736x/80/29/a9/8029a9bf324c79b4803e1e5a2aba25f3--costume-makeup-iphone-wallpaper.jpg';
export default class BackgroundImage extends Component {
render() {
const resizeMode = 'center';
return (
<Image
style={{
flex: 1,
resizeMode,
}}
source={{ uri: remote }}
/>
);
}
}
AppRegistry.registerComponent('BackgroundImage', () => BackgroundImage);
export default class App extends React.Component {
state ={
thing: "",
things: [],
};
thingValueChanged = value =>{
//alert(value);
this.setState({
thing: value
});
}
onClickingAdd = () =>
{
if(this.state.thing === "")
{
return;
}
this.setState(prevState => {
return {
things: prevState.things.concat(prevState.thing)
};
});
}
render() {
const thingsOut = this.state.things.map((thing,i) => (<ListItem key = {i} thing={thing} />))
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.headerText}>My Favourite Things</Text>
</View>
<View style={styles.input}>
<TextInput
value={this.state.thing}
placeholder="Add your favourite things"
style={styles.inputbox}
onChangeText={this.thingValueChanged}
/>
<Button
title="Add"
style={styles.addButton}
onPress = {this.onClickingAdd}
/>
</View>
<View>
{thingsOut}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
backgroundColor: 'black',
opacity: 0.5,
justifyContent: 'flex-start',
paddingTop: 30,
},
header: {
padding: 10,
},
headerText: {
fontSize: 30,
color: '#003cb3',
},
inputbox: {
borderWidth: 1,
height: 40,
width: "70%",
backgroundColor: 'white',
},
addButton: {
width: "30%"
},
input: {
flexDirection: "row",
width: '100%',
justifyContent: "space-evenly",
alignItems: "center",
}
});
It said I cant run two export classes

This code works for me:
import React from 'react';
import { StyleSheet, Text, View, ImageBackground } from 'react-native';
export default class App extends React.Component {
render() {
return (
<ImageBackground source=
{ {uri: 'https://i.pinimg.com/736x/80/29/a9/8029a9bf324c79b4803e1e5a2aba25f3--costume-makeup-iphone-wallpaper.jpg' } }
style={styles.container}
>
<Text>Some</Text>
<Text>Text</Text>
<Text>Centered</Text>
<Text>In</Text>
<Text>Columns</Text>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
width: '100%'
},
});
You can read more about <ImageBackground/> here: https://facebook.github.io/react-native/docs/images#background-image-via-nesting

Related

tabBarOptions not applied to project (React Native)

I am creating a small app that has a to-do list and a calendar. At the bottom is a bottom tab navigator. Everything works and is functional, however, when I try to add style: {} inside tabBarOptions it isn't being applied. Changing activeTintColor, inactiveTintColor and labelStyle works just fine.
I tried to create a stylesheet and replace everything inside tabBarOptions, but that didn't work. My main goal is to simply create a slightly larger bar along the bottom of the screen. I don't even want a crazy custom navigation bar, just slightly larger so I can make the items inside a little bigger.
MainContainer Class:
import React from 'react';
import {StyleSheet} from 'react-native';
import {NavigationContainer} from '#react-navigation/native';
import {createBottomTabNavigator} from '#react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons'
//screens
import Calendar from './screens/Calendar';
import ToDoList from './screens/ToDoList';
// Screen names
const calendarName = 'Calendar';
const ToDoListName = 'To Do List';
const Tab = createBottomTabNavigator();
export default function MainContainer() {
return (
<NavigationContainer>
<Tab.Navigator
tabBarOptions={{
activeTintColor: 'tomato',
inactiveTintColor: 'black',
labelStyle: {paddingBottom: 10, fontSize: 10},
style: {padding: 10, height: 70},
}}
initialRouteName={ToDoListName}
screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
let iconName;
let rn = route.name;
if (rn === ToDoListName) {
iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
} else if (rn === calendarName) {
iconName = focused ? 'calendar' : 'calendar-outline'
}
return <Ionicons name={iconName} size={size} color={color}/>
},
})}>
<Tab.Screen name={ToDoListName} component={ToDoList}/>
<Tab.Screen name={calendarName} component={Calendar}/>
</Tab.Navigator>
</NavigationContainer>
)
}
For reference here is my ToDoList class
import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity, Platform, Keyboard } from 'react-native';
import Task from '../../components/Task';
import React, { useState } from 'react';
import { ScrollView } from 'react-native-web';
export default function ToDoList() {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice(index, 1);
setTaskItems(itemsCopy)
}
return (
<View style={styles.container}>
{/* Scroll View when list gets longer than page */}
<ScrollView contentContainerStyle={{
flexGrow: 1
}} keyboardShouldPersistTaps='handled'>
{/*Today's Tasks */}
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Today's Tasks</Text>
<View style={styles.items}>
{/* This is where the tasks will go*/}
{
taskItems.map((item, index) => {
return (
<TouchableOpacity key={index} onPress={() => completeTask(index)}>
<Task text={item} />
</TouchableOpacity>
)
})
}
</View>
</View>
</ScrollView>
{/* Write a task section */}
{/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.writeTaskWrapper}>
<TextInput style={styles.input} placeholder={'Write a task'} value={task} onChangeText={text => setTask(text)} />
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrapper}>
<Text style={styles.addText}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#E8EAED',
},
tasksWrapper: {
paddingTop: 20,
paddingHorizontal: 20,
},
sectionTitle: {
fontSize: 24,
fontWeight: 'bold',
},
items: {
marginTop: 30,
},
writeTaskWrapper: {
position: 'absolute',
bottom: 20,
paddingLeft: 10,
paddingRight: 10,
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
input: {
paddingVertical: 15,
width: 250,
paddingHorizontal: 15,
backgroundColor: '#FFF',
borderRadius: 60,
borderColor: '#C0C0C0',
borderWidth: 1,
},
addWrapper: {
width: 60,
height: 60,
backgroundColor: '#FFF',
borderRadius: 60,
justifyContent: 'center',
alignItems: 'center',
borderColor: '#C0C0C0',
borderWidth: 1,
},
addText: {
},
});
And my Calendar class
import * as React from 'react';
import { View, Text } from 'react-native';
export default function Calendar(){
return(
<View>
<Text>Calendar Will go here</Text>
</View>
)
}
I made a Task component for the ToDoList. Not sure if you need it to solve this but I'll paste it here anyway.
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TouchableOpacity } from 'react-native-web';
const Task = (props) => {
return (
<View style={styles.item}>
<View style={styles.itemLeft}>
<View style={styles.square}></View>
<Text style={styles.itemText}>{props.text}</Text>
</View>
<View style={styles.circular}></View>
</View>
)
}
const styles = StyleSheet.create({
item: {
backgroundColor: '#FFF',
padding: 15,
borderRadius: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: 20,
},
itemLeft: {
flexDirection: 'row',
alignItems: 'center',
flexWrap: 'wrap',
},
square: {
width: 24,
height: 24,
backgroundColor: '#55BCF6',
opacity: .4,
borderRadius: 5,
marginRight: 15,
},
itemText: {
maxWidth: '80%',
},
circular: {
width: 12,
height: 12,
borderColor: '#55BCF6',
borderWidth: 2,
borderRadius: 5
},
});
export default Task;
It sounds like you are looking for the tabBarStyle property. You should be able to rename style (which is not a supported prop of the tab navigator) to tabBarStyle.
Here's the spot in the docs that mentions this. https://reactnavigation.org/docs/bottom-tab-navigator#tabbarstyle
What I ended up doing to solve this was to put the styling inside the screenOptions. I didn't want to do this because I wanted to separate the styling from the logic, but it solved the problem for me. See code below:
export default function MainContainer() {
return (
<NavigationContainer>
<Tab.Navigator
initialRouteName={ToDoListName}
screenOptions={({route}) => ({
tabBarIcon: ({focused, color, size}) => {
let iconName;
let rn = route.name;
if (rn === ToDoListName) {
iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
} else if (rn === calendarName) {
iconName = focused ? 'calendar' : 'calendar-outline'
}
return <Ionicons name={iconName} size={size} color={color}/>
},
activeTintColor: 'tomato',
inactiveTintColor: 'black',
tabBarShowLabel: false,
tabBarStyle: {padding: 10, height: 100, backgroundColor: 'black'},
})}>
<Tab.Screen name={ToDoListName} component={ToDoList}/>
<Tab.Screen name={calendarName} component={Calendar}/>
</Tab.Navigator>
</NavigationContainer>
)
}

View dont refresh when add a new json object in array. REACT NATIVE

the program compiles perfect, but when I scan a product, it doesn't refresh in the view.
I have mounted a mysql xampp with all the products. when querying a barcode. I get in response the detail of the product, and, add the json response with parse object in a array.
the view refresh when click TouchableOpacity, later of scan a product.
import React, {Component, useState, useEffect} from 'react';
import {Dimensions,Image, View, Text,AsyncStorage, TouchableOpacity, Grid, StyleSheet, ScrollView,ToastAndroid} from 'react-native';
import { SearchBar, Card, Icon } from 'react-native-elements';
import { BarCodeScanner } from 'expo-barcode-scanner';
//import { NumberList } from './NumberList';
const {width, height} = Dimensions.get('window');
const urlApi = "http://192.168.1.24/rst/api/getProduct.php";
const numbers = [1,2,3,4,5,6];
class SaleScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
scan: false,
result: null,
ScanResult: false,
hasPermission: true,
setHasPermission: true,
productos: [],
jwt: null,
};
//this.componentDidMount();
}
async componentDidMount(){
let _jwt = await AsyncStorage.getItem('userToken');
this.setState({
jwt: _jwt
});
}
_searchProduct = async (data) => {
try {
let response = await fetch(urlApi,{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer '+this.state.jwt
},
body: JSON.stringify({
CodiBarra: data
})
});
let responseJson = await response.json();
//console.log(responseJson);
if (responseJson.codibarra === null) {
//console.log("retorna falso");
return false;
}
else
{
if(this.state.productos != null)
{
this.state.productos.push(responseJson[0]);
//this.setState({productos: this.state.productos.push(responseJson[0])})
//console.log(this.state.productos);
}
else
{
this.state.productos.push(responseJson[0]);
}
}
} catch (error) {
console.error(error);
}
};
render(){
const { scan, ScanResult, result, hasPermission, setHasPermission, productos } = this.state;
const activeBarcode = ()=> {
this.setState({
scan: true
})
}
const handleBarCodeScanned = async ({ type, data }) => {
//console.log('scanned data' + data);
this.setState({result: data, scan: false, ScanResult: false});
this._searchProduct(data);
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style= {{flex: 1}}>
{productos.length == 0 &&
<View style = {styles.button}>
<TouchableOpacity
onPress= {activeBarcode}
style={{
borderWidth:1,
borderColor:'rgba(0,0,0,0.2)',
alignItems:'center',
justifyContent:'center',
width:50,
height:50,
backgroundColor:'#fff',
borderRadius:50,
position: 'absolute',
marginTop: 10,
marginLeft: width - 100
}}
>
<Icon
type="font-awesome"
name="barcode"
/>
</TouchableOpacity>
</View>
}
{productos.length>0 &&
<View style={{flex:1}}>
<View style = {styles.button}>
<TouchableOpacity
onPress= {activeBarcode}
style={{
borderWidth:1,
borderColor:'rgba(0,0,0,0.2)',
alignItems:'center',
justifyContent:'center',
width:50,
height:50,
backgroundColor:'#fff',
borderRadius:50,
position: 'absolute',
marginTop: 10,
marginLeft: width - 100
}}
>
<Icon
type="font-awesome"
name="barcode"
/>
</TouchableOpacity>
</View>
<View style ={{flex:1,marginTop:20}}>
<ScrollView>
<NumberList products={this.state.productos} />
</ScrollView>
</View>
<View style ={{flex:1,marginTop:20}}>
<View style={{flexDirection:"row", height: 50, width: width, backgroundColor: "green", justifyContent: "center",}}>
<View style = {{ flexDirection:"column"}}>
<Text style = {{ fontSize: 40,color:"white"}}>{"TOTAL: "}</Text>
</View>
<View style={{justifyContent: "center", flexDirection:"row-reverse", paddingRight:20}}>
<Text style = {{ fontSize: 40,color:"white"}}>{result.precioventa}</Text>
</View>
</View>
</View>
</View>
}
{scan &&
<BarCodeScanner
onBarCodeScanned={handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
}
</View>
);
}
}
function NumberList(props) {
console.log("NUMBERLIST")
console.log(props);
const products = props.products;
const listItems = products.map((product) =>
// Correct! Key should be specified inside the array.
<ListItem key={product.key} value={product} />
);
return (
<View>
{listItems}
</View>
);
}
function ListItem(props) {
// Correct! There is no need to specify the key here:
const u = props.value;
return (
<View>
{u &&
<Card>
<View style={{flexDirection:"row"}}>
<Icon
name = "monetization-on"
size = {40}
/>
<View style={{flex:1, flexDirection: "column", paddingTop: 10}}><Text>{u.descripcion}</Text></View>
<View style = {{flexDirection:"row-reverse", paddingTop: 10}}><Text>{u.precioventa}</Text></View>
</View>
</Card>
}
</View>);
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'black'
},
containerHome:{
backgroundColor: 'white',
height: height,
width: width,
flexDirection: 'column'
},
cardSales:{
backgroundColor: 'white',
flex: 1,
padding: 15,
borderWidth: 1,
borderRadius: 10,
borderColor: '#ddd',
borderBottomWidth: 7,
//shadowColor: '#000',
shadowColor: "#191919",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop: 20,
},
cardContent:{
flexDirection: 'row-reverse',
fontSize: 50
},
button:{
flexDirection: 'column',
marginTop: 20,
marginLeft: 20,
marginRight: 20,
},
contentActionFast:{
backgroundColor: 'white',
flexDirection: 'row',
alignItems:'center',
justifyContent: 'space-between',
flex:1
}
});
export default SaleScreen;
if anyone could help me I'd really appreciate it
Your component isn't re-rendering because in _searchProduct you're doing this.state.productos.push(responseJson[0]); to update the state object when you should be using setState(). Directly modifying the state, which you're doing now, won't trigger a re-render and could lead to other problems, which is why you should never do it and always use setState() (or a hook) to update state. This is mentioned in the docs here: https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly.
Instead try:
this.setState((prevState) => ({
productos: [...prevState.productos, responseJson[0]]
});

How to rerender the page on alert ok button

Here in my code I am trying to reload the page on Alert ok button . But its not working . How can I rerender the page on ok button , this is written on same page that I have to reload .
In my code I am sung form and inputfield compont for my login screen . All code is there below . I am tryning to is , when I am getting any respons like wrong username and password in alere then ok button I have to clear my form field . While here ists not happning . For this I am deleting my value mannully.
Please sugget .
import React from 'react';
import { Alert, Dimensions, ImageBackground, Text, View, TouchableOpacity, Platform , StatusBar} from 'react-native';
import Formbox from './ui/form';
import { RegularText, } from './ui/text';
import pkg from '../../package';
import _ from 'lodash';
import { LOGIN_BACKGROUND , LOGIN_BACKGROUND_DARK} from '../images'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import parentStyle from '../themes/parent.style'
import LottieView from 'lottie-react-native';
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
const styles = {
imgBG: { width: '100%', height: '100%' },
mainContainer: {
flex: 1,
alignItems: 'stretch',
justifyContent: 'flex-start',
height: deviceHeight,
paddingLeft: 20,
paddingRight: 20
},
logoContainer: { justifyContent: 'center', alignItems: 'center', background: 'red', marginTop: -50 },
logoView: {
borderWidth: 3,
borderColor: '#FFFFFF',
borderRadius: 4,
zIndex: -1,
...Platform.select({
ios: {
shadowOpacity: 0.45,
shadowRadius: 3,
shadowColor: '#090909',
shadowOffset: { height: 1, width: 0 }
},
android: {
elevation: 3
}
})
}
};
export default class Login extends React.Component {
constructor(props) {
super(props);
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.error) {
if (this.props.error.graphQLErrors[0] !== undefined) {
const errorDetails = _.map(_.split(this.props.error.graphQLErrors[0].message, '#'), _.trim)
const header = errorDetails[0];
const message = errorDetails[1];
Alert.alert(header, message, [{
text: 'OK',
onPress: () => this.props.navigation.push('Auth')
},]);
} else {
Alert.alert('Network Error', this.props.error.networkError.message, [{
text: 'OK',
onPress: () => this.props.navigation.navigate('Auth')
},]);
}
}
}
componentDidMount(){
StatusBar.setBarStyle('dark-content');
}
render() {
let loginForm = [
{ label: 'Username', icon: 'person', type: 'text' },
{ label: 'Password', icon: 'key', type: 'password' }
];
let submitBtn = { label: 'Login', OnSubmit: this.props.onLogin };
let appliedTheme = this.props.theme;
let appliedMode = this.props.mode;
return (
<ImageBackground source={appliedMode === 'light' ? LOGIN_BACKGROUND : LOGIN_BACKGROUND_DARK} style={styles.imgBG}>
<View style={styles.mainContainer}>
<View style={{ flexDirection: 'column', alignContent: 'center', justifyContent: 'center', flex: 1 }}>
<View style={{ flex: 0.75, justifyContent: 'center' }}>
<RegularText text={'Welcome,'} textColor='#57606F' style={{ fontSize: hp('5%') }} />
<RegularText text={'Sign in to continue'} textColor='#ABAFB7' style={{ fontSize: hp('3.5%') }} />
</View>
<View style={{ flex: 2 }}>
<View style={{ flex: 2 }}>
<Formbox
theme={parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].primaryButtonColor : undefined}
mode={this.props.mode}
formFields={loginForm}
submit={submitBtn}
that={this}
mutation={this.props.token}
/>
<View style={{ height: hp(20), zIndex:10, top: -25}}>
{this.props.loading && (
<LottieView source={require('./animations/login_authentication.json')} autoPlay loop />
)}
</View>
<View style={{top:-70, zIndex:10}}>
{false && <View style={{ alignItems: 'center' }}>
<RegularText text={`v${pkg.version}`} textColor='#ABAFB7' style={{ fontSize: hp('2%') }} />
</View>}
<View style={{ alignItems: 'flex-end' }}>
<View style={{ flexDirection: 'row' }}>
<RegularText text={`New User?`} textColor='#4A494A' style={{ fontSize: hp('2%') }} />
<TouchableOpacity>
<RegularText text={` REGISTER`} textColor={parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].primaryButtonColor : '#fff'} style={{ fontSize: hp('2%'), fontWeight: 'bold' }} />
</TouchableOpacity>
</View>
</View>
</View>
</View>
</View>
</View>
</View>
</ImageBackground>
);
}
}
////// Form ,js
import React, { Component } from 'react';
import { View, Platform, Dimensions } from 'react-native';
import { PrimaryBtn,PrimaryAbsoluteGradientBtn } from './buttons';
import { InputField, PasswordField } from './inputField';
import { Form } from 'native-base';
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
export default class Formbox extends Component {
constructor(props) {
super(props);
}
OnSubmit() {
let { formFields, that, submit, mutation } = this.props;
submit.OnSubmit.bind(that, formFields, mutation)();
}
OnChange(field, target) {
this.props.formFields.forEach(function (formField, indx) {
if (formField.label === field.label) {
formField.value = target;
}
});
}
renderFields(field, indx) {
let { label, icon, type } = field;
if (label && icon) {
if (type === 'password') {
return <PasswordField key={label + indx} type={type ? type : ''} label={label} icon={icon}
OnChange={this.OnChange} that={this} />;
}
return <InputField key={label + indx} type={type ? type : ''} label={label} icon={icon} OnChange={this.OnChange}
that={this} />;
}
}
render() {
let { formFields, submit, that , theme, mode} = this.props;
return (
<View style={{ width: '100%' }}>
<Form style={{ width: '95%' }}>
{formFields.map((field, indx) => this.renderFields(field, indx))}
<View style={{ marginTop: 60 }}>
<PrimaryAbsoluteGradientBtn label={submit.label} OnClick={this.OnSubmit} that={this} backgroundColor={theme}/></View>
</Form>
</View>
);
}
}
/// input fields js
import React, { Component } from 'react';
import { Icon, Input, Item, Label } from 'native-base';
import { View } from 'react-native';
import { DoNothing } from '../services/services';
class InputField extends Component {
constructor(props) {
super(props);
}
render() {
let { label, OnChange, icon, that,type, keyboardType } = this.props;
return (
<View>
<Item floatingLabel>
{icon && <Icon active name={icon}/>}
{label && <Label>{label}</Label>}
<Input
secureTextEntry={type === 'password'}
onChangeText={OnChange ? (e) => OnChange.bind(that, this.props, e)() : DoNothing.bind(this)}
keyboardType={keyboardType || 'default'}
autoCapitalize = 'none'
autoCorrect={false}
/>
</Item>
</View>
);
}
}
class PasswordField extends Component {
constructor(props) {
super(props);
this.state = {
isMasked: true
};
}
_toggleMask = () => {
this.setState({
isMasked: !this.state.isMasked
});
};
render() {
let { label, OnChange, icon, that, type } = this.props;
const { isMasked } = this.state;
return (
<View>
<Item floatingLabel>
{icon && <Icon active name={icon}/>}
<Label>{label}</Label>
<Input
autoCapitalize = 'none'
secureTextEntry={isMasked}
onChangeText={OnChange ? (e) => OnChange.bind(that, this.props, e)() : DoNothing.bind(this)}
/>
<Icon name={isMasked ? "md-eye-off" : "md-eye"} active type="Ionicons" onPress={() => this._toggleMask()}/>
</Item>
</View>
);
}
}
const styles = {
dark: {
color: "#000000"
},
light: {
color: "#EAEAEA"
}
}
export { InputField, PasswordField };
You can either do :
onPress: () => this.props.navigation.push('Auth')
or do something like :
onPress: () => this.setState({name:'random'})
These both will trigger re rendering, Hope it helps. feel free for doubts

Not able to navigate to other page in react native

I am not able to navigate to other page in react native.
Here is my App.js:
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View,Dimensions,TextInput,TouchableOpacity,Button } from 'react-native';
import Camera from 'react-native-camera';
import ContactDetails from './Components/ContactDetails';
import Finalpage from './Components/Finalpage'
import { StackNavigator } from 'react-navigation';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
class HomeScreen extends Component {
_onPressButton = ()=> {
this.props.navigation.navigate('SignUp1');
}
render() {
return (
<View style={{ flex: 1 }}>
<TouchableOpacity
style={{
backgroundColor: '#f2f2f2',
paddingVertical: 10,
borderRadius: 20,
justifyContent: 'center',
alignItems: 'center',
marginTop: 35,
}}>
<Text style={{ color: '#010101' }}>Please Capture Image</Text>
</TouchableOpacity>
<Button
onPress={this._onPressButton}
title="Press Me"
/>
</View>
);
}
}
export default class App extends Component
<Props>
{
constructor(props) {
super(props);
this.state = {
path: null,
};
}
takePicture() {
this.method();
const { navigate } = this.props.navigation;
alert("HI");
this.camera.capture()
.then((data) => {
console.log(data);
alert("HI");
this.props.navigator.push({
component: ContactDetails,
});
})
.catch(err => console.error(err));
}
renderCamera() {
const { navigate } = this.props.navigation;
return (
<Camera
ref={(cam) =>
{
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}
captureQuality={Camera.constants.CaptureQuality.medium}
captureTarget={Camera.constants.CaptureTarget.disk}
orientation={Camera.constants.Orientation.auto}
aspect={Camera.constants.Aspect.fill}
>
<TouchableHighlight
style={styles.capture}
onPress={this.takePicture()
}
underlayColor="rgba(255, 255, 255, 0.5)"
>
<View />
</TouchableHighlight>
</Camera>
);
}
renderImage() {
return (
<View>
<Image
source={{ uri: this.state.path }}
style={styles.preview}
/>
<Text
style={styles.cancel}
onPress={() => this.method()}
>Cancel
</Text>
</View>
);
}
method(){
alert("HI");
this.props.navigation.navigate('SignUp1');
}
render() {
return (
<RootStack />
)
}
}
const RootStack = StackNavigator({
Home: {
screen: HomeScreen,
},
SignUp1: {
screen: ContactDetails,
},
finalpage:{
screen:Finalpage,
}
});
Here is the style for App.js file
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width
},
capture: {
width: 70,
height: 70,
borderRadius: 35,
borderWidth: 5,
borderColor: '#FFF',
marginBottom: 15,
},
cancel: {
position: 'absolute',
right: 20,
top: 20,
backgroundColor: 'transparent',
color: '#FFF',
fontWeight: '600',
fontSize: 17,
}
});
List item: in contactDetails.js
import React, { Component } from 'react';
import {
View,
StyleSheet,
Dimensions,
TouchableHighlight,
Image,
Text,
} from 'react-native';
import Camera from 'react-native-camera';
import { StackNavigator } from 'react-navigation';
import {Finalpage} from'../Components/Finalpage';
const RootStack = StackNavigator({
SignUpMEW: {
screen: Finalpage,
},
});
class CameraRoute extends Component {
constructor(props) {
super(props);
this.state = {
path: null,
};
}
takePicture() {
this.camera.capture()
.then((data) => {
console.log(data);
this._onPressButton();
})
.catch(err => console.error(err));
}
renderCamera() {
return (
<Camera
ref={(cam) =>
{
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}
captureTarget={Camera.constants.CaptureTarget.disk}
>
<TouchableHighlight
style={styles.capture}
onPressIn={() =>
this.takePicture()}
onPressOut={() => this._onPressButtonNEW()}
underlayColor="rgba(255, 255, 255, 0.5)"
>
<View />
</TouchableHighlight>
</Camera>
);
}
_onPressButton = ()=> {
this.props.navigation.push('SignUpMEW');
}
_onPressButtonNEW = ()=> {
alert("Thanks For Storing the data");
this.props.navigation.push('SignUpMEW');
alert(this.props.navigation);
}
renderImage() {
return (
<View>
<Image
source={{ uri: this.state.path }}
style={styles.preview}
/>
<Text
style={styles.cancel}
onPress={() => this.props.navigation.navigate('SignUpMEW')}
>Cancel
</Text>
</View>
);
}
render() {
return (
<View style={styles.container}>
{this.state.path ? this.renderImage() : this.renderCamera()}
</View>
);
}
}
Here is the style for contactDetails.js
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width
},
capture: {
width: 70,
height: 70,
borderRadius: 35,
borderWidth: 5,
borderColor: '#FFF',
marginBottom: 15,
},
cancel: {
position: 'absolute',
right: 20,
top: 20,
backgroundColor: 'transparent',
color: '#FFF',
fontWeight: '600',
fontSize: 17,
}
});
export default CameraRoute;
Page 2 - In final page
import React, {Component
} from 'react';
import {
Text,
View,StyleSheet
} from 'react-native';
export class Finalpage extends React.Component{
render() {
return (
<View style={styles.container}>
<Text>Thanks For Update</Text>
</View>
);
}
}
Here is the style for the final page
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
}
});
I cannot navigate to final page please help me out i am new to React so please help me out
First: your code is unreadable and not structured. It is horrible to read.
Second: As far as I can see, your usage of StackNavigator is wrong. Should be like this (you are missing create):
const RootStack = createStackNavigator({
Home: {
screen: HomeScreen,
},
SignUp1: {
screen: ContactDetails,
},
finalpage:{
screen:Finalpage,
}
});
Docs StackNavigator

React Native randomly errors: Can't find variable image after 30 - 90 seconds

So I'm building a React Native app using
React Native - Latest
MobX and MobX-React - Latest
Firebase - Latest
My app works fine. However, I can leave the app idle or play around with it and after 30-90 seconds I red screen with this error. Its not being very specific about what file is erroring! How can I debug this?
Firebase.js
export function getFeed(db,id,callback){
db.collection("posts").where("userId", "==", id)
.get()
.then(function (querySnapshot) {
callback(true,querySnapshot)
})
.catch(function (error) {
callback(false)
console.log("Error getting documents: ", error);
});
}
List.js
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TouchableOpacity,
FlatList,
ActivityIndicator,
RefreshControl
} from 'react-native';
import Post from './Post';
import Spinner from 'react-native-spinkit';
import { Icon } from 'react-native-elements';
import { getFeed } from '../../network/Firebase';
import { observer, inject } from 'mobx-react';
#inject('mainStore')
#observer export default class List extends Component {
constructor(props) {
super(props)
this.state = {
dataSource: [],
initialLoad: true,
refreshing: false
}
this.getData = this.getData.bind(this)
}
componentWillMount() {
this.getData()
}
getData() {
this.setState({
refreshing: true
})
getFeed(this.props.screenProps.db, this.props.mainStore.userData.id, (status, res) => {
let tempArray = []
let counter = 0
res.forEach((doc) => {
let tempObj = doc.data()
doc.data().user
.get()
.then((querySnapshot) => {
tempObj.userData = querySnapshot.data()
tempArray.push(tempObj)
counter = counter + 1
if (counter === res.docs.length - 1) {
this.setState({
dataSource: tempArray,
initialLoad: false,
refreshing: false
})
}
})
});
})
}
renderRow = ({ item }) => {
return (
<Post item={item} />
)
}
render() {
if (this.state.initialLoad) {
return (
<View style={styles.spinner}>
<Spinner isVisible={true} type="9CubeGrid" size={40} color="white" />
</View>
)
} else {
return (
<FlatList
data={this.state.dataSource}
extraData={this.state}
keyExtractor={(_, i) => i}
renderItem={(item) => this.renderRow(item)}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this.getData}
/>
}
/>
);
}
}
}
const styles = StyleSheet.create({
spinner: {
marginTop: 30,
alignItems: 'center'
}
});
Post.js
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TouchableOpacity,
Image
} from 'react-native';
import moment from 'moment';
import { Icon } from 'react-native-elements';
export default class Post extends React.PureComponent {
render() {
let today = moment()
let date = this.props.item.date
if(today.diff(date, 'days') < 5){
date = moment(date).startOf('day').fromNow()
}else{
date = moment(date).format('DD MMM YYYY, h:mm a')
}
return (
<View
style={styles.container}
>
<View style={styles.top}>
<Image style={styles.profile} source={{uri: this.props.item.userData.image}} />
<Text style={styles.title}>{this.props.item.userData.firstName+' '+this.props.item.userData.lastName}</Text>
</View>
<View style={styles.descriptionContainer}>
<Text style={styles.description}>{this.props.item.description}</Text>
</View>
<View style={styles.imageContainer}>
<Image style={styles.image} source={{uri: this.props.item.image}} />
</View>
<TouchableOpacity style={styles.commentsContainer}>
<View style={styles.timeFlex}>
<Text style={styles.title}>{date}</Text>
</View>
<View style={styles.commentFlex}>
<Text style={styles.title}>Comments (12)</Text>
</View>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
title: {
color: 'white',
backgroundColor: 'transparent'
},
timeFlex: {
flex: 0.5,
alignItems: 'flex-start'
},
commentFlex: {
flex: 0.5,
alignItems: 'flex-end'
},
profile: {
width: 40,
height: 40,
borderRadius: 20,
marginRight: 10
},
descriptionContainer: {
marginBottom: 10,
marginHorizontal: 15,
},
description: {
color: 'rgba(255,255,255,0.5)'
},
commentsContainer: {
marginBottom: 10,
alignItems: 'flex-end',
marginHorizontal: 15,
flexDirection: 'row'
},
imageContainer: {
marginBottom: 10,
marginHorizontal: 15,
height: 180
},
image: {
height: '100%',
width: '100%'
},
top: {
justifyContent: 'flex-start',
margin: 10,
marginLeft: 15,
flexDirection: 'row',
alignItems: 'center'
},
container: {
margin: 10,
backgroundColor: '#243c5e',
borderRadius: 10,
shadowColor: 'black',
shadowOffset: {
width: 2,
height: 1
},
shadowRadius: 4,
shadowOpacity: 0.3
}
});

Categories

Resources