To pass the values on another page in react native - javascript

I'm working on to pass the values from one page to another. I'm passing the values with navigation.
I tried this code
this.props.navigation.navigate('welcome',
{JSON_ListView_Clicked_Item:this.state.email,}))
in parent class from which i'm sending.
const { navigation } = this.props;
const JSON_ListView_Clicked_Item =
navigation.getParam('JSON_ListView_Clicked_Item', 'NO-ID');
<Text>JSON_ListView_Clicked_Item:
{JSON.stringify(JSON_ListView_Clicked_Item)}</Text>
this is the second class where i want data.
This is my code
this.state = { email: '', password: '', error: ''};
firebase.auth()
.signInWithEmailAndPassword(email,
password).then(this.onLoginSuccess.bind(this))
.then(() => this.props.navigation.navigate('welcome',
{JSON_ListView_Clicked_Item:this.state.emai
l,}))
set the text input
<TextInput
style={{height: 40,width:250, borderRadius: 5
,multiline:"true",borderColor: 'purple',
borderWidth: 2,
}}
value={this.state.email}
secureTextEntry={false}
onChangeText={email => this.setState({ email })}
placeholder="email"
onSubmitEditing={() => {
this.focusNextField('Password');
}}
returnKeyType={ "next" }
ref={ input => {
this.inputs['email'] = input;
}}
/>
set the text input on the second class to get data
renderComponent() {
const { navigation } = this.props;
const JSON_ListView_Clicked_Item =
navigation.getParam('JSON_ListView_Clicked_Item', 'NO-ID');
if (this.state.loggedIn) {
return (
<View>
<Text>JSON_ListView_Clicked_Item:
{JSON.stringify(JSON_ListView_Clicked_Item)}</Text>
<Button
title="Sign out"
onPress={() => firebase.auth().signOut()}
/>
</View>
);
I'm getting the blank data on the second page. I just want that when I fill the email and click the button I get the email on next page

import React from 'react';
import { Button, View, Text } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation'; // Version can be specified in package.json
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
title="Go to Details"
onPress={() => {
/* 1. Navigate to the Details route with params */
this.props.navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});
}}
/>
</View>
);
}
}
class DetailsScreen extends React.Component {
render() {
/* 2. Get the param, provide a fallback value if not available */
const { navigation } = this.props;
const itemId = navigation.getParam('itemId', 'NO-ID');
const otherParam = navigation.getParam('otherParam', 'some default value');
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
<Text>itemId: {JSON.stringify(itemId)}</Text>
<Text>otherParam: {JSON.stringify(otherParam)}</Text>
</View>
);
}
}
here is a sample that you can pass data to another page but first do these steps
yarn add react-navigation
yarn add react-native-gesture-handler
react-native link react-native-gesture-handler
you can also visit following 2 pages
https://reactnavigation.org/docs/en/getting-started.html --> FOR INSTALLING NAVIGATION
https://reactnavigation.org/docs/en/params.html --> FOR PASSING DATA

sender
`this.props.navigation.navigate('Details', {
itemId: 86,
otherParam: 'anything you want here',
});`
receiver
const { navigation } = this.props;
const itemId = navigation.getParam('itemId', 'NO-ID');
const otherParam = navigation.getParam('otherParam', 'some default value');
check documentation here

Related

How do i pass item data from Flatlist in react native

I'm new to react. I have my App.js page that contains the main code, and a lists.js page in another folder that contains the list itself.
I import from lists.js into my App.js. It works fine.
I'm trying to set an onPress action for the listItems that also sends a unique ID to the next page that I can use to call out items in the new page.
For clarity, if i was to do this with a normal button, it will look like:
this.props.navigation.navigate('NextPage', { Email: UserEmail });
So how do i do this with a ListView that I imported from another file.
This is how my code is structured
App.js
import MarketList from './lists/markets';
class ProfileActivity extends Component
{
static navigationOptions =
{
title: 'Home',
headerStyle : {
backgroundColor: '#00b47a'
},
headerTitleStyle: {
color: 'white'
},
headerLeft: null,
headerRight: (
<Icon containerStyle={{ paddingRight: 15 }}
color='#000' onPress={()=> navigation.getParam('openBottomSheet')()}
name="menu" />
)
};
constructor () {
super()
this.state = { toggled: false }
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<MarketList />
</View>
);
}
}
My lists.js
export default class MarketList extends React.Component {
constructor(props) {
super(props)
this.state = {
items: '',
};
}
render() {
fetch('https://example.php')
.then((response) => response.json())
.then((json) => {
this.setState({
items: json.items,
})
})
.catch((error) => {
console.error(error);
});
return (
<View style={styles.container}>
<FlatList
data={this.state.items}
renderItem={({item}) => <TouchableOpacity onPress={} style={styles.itemList}><View style={styles.item}><Text style={styles.market}>{item.name}</Text><Text style={styles.location}>{item.Location}</Text></View><View style={styles.go}><Icon name="arrow-right" color="#00b47a" /></View></TouchableOpacity>}
/>
</View>
);
}
}
You can do something like below
Pass navigation as a prop to MarketList component
<MarketList navigation={this.props.navigation}/>
And use like below
renderItem={({item}) => <TouchableOpacity onPress={()=>this.props.navigation.navigate("pagename",{item:item})}

How to get params in other App Container - React Navigation?

I want to use the params I passed to Profile Screen and he is in a separate App Container,
And I create TopTabs and put it in a specific AppContainer because I don't have any way to use it in a one AppContainer so how I Get these Params from another AppContainer?
So My Code here's
First thing, now I'm in the Map Screen and want to navigate to profile screen and pass some params like this
this.props.navigation.navigate('ProviderProfile', {
providerId: marker.id,
providerName: marker.name,
providerService: marker.service,
gKey: marker.gKey,
token: marker.token._55,
region: region
}
And here is Profile Screen, Contain let's say Card and TobTabs "I wrap it in a separate AppContainer"
and want to use params I passed in these TopTabs "every single tab" so how to handle these OR pass these params to every single Tab?
ProviderProfile.js
import React, { Component } from "react";
import Icon from "react-native-vector-icons/Ionicons";
import firebase from "react-native-firebase";
import { createAppContainer } from "react-navigation";
import { NavTabs } from "./ProviderTabs/NabTabs";
import { View, Text, StyleSheet, TouchableOpacity, Image } from "react-native";
console.disableYellowBox = true;
class ProviderProfile extends Component {
static navigationOptions = ({ navigation }) => {
const { state } = navigation;
return {
title: ` ${state.params.providerName}` || "profile"
};
};
constructor(props) {
super(props);
this.state = {
providerId: this.props.navigation.getParam("providerId"),
providerService: this.props.navigation.getParam("providerService"),
providerName: this.props.navigation.getParam("providerName"),
gKey: this.props.navigation.getParam("gKey"),
token: this.props.navigation.getParam("token"),
region: this.props.navigation.getParam("region"),
fav: false
};
}
_addToFavorite = () => {
const { providerName, providerService, providerId, fav } = this.state;
const currentUser = firebase.auth().currentUser.uid;
this.setState({ fav: !fav });
const ref = firebase
.database()
.ref(`favorites/${currentUser}/${providerId}`);
if (!fav) {
ref
.set({
ProviderId: providerId,
providerName: providerName,
providerService: providerService
})
.then(() => alert("Great, Added to your favorite list"));
} else {
ref.remove();
}
};
render() {
const {
providerName,
providerService,
providerId,
fav,
gKey,
region,
token
} = this.state;
return (
<View style={styles.container}>
{/* <Text>{gKey}</Text> */}
<Image
resizeMode="contain"
source={require("../assets/marker.png")}
/>
<View>
<View>
<Icon
name={`ios-heart${fav ? "" : "-empty"}`}
size={35}
color="#f00"
onPress={this._addToFavorite}
/>
</View>
<Text>
<Icon name="ios-star" size={20} color="#f2ba13" />
<Icon name="ios-star" size={20} color="#f2ba13" />
<Icon name="ios-star" size={20} color="#f2ba13" />
<Icon name="ios-star-half" size={20} color="#f2ba13" />
<Icon name="ios-star-outline" size={20} color="#f2ba13" />
</Text>
<Text style={{ fontSize: 19, color: "#000", padding: 5 }}>
{providerName}
</Text>
<Text>
Service: <Text>{providerService}</Text>
</Text>
<View style={{ flexDirection: "row", marginTop: 10 }}>
<TouchableOpacity
onPress={() => alert("Message")}
>
<Text>
Message
</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate("Order", {
providerName,
providerId,
providerService,
gKey,
token,
region
})
}
>
<Text
>
Send Order
</Text>
</TouchableOpacity>
</View>
</View>
<Roots /> // Here's Tabs
</View>
);
}
}
const Roots = createAppContainer(NavTabs);
export default ProviderProfile;
And Here is a Tabs Screen "NavTabs"
import {
createMaterialTopTabNavigator,
} from "react-navigation";
import AboutScreen from "./About";
import GalaryScreen from "./Galary";
import ReviewsScreen from "./Reviews";
export const NavTabs = createMaterialTopTabNavigator(
{
About: { screen: AboutScreen },
Galaty: { screen: GalaryScreen },
Reviews: { screen: ReviewsScreen }
},
{
tabBarOptions: {
activeTintColor: "#fff",
inactiveTintColor: "#ddd",
tabStyle: {
justifyContent: "center"
},
indicatorStyle: {
backgroundColor: "#fcc11e"
},
style: {
backgroundColor: "#347ed8"
}
}
}
);
As you see, I want to use the username in Tab "About"
or other Tabs
Send params:
this.props.navigation.navigate('RouteName', { /* params go here */ })
Get params:
this.props.navigation.getParam(paramName, defaultValue)
Example:
this.props.navigation.navigate('NameListScreen', { names:["John","Mary"] })
let params = this.props.navigation.getParam(names, [])
I haven't use React Navigation myself but in their documentation say you can pass props to App Containers, so as you have defined the state with the props from the MapScreen you should probably pass them as props where you have defined your NavTabs Component as <Roots />
Also, there is another alternative to want to achieve as they present in here and it will be done in a redux way.

React Native error when passing size of ActivityIndicator as a prop

I was creating a reusable spinner component for my project I had created 2 components: loginform and spinner, where i passed an enum as a prop from loginform to spinner when I reloaded the app it crashed on android but thankfully it displayed an error message on iOS saying "Error while updating property 'width' in shadow node of type: AndroidProgressBar".
I've tried removing the reference to the prop and instead specified the enum values i.e., 'small' or 'large' to the spinner component. It worked but that completely destroyed the whole point of creating a reusable component.
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import firebase from 'firebase';
import { Button, Card, CardSection, Input, Spinner } from './common/';
class LoginForm extends Component {
state = { email: '', password: '', error: '', loading: false };
onButtonPress() {
const { email, password } = this.state;
this.setState({ error: '', loading: true });
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(() => {
this.setState({ error: 'Authentication Failed!' });
});
});
}
renderButton() {
if (this.state.loading) {
return <Spinner size="small" />;
}
return <Button onPress={this.onButtonPress.bind(this)}>Log In</Button>;
}
render() {
return (
<View style={{ marginTop: 50 }}>
<Card>
<CardSection>
<Input
autoCorrect={false}
label='Email :'
placeholder='user#example.com'
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
</CardSection>
<CardSection>
<Input
secureTextEntry
placeholder='password'
label='Password :'
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</CardSection>
<Text style={styles.errorTextStyle}>{this.state.error}</Text>
<CardSection style={{ flexDirection: 'column' }}>
{this.renderButton()}
</CardSection>
</Card>
</View>
);
}
}
const styles = {
errorTextStyle: {
fontSize: 20,
color: 'red',
alignSelf: 'center',
borderColor: 'white',
}
};
export default LoginForm;
The other component's code:
import React from 'react';
import { ActivityIndicator, View } from 'react-native';
// eslint-disable-next-line arrow-body-style
const Spinner = (size) => {
return (
<View style={styles.spinnerStyle}>
<ActivityIndicator size={size || 'large'} />
</View>
);
};
const styles = {
spinnerStyle: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
};
export { Spinner };
I ran the above code and on the expo app on android, it crashed and on ios it didn't crash but displayed the above mentioned error on the red screen.
Did you used "this.props.prop" to access the props, if so, an stateless component doesn't have the "this.props" property, instead you should pass the props like this
In your login screen use this normally
if (this.state.loading) {
return <Spinner prop="small" />;
}
In your component use this
const Spinner = (prop) => {
return (
<View style={styles.spinnerStyle}>
<ActivityIndicator size=prop />
</View>
);
};

onSubmitEditing never fires?

Really simple question, why isn't onSubmitEditing firing when I hit 'Search' on the virtual keyboard?
Currently there are no errors thrown and the console.log in onSearch() never fires.
I'm using the EXPO SDK v.29.
import React from 'react';
import { StyleSheet, Text, View, TextInput, ScrollView, Image } from 'react-native';
import { WebBrowser } from 'expo';
import Icon from 'react-native-vector-icons/Ionicons';
import Styles from 'app/constants/Styles';
import Vars from 'app/constants/Vars';
import Menu from 'app/components/Menu';
import MiniMap from 'app/components/MiniMap';
import NewsList from 'app/components/NewsList';
import {get, post} from 'app/helpers/api';
export default class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: (<Image style={{width: 132, height: 30}} source={require('./../../assets/images/header_image.png')}/>)
};
};
constructor(props) {
super(props);
this.state = {
menu: [],
loadingMenu: true,
searchString: '',
};
}
onMenuPress = (item) => {
let next;
let route = item.page_type.slice(4);
if(route == "PageExternal") {
WebBrowser.openBrowserAsync(item.page.url);
} else {
data = item.page;
if(item.children.length > 0) {
route = 'Menu';
data = item.children;
}
this.props.navigation.navigate(route, {
data: data,
title: item.title
});
}
}
onSearch = (e) => {
console.log('onSearch', e);
//WebBrowser.openBrowserAsync('https://www.1177.se/Halland/Sok/?q=Diabetes&submitted=true');
}
async componentDidMount() {
console.log('Eat my shorrs');
menuitems = await get('content/menu');
this.setState({
menu: menuitems,
loadingMenu: false,
})
//this._getMenu();
}
render() {
return (
<ScrollView style={Styles.whiteBackground}>
<View style={[Styles.blueBackground, Styles.topPadding, Styles.horizontalPadding]}>
<View style={[Styles.searchBox, Styles.bottomMargin]}>
<View style={Styles.searchField}>
<TextInput
style = {Styles.searchInput}
placeholder = "Sök sjukdom/behandling"
onSubmitEditing = {(e) => (this.onSearch(e))}
underlineColorAndroid = "transparent"
returnKeyLabel = "Sök på 1177"
returnKeyType = "search"
/>
<Icon style = {Styles.searchIcon} name = "ios-search" size={18}/>
</View>
<Text style={[Styles.searchLabel]}>Söksvaren kommer från 1177.se</Text>
</View>
<Menu
data={this.state.menu}
loading={this.state.loadingMenu}
style={Styles.topPadding}
onItemPress={this.onMenuPress}
/>
</View>
<Text style={[Styles.h1, Styles.blackText, Styles.horizontalPadding]}>Hitta till oss</Text>
<MiniMap navigation={this.props.navigation}></MiniMap>
<Text style={[Styles.h1, Styles.blackText, Styles.horizontalPadding]}>Nyheter</Text>
<NewsList navigation={this.props.navigation}></NewsList>
</ScrollView>
);
}
}
<TextInput
onSubmitEditing = {(event) => (this.onSearch(event.nativeEvent.text))}
multiline={false}
/>
It does not work when multiline={true} is specified, perhaps your styles has that. See Documentation
You will find your text with event.nativeEvent.text
Try changing
onSubmitEditing = {(e) => (this.onSearch(e))}
to
onSubmitEditing = {this.onSearch}
Then keep
onSubmitEditing = {(e) => this.onSearch(e)}
like this and try by changing the function like below
function onSearch(e) {
console.log('onSearch', e);
//WebBrowser.openBrowserAsync('https://www.1177.se/Halland/Sok/?q=Diabetes&submitted=true');
}
Hope this will work
Check this out
https://snack.expo.io/#raajnadar/submit-text-input
Render method
render() {
return (
<View style={styles.container}>
<TextInput
placeholder="Sök sjukdom/behandling"
onSubmitEditing={this.onSearch}
underlineColorAndroid="transparent"
returnKeyLabel="Sök på 1177"
returnKeyType="search"
style={{ width: '100%', textAlign: 'center' }}
/>
</View>
);
}
On submit function
onSearch() {
console.log('onSearch')
}

React Native Elements Checkbox Should be checked after clicking

I'm using React Native Elements CheckBox inside List Items, of Flat List.
import React, { Component } from "react";
import { View, Text, StyleSheet, FlatList } from "react-native";
import axios from "axios";
import {
Button,
Container,
Content,
Header,
Body,
Left,
Right,
Title
} from "native-base";
import Icon from "react-native-vector-icons/Ionicons";
import { List, ListItem, SearchBar, CheckBox } from "react-native-elements";
// const itemId = this.props.navigation.getParam('itemId', 'NO-ID');
// const otherParam = this.props.navigation.getParam('otherParam', 'some default value');
class TeacherSubjectSingle extends Component {
static navigationOptions = {
header: null
};
// static navigationOptions = {
// headerStyle: {
// backgroundColor: '#8E44AD',
// },
// headerTintColor: '#fff',
// }
state = {
class_id: null,
userid: null,
usertype: null,
student_list: [],
faq: [],
checked: []
};
componentWillMount = async () => {
const {
class_id,
student_list,
userid,
usertype
} = this.props.navigation.state.params;
await this.setState({
class_id: class_id,
student_list: student_list,
userid: userid,
usertype: usertype
});
console.log(this.state.class_id);
var result = student_list.filter(function(obj) {
return obj.class_section_name == class_id;
});
this.setState({
student_list: result[0]
});
};
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#CED0CE"
}}
/>
);
};
checkItem = item => {
const { checked } = this.state;
if (!checked.includes(item)) {
this.setState({ checked: [...checked, item] });
} else {
this.setState({ checked: checked.filter(a => a !== item) });
}
};
render() {
return (
<Container>
<Header style={{ backgroundColor: "#8E44AD" }}>
<Left>
<Button
transparent
onPress={() => this.props.navigation.navigate("ClassTeacher")}
>
<Icon name="ios-arrow-dropleft" size={24} color="white" />
</Button>
</Left>
<Body>
<Title style={{ color: "white" }}>{this.state.class_id}</Title>
</Body>
<Right />
</Header>
<View style={{ flex: 1, backgroundColor: "#fff" }}>
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={this.state.student_list.students}
renderItem={({ item }) => (
<ListItem
// roundAvatar
title={
<CheckBox
title={item.name}
onPress={() => this.checkItem(item.userid)}
checked={this.state.checked.includes(item.userid)}
/>
}
// subtitle={item.email}
// avatar={{ uri: item.picture.thumbnail }}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() =>
this.props.navigation.navigate("IndividualChat", {
rc_id: item.userid,
userid: this.state.userid,
usertype: this.state.usertype,
subject_name: this.state.student_list.subject_name
})
}
/>
)}
keyExtractor={item => item.userid}
ItemSeparatorComponent={this.renderSeparator}
/>
</List>
</View>
</Container>
);
}
}
export default TeacherSubjectSingle;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center"
}
});
Above is my code for the same, I have tried every possibility and checked the GitHub page for the same, but my items are not getting checked if I press on the checkbox.
My renderItem will have an array to render which is having a field like 'name' and 'userid'.
This is the example of the code from where I have coppied the coding for the same, where it is working
I want to save selected ids to an array so that I can pass that as a prop to the next screen.
Since FlatList is a PureComponent, it will not re-render the items unless the data changes. If you want the FlatList to re-render when checked array changes, you need to pass it to e.g. extraData.
<FlatList
data={this.state.student_list.students}
extraData={this.state.checked}
renderItem={({ item }) => {
// ...
}}
keyExtractor={item => item.userid}
ItemSeparatorComponent={this.renderSeparator}
/>

Categories

Resources