react-native - Navigator and toolbarAndroid - react-native

Is there any way to set only one toolbarAndroid to be used on every screen of the application in conjunction with a navigator.
I set up a navigator in index.android.js :
import React, { Component } from 'react';
import {
AppRegistry,
Navigator,
} from 'react-native';
import ContactList from './src/containers/ContactList.js';
class MyIndex extends Component {
render() {
return (
<Navigator
initialRoute={{ name: 'index', component: ContactList }}
renderScene={(route, navigator) => {
if (route.component) {
return React.createElement(route.component, { navigator, ...route.props });
}
return undefined;
}}
/>
);
}
}
AppRegistry.registerComponent('reactest', () => MyIndex);
The first screen displays a contact list :
import React, { Component, PropTypes } from 'react';
import {
Text,
View,
TouchableOpacity,
TouchableHighlight,
ListView,
Image,
ActivityIndicator,
ToolbarAndroid,
} from 'react-native';
import styles from '../../styles';
import ContactDetails from './ContactDetails';
import logo from '../images/ic_launcher.png';
const url = 'http://api.randomuser.me/?results=15&seed=azer';
export default class ContactList extends Component {
static propTypes = {
navigator: PropTypes.object.isRequired,
}
constructor(props) {
super(props);
const datasource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = {
animating: false,
animatingSize: 0,
jsonData: datasource.cloneWithRows([]),
ds: datasource,
appTitle: 'Test',
appLogo: logo,
};
}
_handlePress() {
this.setState({
animating: true,
animatingSize: 80,
});
return fetch(url)
// convert to json
.then((response) => response.json())
// do some string manipulation on json
.then(({ results }) => {
const newResults = results.map((user) => {
const newUser = {
...user,
name: {
title: `${user.name.title.charAt(0).toUpperCase()}${user.name.title.slice(1)}`,
first: `${user.name.first.charAt(0).toUpperCase()}${user.name.first.slice(1)}`,
last: `${user.name.last.charAt(0).toUpperCase()}${user.name.last.slice(1)}`,
},
};
return newUser;
});
return newResults;
})
// set state
.then((results) => {
this.setState({
appSubTitle: 'Contacts list',
animating: false,
animatingSize: 0,
jsonData: this.state.ds.cloneWithRows(results),
});
});
}
renderRow(rowData: string) {
return (
<TouchableHighlight
onPress={() => {
this.props.navigator.push({
first: rowData.name.first,
component: ContactDetails,
props: {
title: rowData.name.title,
first: rowData.name.first,
last: rowData.name.last,
picture: rowData.picture.large,
thumbnail: rowData.picture.thumbnail,
},
});
}}
>
<View style={styles.listview_row}>
<Image
source={{ uri: rowData.picture.thumbnail }}
style={{ height: 48, width: 48 }}
/>
<Text>
{rowData.name.title} {rowData.name.first} {rowData.name.last}
</Text>
</View>
</TouchableHighlight>
);
}
render() {
const view = (
<View style={styles.container}>
<ToolbarAndroid
logo={this.state.appLogo}
title={this.state.appTitle}
subtitle={this.state.appSubTitle}
style={[{ backgroundColor: '#e9eaed', height: 56 }]}
/>
<ActivityIndicator
animating={this.state.animating}
style={[styles.centering, { height: this.state.animatingSize }]}
/>
<TouchableOpacity
onPress={() => this._handlePress()}
style={styles.button}
size="large"
>
<Text>Fetch results?</Text>
</TouchableOpacity>
<ListView
enableEmptySections
dataSource={this.state.jsonData}
renderRow={(rowData) => this.renderRow(rowData)}
onPress={() => this._handleRowClick()}
/>
</View>
);
return view;
}
}
and the second one displays a contact details :
import React, {
Component,
PropTypes,
} from 'react';
import {
Text,
View,
Image,
ToolbarAndroid,
} from 'react-native';
import styles from '../../styles';
export default class ContactDetails extends Component {
constructor(props) {
super(props);
this.state = {
animating: false,
animatingSize: 0,
appTitle: 'Test',
appLogo: { uri: this.props.thumbnail, height: 56 },
appSubTitle: `Contact Details - ${this.props.first} ${this.props.last}`,
};
}
render() {
return (
<View style={styles.container}>
<ToolbarAndroid
logo={this.state.appLogo}
title={this.state.appTitle}
subtitle={this.state.appSubTitle}
style={[{ backgroundColor: '#e9eaed', height: 56 }]}
/>
<Image
source={{ uri: this.props.picture }}
style={{ height: 128, width: 128 }}
/>
<Text>{this.props.title} {this.props.first} {this.props.last}</Text>
</View>
);
}
}
ContactDetails.propTypes = {
title: PropTypes.string.isRequired,
first: PropTypes.string.isRequired,
last: PropTypes.string.isRequired,
picture: PropTypes.string.isRequired,
thumbnail: PropTypes.string.isRequired,
};
I set up an toolbarAndroid in my first screen and another in my second screen, it's working well, but I have a feeling that it would be better to define only one toolbarAndroid and update it calling setState.
Is it possible, if so how ?

Wrap your Navigator class with your ToolbarAndroid. This way, everything that is rendered on the Navigator will be wrapped by the Toolbar. Actually, everything that is common between those scenes should be put on a single component wrapping the rest.
class MyIndex extends Component {
render() {
return (
<ToolbarAndroid>
<Navigator
initialRoute={{ name: 'index', component: ContactList }}
renderScene={(route, navigator) => {
if (route.component) {
return React.createElement(route.component, { navigator, ...route.props });
}
return undefined;
}}
/>
</ToolbarAndroid>
);
}
}

I managed to do that by wrapping the toolbarAndroid and the navigator in a view :
class MyIndex extends Component {
constructor(props) {
super(props);
this.state = {
appTitle: 'Test',
appLogo: logo,
};
}
render() {
return (
<View
style={styles.container}
>
<ToolbarAndroid
logo={this.state.appLogo}
title={this.state.appTitle}
subtitle={this.state.appSubTitle}
style={[{ backgroundColor: '#e9eaed', height: 56 }]}
/>
<Navigator
initialRoute={{ name: 'index', component: ContactList }}
renderScene={(route, navigator) => {
if (route.component) {
return React.createElement(route.component, { navigator, ...route.props });
}
return undefined;
}}
/>
</View>
);
}
}

Related

React native Flatlist error requires all the attributes

I am new to react native. I am doing a simple app where I add name and age of a person to firebase and then showing it in the list, I am using flatList in this project but it asks to import all the attributes of the flatList. if I add only 2 attributes like data, renderItem it gives an error, please help
here my code
import React from "react";
import {StyleSheet, View, Button, Text, FlatList, TextInput, ListView} from "react-native";
import firebase from './firebase'
let db = firebase.firestore();
class TextInputExample extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
userName: '',
userAge: '',
input1Background: 'red',
textColor1: 'white',
input2Background: 'red',
textColor2: 'white'
};
}
componentDidMount(): void {
db.collection('users')
.onSnapshot((snapshot) => {
snapshot.docChanges().forEach(change => {
if (change.type === 'added') {
this.state.data.push({
name: change.doc.get('name'),
age: change.doc.get('age')
});
console.log(this.state.data);
}
})
}, (error => {
console.log(error.message);
}))
}
addToDatabase = () => {
let data = {
name: this.state.userName,
age: this.state.userAge
};
console.log(data);
db.collection('users').add(data)
.then(ref => {
}).catch(msg => {
console.log(msg);
});
};
renderItem = ({item}) => {
return(
<View>
<Text>{item.name}</Text>
<Text>{item.age}</Text>
</View>
);
};
render(): React.Node {
return (
<View style={styles.container}>
<TextInput
placeHolder={'Enter name'}
onChangeText={(text) => this.setState( {userName: text} )}
/>
<TextInput
placeHolder={'Enter Age'}
onChangeText={(text) => this.setState( {userAge: text} )}
/>
<Button title={'Add'} onPress={() => this.addToDatabase()}/>
<View>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
/>
</View>
</View>
);
}
}
export default TextInputExample;
const styles = StyleSheet.create({
container: {
flex: 1, alignSelf: 'center', alignItems: 'center'
}
});
I think your error is because you're updating your state in the wrong way, if you want to add an element to an array in your state you must do it using the setState method and not directly accessing to the array and push it.
Do this
const newItem = {
name: change.doc.get('name'),
age: change.doc.get('age')
}
this.setState((prevState) => ({
...prevState,
data: [...prevState, newItem]
}))

React native navigation with redux

I have an inbox component which fetches all the notifications from the server and lists in a view. The code for which looks like,
import React, { Component } from 'react'
import {
View,
FlatList,
ActivityIndicator,
TouchableOpacity
} from 'react-native'
import {List, ListItem, SearchBar} from 'react-native-elements'
import Header from '../common/Header'
import { Container } from 'native-base'
import PushNotifications from '../../fcm/notifications/PushNotifications'
import NotificationDetails from './NotificationDetails';
export const Navigator = new StackNavigator({
NotificationList: { screen: NotificationList },
NotificationDetail: { screen: NotificationDetail },
},{
initialRouteName: 'NotificationList',
})
class NotificationList extends Component {
constructor(props) {
super(props)
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false
}
this.loadNotificationDetails = this.loadNotificationDetails.bind(this)
}
componentDidMount() {
const{dispatch,actions} = this.props
dispatch(actions.getNotification())
}
handleRefresh = () => {
this.setState(
{
page: 1,
seed: this.state.seed + 1,
refreshing: true
},
() => {
const{dispatch,actions} = this.props
dispatch(actions.getNotification())
}
)
}
handleLoadMore = () => {
this.setState(
{
page: this.state.page + 1
},
() => {
const{dispatch,actions} = this.props
dispatch(actions.getNotification())
}
);
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "86%",
backgroundColor: "#CED0CE",
marginLeft: "14%"
}}
/>
);
};
renderHeader = () => {
return <SearchBar placeholder="Type Here..." lightTheme round />
}
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: "#CED0CE"
}}
>
<ActivityIndicator animating size="large" />
</View>
)
}
loadNotificationDetails = () => {
this.props.navigation.navigate('NotificationDetails')
}
render() {
return (
<Container >
<Header />
<List containerStyle={{ marginTop: 0, borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={this.props.listNotification}
renderItem={({ item }) => (
<TouchableOpacity
onPress={() => this.loadNotificationDetails()}>
<ListItem
roundAvatar
title={`${item.text}`}
subtitle={item.dateTime}
// avatar={{ uri: item.picture.thumbnail }}
containerStyle={{ borderBottomWidth: 0 }}
/>
</TouchableOpacity>
)}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
onRefresh={this.handleRefresh}
refreshing={this.state.refreshing}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={50}
/>
</List>
<PushNotifications />
</Container>
)
}
}
export default NotificationList;
Now what i want to achieve is on clicking any of the listItem, i want to load the complete detailed notification.
Whats happening is when i click it seems to be missing the navigation object. Hence its complaining cannot find property of navigate.
The props is having only the items from the redux store, i am not able to understand how do i get the navigation props into this component which is already having props from the redux store?
How do i achieve this? Any help is much appreciated.
Thanks,
Vikram
StackNavigator is a factory function instead of a constructor. Have you try
const Navigator = StackNavigator({
NotificationList: { screen: NotificationList },
NotificationDetail: { screen: NotificationDetail },
},{
initialRouteName: 'NotificationList',
})
It is a bit confusing, however in v2 the team change the api to createStackNavigator.

Why isn't the Todo class rendering

I have the following script. It's not quite there yet but I'm stuck on getting the class to render
Here's where I think I'm messing up:
{this.state.todos.map(todo=>{
<Todo
onToggle={()=>(this.toggle(todo.id))}
onDelete={()=>(this.removeTodo(todo.id))}
todo={todo}
key={todo.id}
/>})}
and here's the entire code:
import React from 'react';
import { TextInput,Button, StyleSheet, View,Text, ScrollView } from 'react-native';
import {Constants} from 'expo'
let id=0
{/* const Todo = (props) => (
<Text>
{/* <input type='checkbox'
checked={props.todo.checked}
onClick={props.onToggle}
/>
<Button title='delete' button onPress={props.onDelete}></Button>
<Text>{props.todo.text}</Text>
</Text>
) */}
class Todo extends React.Component{
shouldComponentUpdate(nextProps,nextState){
return true
}
render(){
console.log('inside')
return(
<Text>
<Button title='delete' button onPress={props.onDelete}></Button>
<Text>{props.todo.text}</Text>
</Text>
)
}}
export default class App extends React.Component {
constructor(){
super()
this.state={
todos:[],
inputText:'',
update:false
}
}
clearText(){
this.setState({inputText:''})
this.setState({update:true})
}
addTodo(text){
this.setState({update:false})
this.setState({todos: [...this.state.todos,
{ id:id++,
text: text,
checked:false
}
]
})
this.setState({inputText:text})
}
toggle(id){
this.setState({todos: this.state.todos.map(todo=>{
if(id!==todo.id)return todo
return{
id:todo.id,
text:todo.text,
checked: !todo.checked}})})
}
removeTodo(id){
this.setState({todos: this.state.todos.filter(todo=>(todo.id!==id))})
}
render(){
return(
<View style={styles.container}>
<Text >Count of Todos: {this.state.todos.length}</Text>
<Text >{"Todo's checked:"}
{this.state.todos.filter(todo =>(todo.checked===true)).length}</Text>
<TextInput
style={{height:25,borderColor:'red',borderWidth:1,textAlign:'center'}}
value={this.state.inputText}
placeholder={'add Todo'}
onSubmitEditing={()=>{this.clearText()}}
onChangeText={(text) => {this.addTodo(text)}}
/>
<ScrollView>
{this.state.todos.map(todo=>{
<Todo
onToggle={()=>(this.toggle(todo.id))}
onDelete={()=>(this.removeTodo(todo.id))}
todo={todo}
key={todo.id}
/>})}
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
container:{
flex:1,
flexDirection:'column',
height:50,
paddingTop:3*Constants.statusBarHeight,
}
})
You need to return the data from the map in order to render it.
{this.state.todos.map(todo=> (
<Todo
onToggle={()=>(this.toggle(todo.id))}
onDelete={()=>(this.removeTodo(todo.id))}
todo={todo}
key={todo.id}
/>))}
=> {} returns undefined since it is an explicit block, you need to return an implicit block
Here is working code. I modified your code to run on my pc.
import React from 'react';
import {TextInput, Button, StyleSheet, View, Text, ScrollView} from 'react-native';
//import {Constants} from 'expo'
let id = 0
{/* const Todo = (props) => (
<Text>
{/* <input type='checkbox'
checked={props.todo.checked}
onClick={props.onToggle}
/>
<Button title='delete' button onPress={props.onDelete}></Button>
<Text>{props.todo.text}</Text>
</Text>
) */}
class Todo extends React.Component {
shouldComponentUpdate (nextProps, nextState) {
return true
}
render () {
console.log('inside')
return (
<Text>
<Button title='delete' onPress={this.props.onDelete}></Button>
<Text>{this.props.todo.text}</Text>
</Text>
)
}
}
export default class App extends React.Component {
constructor () {
super()
this.state = {
todos: [],
inputText: '',
update: false
}
}
clearText () {
this.setState({inputText: ''})
this.setState({update: true})
}
addTodo (text) {
this.setState({update: false})
this.setState({
todos: [...this.state.todos,
{
id: id++,
text: text,
checked: false
}
]
})
this.setState({inputText: text})
}
toggle (id) {
this.setState({
todos: this.state.todos.map(todo => {
if (id !== todo.id) return todo
return {
id: todo.id,
text: todo.text,
checked: !todo.checked
}
})
})
}
removeTodo (id) {
this.setState({todos: this.state.todos.filter(todo => (todo.id !== id))})
}
render () {
return (
<View style={styles.container}>
<Text >Count of Todos: {this.state.todos.length}</Text>
<Text >{"Todo's checked:"}
{this.state.todos.filter(todo => (todo.checked === true)).length}</Text>
<TextInput
style={{height: 25, borderColor: 'red', borderWidth: 1, textAlign: 'center'}}
value={this.state.inputText}
placeholder={'add Todo'}
onSubmitEditing={() => {this.clearText()}}
onChangeText={(text) => {this.addTodo(text)}}
/>
<ScrollView>
{this.state.todos.map(todo =>
<Todo
onToggle={() => (this.toggle(todo.id))}
onDelete={() => (this.removeTodo(todo.id))}
todo={todo}
key={todo.id}
/>
)}
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
height: 50,
//paddingTop:3*Constants.statusBarHeight,
paddingTop: 3 * 10,
}
})

function is not a function - react-native

In my project, I used stack navigator as the navigator. Inside navigationOptions, at headerRight, I used a custom button. When I try to call the onPress, it says the function is not a function.
this is the function
sharePost() {
// this.props.doShare();
console.log("DONE");
}
I have put the full code here. I want to use sharePost function inside the rightHeader of navigationOptions.
import React, { Component } from "react";
import Icon from "react-native-vector-icons/MaterialCommunityIcons";
import {
View,
Text,
Image,
TouchableOpacity,
Animated,
ScrollView,
StyleSheet,
Dimensions
} from "react-native";
import { PostProfileBar, WritePost } from "../../components";
import { ButtonWithoutBackground } from "../../mixing/UI";
const width = Dimensions.get("window").width;
const height = Dimensions.get("window").height / 3;
class SharePostScreen extends Component {
constructor(props) {
super(props);
sharePost() {
// this.props.doShare();
console.log("DONE");
}
render() {
return (
<View style={styles.container}>
<ScrollView>
<WritePost profile={this.state.loggedUserProfile} />
<View style={styles.sharePostWrapper}>
<PostProfileBar profile={this.state.postedUserProfile} />
<Image
source={{
uri: "https://pbs.twimg.com/media/DWvRLbBVoAA4CCM.jpg"
}}
resizeMode={"stretch"}
style={styles.image}
/>
</View>
</ScrollView>
</View>
);
}
static navigationOptions = ({ navigation }) => ({
headerTitle: "Share To Feed",
headerTitleStyle: {
paddingLeft: "20%",
paddingRight: "20%"
},
headerStyle: {
paddingRight: 10,
paddingLeft: 10
},
headerLeft: (
<Icon
name={"close"}
size={30}
onPress={() => {
navigation.goBack();
}}
/>
),
headerRight: (
<ButtonWithoutBackground
buttonText={styles.buttonText}
onPress={this.sharePost()}
>
Post
</ButtonWithoutBackground>
)
});
}
In order to call the class level methods inside the static method navigationOptions, you can do the following,
// Bind function using setParams
componentDidMount() {
const { navigation } = this.props;
navigation.setParams({
referencedSharePost: this.sharePost,
});
}
sharePost = (parameters) => {
// this.props.doShare();
console.log("DONE" + parameters);
}
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
//... Other Options
headerRight: (
<ButtonWithoutBackground
buttonText={styles.buttonText}
onPress={() => params.referencedSharePost("I'm passing something")}
>
Post
</ButtonWithoutBackground>
)
}
}

App get close when i pressed back button of android while using react native

I am new in react native. I have two pages in my app. When i press the back button, i want to open the previous page but when i press the back button, app get close. What can be done to solve this issue ?
My code is :
'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
TextInput,
TouchableHighlight
} from 'react-native';
import ToolbarAndroid from 'ToolbarAndroid';
import ActionButton from 'react-native-action-button';
import backAndroid from 'react-native-back-android';
import {hardwareBackPress} from 'react-native-back-android';
class AwesomeProject extends Component {
renderScene(route, navigator) {
if(route.name == 'HomePage') {
return <HomePage navigator={navigator} {...route.passProps} />
}
if(route.name == 'FormBuilderPage') {
return <FormBuilderPage navigator={navigator} {...route.passProps} />
}
}
render() {
return (
<Navigator
style={{ flex:1 }}
initialRoute={{ name: 'HomePage' }}
renderScene={ this.renderScene } />
)
}
}
class BackButtonEvent extends React.Component{
handleHardwareBackPress(){
if(this.sate.isOpen()){
this.handleClose();
return true;
}
}
}
var HomePage = React.createClass({
_navigate(name) {
this.props.navigator.push({
name: 'FormBuilderPage',
passProps: {
name: name
}
})
},
render() {
return (
<View style={styles.container}>
<ToolbarAndroid style = {styles.toolbar}>
<Text style = {styles.titleText}> Data Collector </Text>
</ToolbarAndroid>
<ActionButton
source = {require('./icon_container/ic_plus_circle_add_new_form.png')}
onPress = {this._navigate}
>
</ActionButton>
</View>
)
}
})
var FormBuilderPage = React.createClass({
render() {
return (
<View style={styles.container}>
<ToolbarAndroid style = {styles.toolbar}>
<TextInput placeholder = "Text here"/>
</ToolbarAndroid>
</View>
)
}
})
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
toolbar: {
height: 56,
backgroundColor: '#3F51B5'
},
titleText: {
color: '#fff',
}
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
You need to use BackAndroid API of React Native. This is the snippet from my example project.
BackAndroid.addEventListener('hardwareBackPress', () => {
var flag = false;
if(_route.name==="newbooking"){
Alert.alert(
"Confirmation",
"Are you sure you want to cancel?",
[
{text: 'No', onPress: () => console.log('OK Pressed!')},
{text: 'Yes', onPress: () => {_navigator.pop();}}
]
);
return true;
}
else{
flag = true;
}
if (_navigator.getCurrentRoutes().length === 1 ) {
return false;
}
if(flag){
_navigator.pop();
return true;
}
});
You can see how I have implemented that here!