Reputation: 133
I am wondering how I can get data from components when button is clicked in React Native and pass it to other component. Here is my code:
This is my input component:
ZipInput.js
import React from 'react';
import { TextInput } from 'react-native';
import styles from './../assets/style';
export default class ZipInput extends React.Component {
constructor(props) {
super(props);
this.state = '';
}
render() {
return (
<TextInput
style={styles.input}
onChangeText={(text) => this.setState({text})}
keyboardType={'numeric'}
placeholder = {'Enter Zip Code'}
/>
);
}
}
This is my button:
GoButton.js
import React from 'react';
import { Button, View } from 'react-native';
import styles from './../assets/style';
import {StackNavigator} from 'react-navigation';
export default class GoButton extends React.Component {
_handlePress(event) {
alert('Pressed!');
}
render() {
const {navigate} = this.props.navigateProp
return (
<View style={styles.buttonContainer}>
<Button
onPress={() =>
navigate('ZipResultScreen')
}
title="GO"
accessibilityLabel="Find Insurance Quotes"
color='#fff'
/>
</View>
);
}
}
I created the components serparetely and import them in Homescreen.js. From there I will pass the data to other component.
Here is my Homescreen.js:
import React from 'react';
import { StyleSheet, Text, View, ImageBackground } from 'react-native';
import styles from '../assets/style'
import Header from '../components/header';
import ZipInput from '../components/zipinput';
import InsuranceType from '../components/insurancetype';
import GoButton from '../components/gobutton';
import {StackNavigator} from 'react-navigation';
export default class HomeScreen extends React.Component {
render() {
const navigate = this.props.navigation;
return (
<View style={styles.container}>
<Header />
<ImageBackground
style={styles.imgbg}
source={{ uri: 'https://www.expertinsurancereviews.com/wp-content/uploads/2017/03/background-hp-1.jpg' }}
>
<View style={styles.intro}>
<Text style={styles.title}>Compare Insurance Rates</Text>
<ZipInput />
<InsuranceType style={styles.select} />
<GoButton navigateProp = {navigate} />
</View>
</ImageBackground>
</View>
);
}
}
Upvotes: 4
Views: 20062
Reputation: 133
Here is what I found from React Navigation Documentation. It is so easy.
https://reactnavigation.org/docs/params.html
Upvotes: 1
Reputation: 4232
You need to pass your data while navigating to another screen.
Consider following example.
<Button onPress={() => navigation.navigate('ScreenName', { data: { title: 'Hello World'} })}>
export default class Screen extends React.Component {
render () {
const { title } = this.props.navigation.state.params.data
return (
<View>
<Text>{title}</Text>
</View>
)
}
}
Upvotes: 1