How to implement swiping to access different navigation screens in React Native? - react-native

I am trying to build an interface similar to the Snapchat's interface where you can swipe left/right/up to access different screen/navigator. Currently I am using the DrawerNavigator but it's kind of janky because I am using a DrawerNavigator on top of another DrawerNavigator.
Does anyone have a good suggestion on the best way to do this?
Thanks!

The following code is implementing easy 4-way swipe navigation across views declaratively in under 20 lines, no Javascript!
import Swiper from 'react-native-swiper'
import randomcolor from 'randomcolor'
const {
View,
Text,
StyleSheet
} = React
var styles = StyleSheet.create({
container: {
flex: 1
},
view: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
})
class TitleText extends React.Component {
render() {
return (
<Text style={{ fontSize: 48, color: 'white' }}>
{this.props.label}
</Text>
)
}
}
class Home extends React.Component {
viewStyle() {
return {
flex: 1,
backgroundColor: randomcolor(),
justifyContent: 'center',
alignItems: 'center',
}
}
render() {
return (
<Swiper
loop={false}
showsPagination={false}
index={1}>
<View style={this.viewStyle()}>
<TitleText label="Left" />
</View>
<Swiper
horizontal={false}
loop={false}
showsPagination={false}
index={1}>
<View style={this.viewStyle()}>
<TitleText label="Top" />
</View>
<View style={this.viewStyle()}>
<TitleText label="Home" />
</View>
<View style={this.viewStyle()}>
<TitleText label="Bottom" />
</View>
</Swiper>
<View style={this.viewStyle()}>
<TitleText label="Right" />
</View>
</Swiper>
)
}
}
export default Home
Unfortunately, vertical navigation is not supported on Android yet.
I’ve used the react-native-swiper component in a previous project and loved it! I figured I can tweak it a little bit to meet my requirements.
You can clearly see that I have seperated my screens and navigation files in a separate folder.
This is my root navigator file:
import {
createStackNavigator
} from 'react-navigation';
import Login from '../screens/Login';
import SplashScreen from '../screens/SplashScreen';
import HomeNavigation from './HomeNavigation';
export default RootNavigation = createStackNavigator({
// Settings:UserProfile,
SplashScreen: SplashScreen,
Login: Login,
DrawerNavigation: HomeNavigation
}, {
headerMode: 'none',
});
This is my root navigator file:
Here i declare all my screens and link it to the root navigator
import React, {
Component
} from 'react';
import {
Text,
View,
Image,
SafeAreaView,
ScrollView,
Dimensions,
AsyncStorage,
ImageBackground,
TouchableOpacity,
Platform
} from 'react-native';
import {
Icon
} from 'native-base';
import {
createStackNavigator,
createDrawerNavigator,
DrawerItems,
createSwitchNavigator,
Header
} from 'react-navigation';
import AppDataStorage from '../helper/AppDataStorage';
import Colors from '../config/Colors';
import {
RNToasty
} from 'react-native-toasty';
import Home from '../screens/Home';
import Contact from '../screens/Contact';
import AboutUs from '../screens/AboutUs';
import Search from '../screens/Search';
import MyProfile from '../screens/MyProfile';
import {
getStatusBarHeight
} from 'react-native-status-bar-height';
var width = Dimensions.get('window').width;
var height = Dimensions.get('window').height;
var drawerWidth = ((width * 0.75) > 350) ? 350 : (width * 0.75);
const ImageHeader = props => ( <
View style = {
{
backgroundColor: '#eee'
}
} >
<
LinearGradien style = {
{
height: '100%',
width: '100%'
}
}
start = {
{
x: 0,
y: 1
}
}
end = {
{
x: 1,
y: 0
}
}
colors = {
['#4c669f', '#3b5998', '#192f6a']
}
/> <
Header { ...props
}
style = {
{
backgroundColor: 'transparent'
}
}
/> < /
View >
);
const headerOptions = (props) => {
return {
// header: (props) => <ImageHeader {...props} />,
headerStyle: {
backgroundColor: Colors.transparent,
paddingTop: Platform.OS === 'ios' ? 0 : getStatusBarHeight(),
height: Header.HEIGHT + (Platform.OS === 'ios' ? 0 : getStatusBarHeight()),
},
headerTintColor: Colors.white,
headerTitleStyle: {
fontWeight: 'bold',
},
headerMode: 'float',
headerLeft: < Icon
onPress = {
() => props.navigation.openDrawer()
}
name = "menu"
type = 'MaterialIcons'
style = {
{
color: 'white',
marginLeft: 10
}
}
/>,
}
};
class homeDrawerComponent extends Component {
constructor(props) {
super(props);
this.state = {
user: null
};
}
async componentDidMount() {
let user = await AppDataStorage.getUser();
console.log("user drawer", user);
await this.setState({
user: user
});
}
render() {
const email = this.state.user ? this.state.user.email : '';
const name = this.state.user ? (this.state.user.firstName + ' ' + this.state.user.lastName) : '';
return ( <
View style = {
{
flex: 1
}
} >
<
ImageBackground resizeMode = 'cover'
source = {
require('../assets/images/Cover.png')
}
style = {
{
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
height: 200,
marginBottom: 32
}
} >
<
View style = {
{
width: 80,
height: 80,
backgroundColor: Colors.white,
marginTop: 40,
borderRadius: 40
}
} >
<
Image source = {
require('../assets/images/drawer-logo.png')
}
style = {
{
width: 80,
height: 80,
}
}
resizeMode = 'contain' / >
<
/View> <
Text style = {
{
marginTop: 10,
color: Colors.white,
fontSize: 14,
}
} > {
name
} <
/Text> <
Text style = {
{
color: Colors.white,
fontSize: 14,
}
} > {
email
} <
/Text> < /
ImageBackground > <
ScrollView showsVerticalScrollIndicator = {
false
} >
<
DrawerItems activeBackgroundColor = '#1a9eae1a'
activeTintColor = {
Colors.secondaryColor
}
inactiveTintColor = {
Colors.primaryColor
}
labelStyle = {
{
color: Colors.text2
}
} { ...this.props
}
/> <
TouchableOpacity onPress = {
() => {
AsyncStorage.clear();
OneSignal.setSubscription(false);
RNToasty.Info({
title: 'You have been logged out.'
})
this.props.navigation.navigate('SplashScreen');
}
} >
<
View style = {
{
padding: 16,
flexDirection: 'row',
alignItems: 'center'
}
} >
<
Icon
type = "MaterialCommunityIcons"
name = "logout"
style = {
{
fontSize: 24,
color: Colors.primaryColor,
fontWeight: 'bold'
}
}
/> <
Text style = {
{
fontSize: 14,
color: Colors.text2,
fontWeight: 'bold',
marginLeft: 32
}
} > Sign Out < /Text> < /
View > <
/TouchableOpacity> < /
ScrollView > {
/* <TouchableOpacity onPress={() => {
AsyncStorage.clear();
RNToasty.Info({ title: 'You have been logged out.' })
this.props.navigation.navigate('SplashScreen');
}}> */
} {
/* <Icon
onPress={() => {
AsyncStorage.clear();
OneSignal.setSubscription(false);
RNToasty.Info({ title: 'You have been logged out.' })
this.props.navigation.navigate('SplashScreen');
}}
type="MaterialCommunityIcons"
name="logout"
style={{ color: Colors.secondaryColor, padding: 16, textAlign: 'left', marginBottom: 20, fontWeight: 'bold' }}> Logout</Icon> */
} <
/View>
)
}
}
const HomeStack = createStackNavigator({
Home: Home,
Search: Search,
Contact: Contact,
}, {
defaultNavigationOptions: headerOptions
});
HomeStack.navigationOptions = ({
navigation
}) => {
let drawerLockMode = 'unlocked';
if (navigation.state.index > 2) {
drawerLockMode = 'locked-closed';
}
return {
drawerLockMode,
};
};
const AboutUsStack = createStackNavigator({
AboutUs: AboutUs,
}, {
defaultNavigationOptions: headerOptions
});
export default HomeNavigation = createDrawerNavigator({
Home: {
screen: HomeStack,
navigationOptions: {
drawerLabel: 'Home',
drawerIcon: ({
tintColor
}) => ( <
Icon type = "FontAwesome5"
name = "home"
style = {
{
fontSize: 20,
color: tintColor
}
}
/>
)
}
},
{
header: null,
contentComponent: homeDrawerComponent,
// drawerWidth
},
);
You're good to go!
Hope this helps.

Related

How can I get the value from custom radio button component in parent class

I have a custom radio button component. I am importing that to my parent form to create a dynamic fields of radio button from JSON file. I have multiple other views too. I am getting these views values and creating a JSON array in my parent form. I am stuck in how to get my custom radio buttons values and pass them to my method where i am creating JSON array of values.Here is my custom component radio button code
import React, { Component } from "react";
import { View, TouchableOpacity, Text, StyleSheet } from "react-native";
export default class RadioButton extends Component {
state = {
value: null,
};
render() {
const { PROP } = this.props;
const { value } = this.state;
return (
<View>
{PROP.map((res) => {
return (
<View key={res.key} style={styles.container}>
<Text style={styles.radioText}>{res.text}</Text>
<TouchableOpacity
style={styles.radioCircle}
onPress={() => {
this.setState({
value: res.text,
});
}}
>
{value === res.text && <View style={styles.selectedRb} />}
</TouchableOpacity>
</View>
);
})}
<Text> Selected: {this.state.value} </Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginBottom: 15,
alignItems: "center",
flexDirection: "row",
justifyContent: "space-between",
},
radioText: {
marginRight: 35,
color: "#000",
},
radioCircle: {
height: 20,
width: 20,
marginRight: 10,
borderRadius: 100,
borderWidth: 2,
borderColor: "#3740ff",
alignItems: "center",
justifyContent: "center",
},
selectedRb: {
width: 15,
height: 15,
borderRadius: 15,
backgroundColor: "#3740ff",
},
result: {
marginTop: 20,
color: "white",
fontWeight: "600",
backgroundColor: "#F3FBFE",
},
});
This is my main class.
import React, { Component } from "react";
import CheckBox from "#react-native-community/checkbox";
import { View, TextInput, Button, StyleSheet, Text } from "react-native";
const data = require("../json/registration.json");
import MyRadioButton from "../component/MyRadioButton";
class Registration extends Component {
constructor(props) {
super(props);
this.state = {
itemstorender: [],
inputData: [],
checked: "",
};
}
addValues = (value, index) => {
let dataArray = this.state.inputData;
let checkBool = false;
if (dataArray.length !== 0) {
dataArray.forEach((element) => {
if (element.index === index) {
element.value = value;
checkBool = true;
}
});
}
if (checkBool) {
this.setState({
inputData: dataArray,
});
} else {
dataArray.push({ value: value, index: index });
this.setState({
inputData: dataArray,
});
// console.log('Data',dataArray);
}
};
getValues = () => {
console.log("Data", this.state.inputData);
};
componentDidMount() {
this.renderData();
}
hideComponent(data) {
// console.log("checkd",data)
this.setState({
checked: data,
});
console.log(this.state.checked);
}
renderData = () => {
const result = data.info;
var itemstorenderLocal = [];
for (var i = 0; i < result.length; i++) {
if (result[i].element == "TextInput") {
let i_id = result[i].id;
console.log("Ids : ", i_id);
itemstorenderLocal.push(
<TextInput
key={result[i].id}
placeholder={result[i].label}
onChangeText={(value) => this.addValues(value, i_id)}
/>
);
this.setState({ itemstorenderLocal });
}else if (result[i].element == "RadioButtons") {
let i_id = result[i].id;
// let options = console.log("Ids : ", i_id);
itemstorenderLocal.push(
<Text>{result[i].label}</Text>,
<View style={styles.container}>
<MyRadioButton
PROP={result[i].options}
/>
</View>
);
this.setState({ itemstorenderLocal });
} else if (result[i].element == "button") {
itemstorenderLocal.push(
<Button
key={result[i].id}
title={result[i].label}
onPress={() => this.getValues()}
/>
);
}
}
this.setState({
itemstorender: itemstorenderLocal,
});
};
render() {
return <View>{this.state.itemstorender}</View>;
}
}
export default Registration;

TypeError: navigation.state.params. React Native

Here I have used Redux to manage state but i am getting this type of Error: TypeError: navigation.state.params.AddBlack is not a function. (In 'navigation.state.params.AddBlack({
noteTitle: noteTitle,
noteValue: noteValue
})', 'navigation.state.params.AddBlack' is undefined)
ViewBlacks.js
import React from 'react'
import { Button, StyleSheet, View, FlatList } from 'react-native'
import { Text, FAB, List } from 'react-native-paper'
import { useSelector, useDispatch } from 'react-redux'
import { addblack, deleteblack } from '../redux/notesApp'
import Header from '../components/Header'
function ViewBlacks({ navigation }) {
const blacks = useSelector(state => state.number)
const dispatch = useDispatch()
const addBlack = black => dispatch(addblack(black))
const deleteBlack = id => dispatch(deleteblack(id))
return (
<>
<Header titleText='Simple Note Taker' />
<Button title="Go back" onPress={() => navigation.goBack()} />
<View style={styles.container}>
{blacks.length === 0 ? (
<View style={styles.titleContainer}>
<Text style={styles.title}>You do not have any notes</Text>
</View>
) : (
<FlatList
data={blacks}
renderItem={({ item }) => (
<List.Item
title={item.black.noteTitle}
description={item.black.noteValue}
descriptionNumberOfLines={1}
titleStyle={styles.listTitle}
onPress={() => deleteBlack(item.id)}
/>
)}
keyExtractor={item => item.id.toString()}
/>
)}
<FAB
style={styles.fab}
small
icon='plus'
label='Add new note'
onPress={() =>
navigation.navigate('AddBlacks', {
addBlack
})
}
/>
</View>
</>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingHorizontal: 10,
paddingVertical: 20
},
titleContainer: {
alignItems: 'center',
justifyContent: 'center',
flex: 1
},
title: {
fontSize: 20
},
fab: {
position: 'absolute',
margin: 20,
right: 0,
bottom: 10
},
listTitle: {
fontSize: 20
}
})
export default ViewBlacks
AddBlack.js
import React, { useState } from 'react'
import { View, StyleSheet } from 'react-native'
import { IconButton, TextInput, FAB } from 'react-native-paper'
import Header from '../components/Header'
function AddBlack({ navigation }) {
const [noteTitle, setNoteTitle] = useState('')
const [noteValue, setNoteValue] = useState('')
function onSaveNote() {
navigation.state.params.addBlack({ noteTitle, noteValue })
navigation.goBack()
}
return (
<>
<Header titleText='Add a new note' />
<IconButton
icon='close'
size={25}
color='white'
onPress={() => navigation.goBack()}
style={styles.iconButton}
/>
<View style={styles.container}>
<TextInput
label='Add Title Here'
value={noteTitle}
mode='outlined'
onChangeText={setNoteTitle}
style={styles.title}
/>
<TextInput
label='Add Note Here'
value={noteValue}
onChangeText={setNoteValue}
mode='flat'
multiline={true}
style={styles.text}
scrollEnabled={true}
returnKeyType='done'
blurOnSubmit={true}
/>
<FAB
style={styles.fab}
small
icon='check'
disabled={noteTitle == '' ? true : false}
onPress={() => onSaveNote()}
/>
</View>
</>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingHorizontal: 20,
paddingVertical: 20
},
iconButton: {
backgroundColor: 'rgba(46, 113, 102, 0.8)',
position: 'absolute',
right: 0,
top: 40,
margin: 10
},
title: {
fontSize: 24,
marginBottom: 20
},
text: {
height: 300,
fontSize: 16
},
fab: {
position: 'absolute',
margin: 20,
right: 0,
bottom: 0
}
})
export default AddBlack
notesReducer.js
import remove from 'lodash.remove'
// Action Types
export const ADD_NOTE = 'ADD_NOTE'
export const DELETE_NOTE = 'DELETE_NOTE'
export const ADD_BLACK = 'ADD_BLACK'
export const DELETE_BLACK = 'DELETE_BLACK'
// Action Creators
let noteID = 0
let blackID = 0
export function addnote(note) {
return {
type: ADD_NOTE,
id: noteID++,
note
}
}
export function deletenote(id) {
return {
type: DELETE_NOTE,
payload: id
}
}
export function addblack(black) {
return {
type: ADD_BLACK,
id: blackID++,
black
}
}
export function deleteblack(id) {
return {
type: DELETE_BLACK,
payload: id
}
}
// reducer
const INITIAL_STATE = {
note: [], // for holds notes
number: [] // for holds numbers
};
function notesReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case ADD_NOTE:
return {
...state,
note: [
...state.note,
{
id: action.id,
note: action.note
}
]
};
case DELETE_NOTE:
const note = remove(state.note, obj => obj.id != action.payload);
return {...state, note};
case ADD_BLACK:
return {
...state,
number: [
...state.number,
{
id: action.id,
number: action.number
}
]
};
case DELETE_BLACK:
const number = remove(state.number, obj => obj.id != action.payload);
return {...state, number}
default:
return state
}
}
export default notesReducer

How to make a QR code scanner in React native using expo?

When I run https://snack.expo.io/#sushil62/qr-code-scanner in the expo which works fine, but when copy the same code given in App.js file, after running the application the camera opens but it shows no result while scanning, and
in expo also when changing the snack version 33 or higher it does not work there too.
import React, { Component } from 'react';
import { Alert, Linking, Dimensions, LayoutAnimation, Text, View, StatusBar, StyleSheet, TouchableOpacity } from 'react-native';
import { BarCodeScanner, Permissions } from 'expo';
export default class App extends Component {
state = {
hasCameraPermission: null,
lastScannedUrl: null,
};
componentDidMount() {
this._requestCameraPermission();
}
_requestCameraPermission = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted',
});
};
_handleBarCodeRead = result => {
if (result.data !== this.state.lastScannedUrl) {
LayoutAnimation.spring();
this.setState({ lastScannedUrl: result.data });
}
};
render() {
return (
<View style={styles.container}>
{this.state.hasCameraPermission === null
? <Text>Requesting for camera permission</Text>
: this.state.hasCameraPermission === false
? <Text style={{ color: '#fff' }}>
Camera permission is not granted
</Text>
: <BarCodeScanner
onBarCodeRead={this._handleBarCodeRead}
style={{
height: Dimensions.get('window').height,
width: Dimensions.get('window').width,
}}
/>}
{this._maybeRenderUrl()}
<StatusBar hidden />
</View>
);
}
_handlePressUrl = () => {
Alert.alert(
'Open this URL?',
this.state.lastScannedUrl,
[
{
text: 'Yes',
onPress: () => Linking.openURL(this.state.lastScannedUrl),
},
{ text: 'No', onPress: () => {} },
],
{ cancellable: false }
);
};
_handlePressCancel = () => {
this.setState({ lastScannedUrl: null });
};
_maybeRenderUrl = () => {
if (!this.state.lastScannedUrl) {
return;
}
return (
<View style={styles.bottomBar}>
<TouchableOpacity style={styles.url} onPress={this._handlePressUrl}>
<Text numberOfLines={1} style={styles.urlText}>
{this.state.lastScannedUrl}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.cancelButton}
onPress={this._handlePressCancel}>
<Text style={styles.cancelButtonText}>
Cancel
</Text>
</TouchableOpacity>
</View>
);
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
},
bottomBar: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
backgroundColor: 'rgba(0,0,0,0.5)',
padding: 15,
flexDirection: 'row',
},
url: {
flex: 1,
},
urlText: {
color: '#fff',
fontSize: 20,
},
cancelButton: {
marginLeft: 10,
alignItems: 'center',
justifyContent: 'center',
},
cancelButtonText: {
color: 'rgba(255,255,255,0.8)',
fontSize: 18,
},
});
It would be very nice if someone suggests me to solve this or give me an example(such as downgrading the expo version) so that I can implement this.
You can use
expo-barcode-scanner
Run expo install expo-barcode-scanner
Usage
You must request permission to access the user's camera before attempting to get it. To do this, you will want to use the Permissions API. You can see this in practice in the following example.
import * as React from 'react';
import {
Text,
View,
StyleSheet,
Button
} from 'react-native';
import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';
import {
BarCodeScanner
} from 'expo-barcode-scanner';
export default class BarcodeScannerExample extends React.Component {
state = {
hasCameraPermission: null,
scanned: false,
};
async componentDidMount() {
this.getPermissionsAsync();
}
getPermissionsAsync = async() => {
const {
status
} = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted'
});
};
render() {
const {
hasCameraPermission,
scanned
} = this.state;
if (hasCameraPermission === null) {
return <Text > Requesting
for camera permission < /Text>;
}
if (hasCameraPermission === false) {
return <Text > No access to camera < /Text>;
}
return ( <
View style = {
{
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-end',
}
} >
<
BarCodeScanner onBarCodeScanned = {
scanned ? undefined : this.handleBarCodeScanned
}
style = {
StyleSheet.absoluteFillObject
}
/>
{
scanned && ( <
Button title = {
'Tap to Scan Again'
}
onPress = {
() => this.setState({
scanned: false
})
}
/>
)
} <
/View>
);
}
handleBarCodeScanned = ({
type,
data
}) => {
this.setState({
scanned: true
});
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
};
}
Note: Passing undefined to the onBarCodeScanned prop will result in no scanning. This can be used to effectively "pause" the scanner so that it doesn't continually scan even after data has been retrieved.
Allow all the permisions which gets popped.
You're good to go!!
Hope this helps.

Cant find the variable React-native

native . I made the status component and router.js file .The emulator giving me error Cant find varible i do not know what is the problem but im getting this error in emulator .
here is my code
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import StatusComponent from './component/StatusComponent';
import HeaderComponent from './component/headerComponent';
import Router from './component/Router';
import MainPage from './component/MainPage';
export default class Point extends Component {
render() {
return (
<View style={{flex: 1,backgroundColor: 'white'}}>
<StatusComponent/>
<HeaderComponent/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
} );
AppRegistry.registerComponent('Point', () => Point);
and here is my status component
import React,{ Component } from 'react';
import {
Text,
View,
StyleSheet
} from 'react-native';
export class StatusComponent extends Component{
render()
{
return(
<View style={styles.Bar}>
</View>
)
};
}
export default StatusComponent;
const styles=StyleSheet.create({
Bar:{
backgroundColor: 'white',
height: 20
}
})
here is code for Router.Js this file cousing the issue
import React, { Component } from 'react'
import {
StyleSheet,
Text,
Navigator,
TouchableOpacity
} from 'react-native'
import MainPage from './MainPage'
import Sports from './Sports'
export default class Router extends Component {
constructor(){
super()
}
render() {
return (
<Navigator
initialRoute = {{ name: 'MainPage', title: 'MainPage' }}
renderScene = { this.renderScene }
navigationBar = {
<Navigator.NavigationBar
style = { styles.navigationBar }
routeMapper = { NavigationBarRouteMapper } />
}
/>
);
}
renderScene(route, navigator) {
if(route.name == 'MainPage') {
return (
<MainPage
navigator = {navigator}
{...route.passProps}
/>
)
}
if(route.name == 'Sports') {
return (
<Sports
navigator = {navigator}
{...route.passProps}
/>
)
}
}
}
var NavigationBarRouteMapper = {
LeftButton(route, navigator, index, navState) {
if(index > 0) {
return (
<TouchableOpacity
onPress = {() => { if (index > 0) { navigator.pop() } }}>
<Text style={ styles.leftButton }>
Back
</Text>
</TouchableOpacity>
)
}
else { return null }
},
RightButton(route, navigator, index, navState) {
if (route.openMenu) return (
<TouchableOpacity
onPress = { () => route.openMenu() }>
<Text style = { styles.rightButton }>
{ route.rightText || 'Menu' }
</Text>
</TouchableOpacity>
)
},
Title(route, navigator, index, navState) {
return (
<Text style = { styles.title }>
{route.title}
</Text>
)
}
};
const styles = StyleSheet.create({
navigationBar: {
backgroundColor: 'blue',
},
leftButton: {
color: '#ffffff',
margin: 10,
fontSize: 17,
},
title: {
paddingVertical: 10,
color: '#ffffff',
justifyContent: 'center',
fontSize: 18
},
rightButton: {
color: 'white',
margin: 10,
fontSize: 16
}
})
In the StatusComponent file, you have export in front of the class StatusComponent extends Component. You should remove that export and leave the export default StatusComponent; at the bottom.
If after that, it still doesn't work then check the absolute path you are using to import the StatusComponent. Make sure it's correct
there is mistake in statusComponent file and thats very stupid mistake

How to refactoring react components with member variable to es6 classes

How can I refactor React components with a member variable to es6 classes
It works without state variable. Why, when running the code below, do I get a big red screen with "Can't add property counter, object is not extensible"?
'use strict';
let Dimensions = require('Dimensions');
let totalWidth = Dimensions.get('window').width;
let leftStartPoint = totalWidth * 0.1;
let componentWidth = totalWidth * 0.8;
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
TextInput,
View
} from 'react-native';
class Login extends Component {
constructor(props) {
super(props);
this.counter =23;
this.state = {
inputedNum: ''
};
}
updateNum(aEvent) {
this.setState((state) => {
return {
inputedNum: aEvent.nativeEvent.text,
};
});
}
buttonPressed() {
this.counter++;
console.log(':::'+this.counter);
}
render() {
return (
<View style={styles.container}>
<TextInput style={styles.numberInputStyle}
placeholder={'input phone number'}
onChange={(event) => this.updateNum(event)}/>
<Text style={styles.bigTextPrompt}
onPress={this.buttonPressed}>
Press me...
</Text>
</View>
);
}
}
let styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
numberInputStyle: {
top: 20,
left: leftStartPoint,
width: componentWidth,
backgroundColor: 'gray',
fontSize: 20
},
bigTextPrompt: {
top: 70,
left: leftStartPoint,
width: componentWidth,
backgroundColor: 'gray',
color: 'white',
textAlign: 'center',
fontSize: 60
}
});
AppRegistry.registerComponent('Project18', () => Login);
You need to set up the value in the constructor:
constructor(props) {
super(props)
this.counter = 23
}
You may be receiving the errors because of the way the state is being set. Try setting the state like this:
updateNum(aEvent) {
this.setState({
inputedNum: aEvent.nativeEvent.text,
})
}
And the onPress function should be called like this:
<Text style={styles.bigTextPrompt} onPress={() => this.buttonPressed()}>
I've set up a full working project here also pasted the code below.
https://rnplay.org/apps/Se8X5A
'use strict';
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
TextInput,
View,
Dimensions
} from 'react-native';
let totalWidth = Dimensions.get('window').width;
let leftStartPoint = totalWidth * 0.1;
let componentWidth = totalWidth * 0.8;
class SampleApp extends Component {
constructor(props) {
super(props);
this.counter =23;
this.state = {
inputedNum: ''
};
}
updateNum(aEvent) {
this.setState({
inputedNum: aEvent.nativeEvent.text,
})
}
buttonPressed() {
this.counter++;
console.log(':::'+this.counter);
}
render() {
return (
<View style={styles.container}>
<TextInput style={styles.numberInputStyle}
placeholder={'input phone number'}
onChange={(event) => this.updateNum(event)}/>
<Text style={styles.bigTextPrompt}
onPress={() => this.buttonPressed()}>
Press me...
</Text>
</View>
);
}
}
let styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
numberInputStyle: {
top: 20,
left: leftStartPoint,
width: componentWidth,
backgroundColor: 'gray',
fontSize: 20,
width:200,
height:50
},
bigTextPrompt: {
top: 70,
left: leftStartPoint,
width: componentWidth,
backgroundColor: 'gray',
color: 'white',
textAlign: 'center',
fontSize: 60
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);