React native how to manage list of inputs - react-native

I wrote an api it return jsondata and limit. I'm creating inputlist in scrollview by lenght of limit.In creation i set the values to input comes from jsondata. Jsondata is may content 0-30 value.
I just gotta how to save this as array.
Here's my code it gives value to input if not undefined
Also do i need onchange for input component for input
export class DataListFor extends Component {
constructor() { super();
this.state = {
dataSource: [],
limit: 30,
}; }
componentDidMount() {
const url = "https://sssaaaaaexample.herokuapp.com/getExample";
this.setState({
dataSource: this.props.route.params.list,
limit: this.props.route.params.limit,
})
}
render() {
var itemList = [];
var data=this.state.dataSource;
for(let i = 0; i < this.state.limit; i++){
if(data[i]==undefined)
{
itemList.push(
<View key = {i}>
<View>
<TextInput
style={{ height: "auto",width:'auto', alignItems: 'center',
fontSize: 20,borderColor:'white',borderWidth:1}}
/>
</View>
</View>
)
}
else{
itemList.push(
<View key = {i}>
<View>
<TextInput
style={{ height: "auto",width:'auto',borderColor:'white',borderWidth:1}}
value={data[i].text}
/>
</View>
</View>
)
}
}
return (
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
}}>
<View >
<Text style={appStyles.listHeader}> To-do</Text>
</View>
<ScrollView style={appStyles.scrollView}>
{ itemList }
</ScrollView>
<Button
title="Save"
onPress={() => console.log("saved")}
/>
</View>
)
}
}

Related

Conditional rendering based on state not working on state change

I have a value in my state that changes based on a Switch. Depending on the value of that state item I want to change the styling of my button. I can see the state change, but the color doesn't change.
This seems straightforward as shown in this documentation: https://reactjs.org/docs/conditional-rendering.html
I actually have one conditional rendering working in the same statement, but it is referencing redux state instead of component state.
I've included the relevant aspects of my code below and tried to strip out the unnecessary stuff.
Still kind of a bit long.
/* eslint-disable prettier/prettier */
import React, { Component } from 'react';
import {
View,
Text,
TouchableOpacity,
Dimensions,
StyleSheet,
TextInput,
Switch,
ActivityIndicator,
} from 'react-native';
import { connect } from 'react-redux';
// Actions
import { createUser } from '../../actions/user-actions';
// Getting dims
const { width: WIDTH } = Dimensions.get('window');
// Styling
const styles = StyleSheet.create({
containerStyle: {
flex: 1,
backgroundColor: 'black',
alignItems: 'center',
justifyContent: 'center',
},
footerContainerStyle: {
justifyContent: 'flex-start',
flex: 3,
width: WIDTH,
paddingHorizontal: 30,
alignItems: 'center',
marginTop: 45,
},
tcStyle: {
flexDirection: 'row',
marginBottom: 20,
},
switchStyle: {
marginRight: 15,
},
buttonStyle: {
width: WIDTH-100,
height: 50,
backgroundColor: '#007AFF',
borderRadius: 4,
alignItems: 'center',
justifyContent: 'center',
marginBottom: 20,
},
disabledButtonStyle: {
width: WIDTH-100,
height: 50,
backgroundColor: '#007AFF',
borderRadius: 4,
alignItems: 'center',
justifyContent: 'center',
marginBottom: 20,
opacity: 0.3,
},
buttonTextStyle: {
color: 'white',
fontSize: 14,
fontWeight: 'bold',
},
linkStyle: {
textDecorationLine: 'underline',
color: 'blue',
},
});
// Component
class Signup extends Component {
constructor(props) {
super(props);
this.state = {
switchValue: false,
email: '',
name: '',
password: '',
passwordConfirm: '',
errorMessage: '',
};
}
componentDidUpdate() {
console.log(this.props.users);
const { navigation } = this.props;
if (this.props.users.user) {
navigation.navigate('Home');
}
}
componentDidMount() {
console.log(this.props);
}
// Helper functions
toggleSwitch = (value) => {
this.setState({switchValue: value});
};
onSignUp = () => {
const { email, name, password, passwordConfirm, switchValue } = this.state;
const { createUser } = this.props;
if (password !== passwordConfirm) {
console.log('Passwords do not match')
this.setState({errorMessage: 'Passwords do not match'});
return;
}
if (!switchValue) {
console.log('You must agree to terms');
this.setState({errorMessage: 'You must agree to terms'});
return;
}
createUser(email, password, name);
}
render() {
// Conditional button rendering
const { email, password, passwordConfirm, name, switchValue } = this.state;
let button;
console.log(switchValue);
if (this.props.users.loading) {
button = (
<TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
<ActivityIndicator size="large" />
</TouchableOpacity>
);
} else if (switchValue) {
button = (
<TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
<Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
</TouchableOpacity>
)
} else if (!switchValue) {
button = (
<TouchableOpacity style={[styles.disabledButtonStyle]} onPress={this.onSignUp}>
<Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
</TouchableOpacity>
)
}
return (
<View style={styles.containerStyle}>
<View style={styles.footerContainerStyle}>
<View style={styles.tcStyle}>
<Switch
onValueChange = {this.toggleSwitch}
value = {this.state.switchValue}
style = {styles.switchStyle}
trackColor={{true: '#007AFF', false: 'grey'}}
/>
<Text style={{color: 'white', flexWrap: 'wrap', flex: 1}}>I have read & agree to the <Text style={styles.linkStyle}>Terms of Use</Text> and <Text style={styles.linkStyle}>Privacy Policy</Text></Text>
</View>
{button}
<View style={styles.textLinkStyle}>
<Text style={styles.ctaHelpTextStyle}>Have an account?</Text>
<TouchableOpacity>
<Text style={styles.ctaTextStyle}> Sign In</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
// state mapping
const mapStateToProps = ({ users }) => ({
users,
});
// Export
export default connect(mapStateToProps, {
createUser,
})(Signup);
If I toggle that switch I am expecting the button component to change to the one with the other styling. That's not happening though.
Actually your state changes correctly, but opacity does not work.
Update:
it seems react native has issues changing TouchableOpacity's opacity.
One solution is removing the opacity from the styles. And wrapping TouchableOpacity component with a View component, giving View an opacity.
You can try like this:
else if (switchValue) {
button = (
<View opacity={0.5}>
<TouchableOpacity style={styles.buttonStyle} onPress={this.onSignUp}>
<Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT true</Text>
</TouchableOpacity>
</View>
);
} else if (!switchValue) {
button = (
<View opacity={0.1}>
<TouchableOpacity
style={styles.disabledButtonStyle}
onPress={this.onSignUp}
>
<Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT false</Text>
</TouchableOpacity>
</View>
);
add return in conditions for example
if (this.props.users.loading) {
return(
<TouchableOpacity style={[styles.buttonStyle]} onPress{this.onSignUp}>
<ActivityIndicator size="large" />
</TouchableOpacity>
);
}
Based on you code, the only difference between both buttons is just the styling.
The way i would approach this is simply make the conditioning inside the styling its self not an if statement on the render method itself, follow along:
Solution
Modify this fragment:
// ... Other code parts
if (this.props.users.loading) {
button = (
<TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
<ActivityIndicator size="large" />
</TouchableOpacity>
);
} else if (switchValue) {
button = (
<TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
<Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
</TouchableOpacity>
)
} else if (!switchValue) {
button = (
<TouchableOpacity style={[styles.disabledButtonStyle]} onPress={this.onSignUp}>
<Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
</TouchableOpacity>
)
}
to this:
// ... Other code parts
if (this.props.users.loading) {
button = (
<TouchableOpacity style={[styles.buttonStyle]} onPress={this.onSignUp}>
<ActivityIndicator size="large" />
</TouchableOpacity>
);
} else {
button = (
<TouchableOpacity style={switchValue ? styles.buttonStyle : styles.disabledButtonStyle} onPress={this.onSignUp}>
<Text style={styles.buttonTextStyle}>CREATE AN ACCOUNT</Text>
</TouchableOpacity>
)
}
Hope this Helps!

Modal and FlatList

i work on my first react-native project and its also my firts javascript work. I want at least a news-app with own database informations. The backend is already finish. Now im in struggle with the app- i want an Popup with Modal with informations from my api like news_image, news_content and news_title. The News are in the FlatList and now i want to click on a item to show the content in an modal popup. so, here is my code where im struggle. i get always an error. so how can i fix this problem? tanks a lot!
import React from "react";
import {
AppRegistry,
FlatList,
Image,
Platform,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
ActivityIndicator,
ListView,
YellowBox,
Alert,
TextInput
} from "react-native";
import { WebBrowser } from "expo";
import Button from "react-native-button";
import Modal from "react-native-modalbox";
import Slider from "react-native-slider";
import { MonoText } from "../components/StyledText";
export default class NewsFeed extends React.Component {
static navigationOptions = {
title: "HomeScreen"
};
constructor(props) {
super(props);
this.state = {
isLoading: true
};
YellowBox.ignoreWarnings([
"Warning: componentWillMount is deprecated",
"Warning: componentWillReceiveProps is deprecated"
]);
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: 0.5,
width: "100%",
backgroundColor: "#000"
}}
/>
);
};
webCall = () => {
return fetch("http://XXXXXXXXXXXX.com/connection.php")
.then(response => response.json())
.then(responseJson => {
this.setState(
{
isLoading: false,
dataSource: responseJson
},
function() {
// In this block you can do something with new state.
}
);
})
.catch(error => {
console.error(error);
});
};
onClose() {
console.log("Modal just closed");
}
onOpen() {
console.log("Modal just opened");
}
onClosingState(state) {
console.log("the open/close of the swipeToClose just changed");
}
componentDidMount() {
this.webCall();
}
render() {
if (this.state.isLoading) {
return (
<View
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}
>
<ActivityIndicator size="large" />
</View>
);
}
return (
<View style={styles.MainContainer}>
<FlatList
data={this.state.dataSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={({ item }) => (
<View style={{ flex: 1, flexDirection: "row" }}>
<Image
source={{ uri: item.news_image }}
style={styles.imageView}
/>
<Text
onPress={() => this.refs.modal.open()}
style={styles.textView}
>
{item.news_title}
{"\n"}
<Text style={styles.textCategory}>{item.author}</Text>
</Text>
<Text style={styles.textViewDate}>{item.created_at}</Text>
<Modal
style={[styles.modal]}
position={"bottom"}
ref={"modal"}
swipeArea={20}
>
<ScrollView>
<View style={{ width: "100%", paddingLeft: 10 }}>
{item.news_content}
</View>
</ScrollView>
</Modal>
</View>
)}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer: {
justifyContent: "center",
flex: 1,
margin: 5
},
imageView: {
width: "25%",
height: 100,
margin: 7,
borderRadius: 7
},
textView: {
width: "100%",
height: "100%",
textAlignVertical: "center",
padding: 10,
fontSize: 20,
color: "#000"
},
textViewDate: {
width: "30%",
textAlignVertical: "center",
padding: 15,
color: "#afafaf"
},
textCategory: {
color: "#d3d3d3",
fontSize: 12
},
modal: {
justifyContent: "center",
alignItems: "center",
height: "90%"
}
});
Check the code below and compare it with your code.
I am not sure where your error is located or what your exact error is, but you can check the example code below, which is similar to yours, for comparison.
I am using 'Axios' over fetch() because of the automatic transformation to JSON and some other beneficial stuff.
npm install --save axios
Code:
import React, { Component } from 'react'
import {
ActivityIndicator,
FlatList,
Image,
ScrollView,
Text,
TouchableOpacity,
View
} from 'react-native';
import Axios from 'axios';
import Modal from "react-native-modalbox";
export default class NewsFeed extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
selectedIndex : -1
}
}
componentDidMount = () => {
Axios.get('<URL>')
.then(response => {
const { data } = response;
this.setState({dataSource : data});
}).catch(error => {
const { data } = error;
console.log(data);
});
}
_openModal = index => {
this.setState({ selectedIndex : index });
this.modalReference.open();
}
_renderSeparator = () => {
return <View style={{ flex: 1, borderBottomWidth: 0.5, borderBottomColor: '#000000' }} />
}
_renderItem = ({item, index}) => {
const {news_image, news_title, news_content, author, created_at} = item;
return <TouchableOpacity onPress={() => this._openModal(index)} >
<View style={{ flex: 1, flexDirection: 'row' }}>
<Image style={{ flex: 1, width: null, height: 200 }} source={{ uri: news_image }} />
<Text>{news_title}</Text>
<Text>{author}</Text>
<Text>{created_at}</Text>
</View>
</TouchableOpacity>;
}
render = () => {
const { dataSource, selectedIndex } = this.state;
const { news_content } = dataSource[selectedIndex];
return dataSource.length === 0 ?
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<ActivityIndicator size="large" />
</View> :
<View style={styles.MainContainer}>
<FlatList
data={dataSource}
keyExtractor={(item, index) => index.toString()}
ItemSeparatorComponent={this._renderSeparator}
renderItem={this._renderItem}
/>
<Modal ref={reference => modalReference = reference}>
<ScrollView style={{ flex: 1, padding: 20 }}>
<Text>{news_content}</Text>
</ScrollView>
</Modal>
</View>
}
}
I think the issue is in modal,
Can you re-write the code like below?
return (
<View style={styles.MainContainer}>
<FlatList
data={this.state.dataSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={({ item }) => (
<View style={{ flex: 1, flexDirection: "row" }}>
<Image source={{ uri: item.news_image }} style={styles.imageView} />
<Text onPress={() => { this.setState({ item: item.news_content }, () => this.refs.modal.open()); }} style={styles.textView}>
{item.news_title}
<Text style={styles.textCategory}>{item.author}</Text>
</Text>
<Text style={styles.textViewDate}>{item.created_at}</Text>
</View>
)}
keyExtractor={(item, index) => index.toString()}
/>
<Modal
style={[styles.modal]}
position={"bottom"}
ref={"modal"}
swipeArea={20}
>
<ScrollView>
<View style={{ width: "100%", paddingLeft: 10 }}>
{this.state.item}
</View>
</ScrollView>
</Modal>
</View>
);
Only single modal is enough for popup screen.
And you can try this also,
Change your reference to
ref={ref => this.modalRef = ref}
And use like this,
this.modalRef.open()

wants to capture image in by using expo camera

i'm trying to capture image from expo camera but when i alert my photo nothing shown up here is complete code of my component
import React from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import { Camera, Permissions } from 'expo';
import {
Container,
Title,
Content,
Header,
Button,
Switch,
Left,
Body,
Right,
List,ListItem,Thumbnail,Footer,FooterTab
} from "native-base";
import {Icon} from 'react-native-elements';
export default class CameraEx extends React.Component {
static navigationOptions = {
header: null
}
state = {
hasCameraPermission: null,
type: Camera.Constants.Type.back,
};
async componentDidMount() {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({ hasCameraPermission: status === 'granted' });
}
takePicture = async function() {
if (this.camera) {
let photo = await this.camera.takePictureAsync();
alert(photo);
}
}
render() {
const { hasCameraPermission } = this.state;
if (hasCameraPermission === null) {
return <View />;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<Container style={{ flex: 1 }}>
<Header transparent>
<Left>
<Button transparent onPress={() =>this.props.navigation.navigate('Home') }>
<Icon name='arrow-back' />
</Button>
</Left>
</Header>
<Camera style={{ flex: 1 }} type={this.state.type}>
<View
style={{
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
justifyContent:'space-between',
width:"50%"
}}>
<TouchableOpacity
style={{
//flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={() => {
this.setState({
type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back,
});
}}>
<Text
style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
{' '}Flip{' '}
</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
// flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
}}
onPress={()=>this.takePicture()}
>
<Text
style={{ fontSize: 18, marginBottom: 10, color: 'white' }}>
{' '}Take Picture{' '}
</Text>
</TouchableOpacity>
</View>
</Camera>
</Container>
);
}
}
}
here is a complete code my component please let me know how i can capture image and stored into state i'm beginner ............................................................................................................................................. ....
you cannot show a picture in alert box. you need to pass the source or base64 of image to react native Image component.
import {ImagePicker} from 'expo';
const options = {
base64: true,
allowsEditing: true
};
const data = await ImagePicker.launchCameraAsync(options);
if (data.cancelled !== true) {
this.setState({imageBase64: data.base64});
}
and then you can use like this:
<Image source={`data:image/png;base64, ${this.state.imageBase64}`} />

React native - already put the bind in constructor but still getting 'undefined is not an object (evaluating this.state)'

The problem occurs when I try to call the _setCategories function. I call it from the onpress of the TouchableHighlight inside the ListView inside the Modal. I try to bind the functions in the constructor as per recommendations on other threads without success. What am I missing? I am new to react native.
Thank you.
So here a piece of my code.
constructor(props) {
super(props);
this.state = {
...
};
this._setCategories = this._setCategories.bind(this);
this._renderItemCategoryFilter = this._renderItemCategoryFilter.bind(this);
this._onPress = this._onPress.bind(this);
}
_setCategories(categoriesArray, categoryId) {
if (categoryId == null) {
let totalListings = 0;
categoriesArray.forEach(function(category) {
totalListings += category.numberOfListings;
});
this.state.currentCategory = {
name: 'All listings',
numberOfListings: totalListings,
subcategories: categories
};
}
else
{
categoriesArray.forEach(function(category) {
if (category.id == categoryId) {
this.state.currentCategory = category;
}
else if (category.subcategories != null) {
this._setCategories(category.subcategories, categoryId)
}
});
}
}
_onPress(category) {
this._setCategories(categories, category.id);
console.log(this.state.currentCategory.name);
}
_renderItemCategoryFilter({item, index}) {
return (
<View>
<TouchableHighlight
activeOpacity={0.5}
onPress={() => this._onPress(item)}
>
<View style={{
flexDirection: 'row',
height: 35,
}}>
<Text style={{
marginLeft: 5,
textAlignVertical: 'center',
}}>{item.name}</Text>
<Text style={
{
textAlignVertical: 'center',
height: 35,
position: 'absolute',
right:5
}
}>{item.numberOfListings}</Text>
</View>
</TouchableHighlight>
<Divider/>
</View>
)
} ;
and the render
<Modal style={[styles.modal]} swipeToClose={true} swipeArea={50} position={"bottom"} ref={"modal1"}>
<View style={{
backgroundColor: '#FFFFFF',
alignItems: 'center',
justifyContent: 'center',
width: width / 2 + 100,
height: 40,
}}>
<Text style={{fontWeight: 'bold'}}>{this.state.currentCategory.name}</Text>
<Text style={{fontWeight: 'bold'}}>{`${this.state.currentCategory.numberOfListings} result${this.state.currentCategory.numberOfListings == 1 ? '' : 's' }`} </Text>
</View>
<Divider/>
<ScrollView style={styles.scrollViewCategories}>
<FlatList
data={this.state.currentCategory.subcategories}
style={styles.flatList}
keyExtractor={(item, index) => index}
renderItem={(item, index) => this._renderItemCategoryFilter(item, index)}
/>
</ScrollView>
</Modal>
Quick fix would be using arrow function expression.
constructor(props) { super(props); this.state = { ... }; } _setCategories = (categoriesArray, categoryId) => { if (categoryId == null) { let totalListings = 0; categoriesArray.forEach(function(category) { totalListings += category.numberOfListings; }); this.state.currentCategory = { name: 'All listings', numberOfListings: totalListings, subcategories: categories }; } else { categoriesArray.forEach(function(category) { if (category.id == categoryId) { this.state.currentCategory = category; } else if (category.subcategories != null) { this._setCategories(category.subcategories, categoryId) } }); } } _onPress= (category) => { this._setCategories(categories, category.id); console.log(this.state.currentCategory.name); } _renderItemCategoryFilter = ({item, index}) => { return ( <View> <TouchableHighlight activeOpacity={0.5} onPress={() => this._onPress(item)} > <View style={{ flexDirection: 'row', height: 35, }}> <Text style={{ marginLeft: 5, textAlignVertical: 'center', }}>{item.name}</Text> <Text style={ { textAlignVertical: 'center', height: 35, position: 'absolute', right:5 } }>{item.numberOfListings}</Text> </View> </TouchableHighlight> <Divider/> </View> ) }

Select a row in ListView react-native to get detail

i'm new in react-native. I saw an example in https://facebook.github.io/react-native/docs/sample-application-movies.html .
It is building a movies app that fetch movies and display them in a ListView. How can we select a row to get its detail data and display it in other view? Please help. thanks :)
Here's what i've done so far:
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, {
Component,
} from 'react';
import {
AppRegistry,
Image,
ListView,
StyleSheet,
Text,
View,
Navigator,
TouchableOpacity,
} from 'react-native';
var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
var SCREEN_WIDTH = require('Dimensions').get('window').width;
var BaseConfig = Navigator.SceneConfigs.FloatFromRight;
var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop, {
snapVelocity: 8,
edgeHitWidth: SCREEN_WIDTH,
});
var CustomSceneConfig = Object.assign({}, BaseConfig, {
springTension: 100,
springFriction: 1,
gestures: {
pop: CustomLeftToRightGesture,
}
});
var PageOne = React.createClass({
getInitialState:function(){
return{
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
}
},
componentDidMount() {
this.fetchData();
},
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.movies),
loaded: true,
});
})
.done();
},
render() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderMovie}
style={styles.listView}
/>
);
},
renderLoadingView() {
return (
<View style={styles.container}>
<Text>
Loading movies...
</Text>
</View>
);
},
renderMovie(movie) {
title1 = movie.title;
year1 = movie.year;
return (
<TouchableOpacity onPress={this._handlePressList}>
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
</TouchableOpacity>
);
},
_handlePressList(){
this.props.navigator.push({id: 2, title1, year1});
},
});
var PageTwo = React.createClass({
render(){
return(
<View style={styles.rightContainer}>
<Text style={styles.title}>{title1}</Text>
<Text style={styles.year}>{year1}</Text>
</View>
)
}
})
class SampleAppMovies extends Component{
_renderScene(route, navigator) {
if (route.id === 1) {
return <PageOne navigator={navigator} />
} else if (route.id === 2) {
return <PageTwo navigator={navigator} />
}
}
_configureScene(route) {
return CustomSceneConfig;
}
render() {
return (
<Navigator
initialRoute={{id: 1, }}
renderScene={this._renderScene}
configureScene={this._configureScene} />
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
rightContainer: {
flex: 1,
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center',
},
year: {
textAlign: 'center',
},
thumbnail: {
width: 53,
height: 81,
},
listView: {
paddingTop: 20,
backgroundColor: '#F5FCFF',
},
});
module.exports = SampleAppMovies;
In your renderRow method (in your case renderMovie), simply pass the movie in onPress prop of TouchableOpacity, something like this:
renderMovie(movie) {
title1 = movie.title;
year1 = movie.year;
return (
<TouchableOpacity onPress={() => _handlePressList(movie)}> // SEE HERE!!
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
</TouchableOpacity>
);
},
_handlePressList(movie){
this.props.navigator.push({id: 2, movie.title1, movie.year1});
},
Then you can do whatever you want with the movie.
Hope it's helpful.
renderMovie(movie) {
title1 = movie.title;
year1 = movie.year;
return (
<TouchableOpacity onPress={this._handlePressList.bind(this, movie)}
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
</TouchableOpacity>
);
},
_handlePressList(movie){
this.props.navigator.push({id: 2, movie.title1, movie.year1});
},
This will solve the problem