Trouble getting function from different component - javascript

I'm new to react native. I am trying to get a 'Key' from a different component. I mean I am trying to call a function from a different component, as a parent component. But, I'm totally jumbled with all these reference calls and all. Please suggest to me how to call a function from a different component.
// AddScreen.js
import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from '../components/styles';
import { createStackNavigator } from 'react-navigation';
import History from '../components/History';
export default class AddScreen extends Component {
constructor(props) {
super(props);
this.state = {
myKey: '',
}
}
getKey = async () => {
try {
const value = await AsyncStorage.getItem('#MySuperStore:key');
this.setState({ myKey: value });
} catch (error) {
console.log("Error retrieving data" + error);
}
}
async saveKey(value) {
try {
await AsyncStorage.setItem('#MySuperStore:key', value);
} catch (error) {
console.log("Error saving data" + error);
}
}
componentDidMount() {
this.getKey();
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.MainContainer}>
<View style={styles.Date_input}>
<TextInput
placeholder="Add input"
value={this.state.myKey}
onChangeText={(value) => this.saveKey(value)}
/>
</View>
<View style={styles.getKeytext}>
<Text >
Stored key is = {this.state.myKey}
</Text>
</View>
<View style={styles.Historybutton}>
<Button
onPress={() => navigate('History')}
title="Press Me"
/>
</View>
</View>
)
}
}
//History.js
import React, { Component } from 'react';
import AddScreen from '../components/AddScreen';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
Button,
View,
AsyncStorage
} from 'react-native';
export default class History extends Component {
constructor(props) {
super(props);
this.state = {
myKey: ''
}
}
render() {call async function synchronously
return (
<View style={styles.container}>
<Button
style={styles.formButton}
onPress={this.onClick}
title="Get Key"
color="#2196f3"
accessibilityLabel="Get Key"
/>
<Text >
Stored key is = {this.state.mykey}
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
padding: 30,
flex: 1,
backgroundColor: '#F5FCFF',
},
});
I just want to call the getKey function from the History component to get the myKey value on the History component's screen.
Please suggest to me, by taking my components as an example.

You just simply need to pass the key via navigation parameters.
<Button
onPress={() => navigate('History', { key: this.state.myKey })}
title="Press Me"
/>
and in your history component you can do
render() {
const key = this.props.navigation.getParam('key');
return (
// other code
)
}
You can read more about passing parameters here. https://reactnavigation.org/docs/en/params.html

Related

Render a new value into TextInput React Native

I've got a react native form with a button that should autofill some of the field based on some user's information. The point is that even if I update the state variable related to a TextInput, the TextInput does not display such data. Here's a short snippet for the sake of simplicity
export default class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null
}
}
autocompile = () => {
this.setState({"value": "new value"})
}
render() {
return (
<View>
<TouchableOpacity
onPress={() => {
this.autocompile
}}>
<Text>Autocompile</Text>
</TouchableOpacity>
<TextInput
onChangeText={(value) => this.setState({'value': value})}
value={this.state.value}
/>
</View>
)
}
}
}
Following this example, if I clicked "Autocompile", the TextInput below wouldn't show the new value, even though the state variable would be updated. My question is, how can I update a TextInput displayed value from the external without typing in?
Class Component Solution
import React from 'react';
import { Text, View, TextInput, TouchableOpacity } from 'react-native';
export default class Component extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
this.autocompile = this.autocompile.bind(this);
}
autocompile() {
this.setState({ value: 'new value' });
}
render() {
return (
<View>
<TouchableOpacity onPress={this.autocompile}>
<Text>Autocompile</Text>
</TouchableOpacity>
<TextInput
onChangeText={(value) => this.setState({ value: value })}
value={this.state.value}
/>
</View>
);
}
}
Function Component Solution
import React, { useState } from 'react';
import { View, TouchableOpacity, Text, TextInput } from 'react-native';
const App = () => {
const [value, setValue] = useState('');
const autocompile = () => setValue('new value');
return (
<View>
<TouchableOpacity onPress={() => autocompile()}>
<Text>Autocompile</Text>
</TouchableOpacity>
<TextInput onChangeText={(value) => setValue(value)} value={value} />
</View>
);
};
export default App;
You need to change this
autocompile = () => {
this.setState({"value": "new value"})
}
to
autocompile = () => {
this.setState({ value: 'new value' })
}
and this one also
onChangeText={(value) => this.setState({'value': value})}
to
onChangeText={(value) => this.setState({ value })}

Getting value from user with textInput and assigning to variable (React-Native)

Here I want to assign the data from textInput to variable a. How can I do it?
(That is, when the user enters data in textInput, I want to assign it to variable a.)
import React, { Component } from 'react'
import { Text, View, TextInput} from 'react-native'
export default class deneme1 extends Component {
constructor(props) {
super(props);
this.state = {
a:"",
};
}
render() {
return (
<View>
<View style={styles.textinput}>
<TextInput
placeholderTextColor='white'
style={styles.textinputtext}
/>
</View>
</View>
)
}
}
You can try this one
<TextInput
placeholder={"A Variable"}
onChangeText={(text) => this.setState({a: text}) }
value={this.state.a}
/>

TypeError: null is not an object (evaluating ''this.state.torchon')

I don't know what am doing wrong in the code below...I want to toggle flash light on/off during camera capturing, but my code is not working, I tried binding the state in different ways but is still not working for me...Below is my code. Please I need help on how to get this working.
import React, { Component } from 'react';
import { View, StyleSheet, Text, TouchableOpacity } from 'react-native';
import { RNCamera } from 'react-native-camera';
import RNFetchBlob from 'rn-fetch-blob';
import Icon from 'react-native-vector-icons/Ionicons';
class cameraComponent extends Component {
toggleTorch()
{
let tstate = this.state.torchon;
if (tstate == RNCamera.Constants.FlashMode.off){
tstate = RNCamera.Constants.FlashMode.torch;
} else {
tstate = RNCamera.Constants.FlashMode.off;
}
this.setState({torchon:tstate})
}
takePicture = async () => {
if(this.camera) {
const options = { quality: 0.5, base64: true };
const data = await this.camera.takePictureAsync(options);
console.log(data.base64)
const path = `${RNFetchBlob.fs.dirs.CacheDir}/test.png`;
console.log('path', path)
try {
RNFetchBlob.fs.writeFile(path, data.base64, 'base64')
}
catch(error) {
console.log(error.message);
}
}
};
render() {
return (
<View style={styles.container}>
<RNCamera
ref = {ref=>{
this.camera=ref;
}}
style={styles.preview}
flashMode={this.state.torchon}
// type = {RNCamera.Constants.Type.back}
>
</RNCamera>
<View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center' }}>
<TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.captureBtn} />
</View>
<TouchableOpacity style={styles.toggleTorch} onPress={this.toggleTorch.bind(this)}>
{ this.state.torchon == RNCamera.Constants.FlashMode.off? (
<Image style={styles.iconbutton} source={require('../images/flashOff.png')} />
) : (
<Image style={styles.iconbutton} source={require('../images/flashOn.png')} />
)
}
</TouchableOpacity>
</View>
);
};
}
export default cameraComponent;
You have not initialized the state anywhere and when you access this.state.torchon it throws the error because this.state is null.
You have to initialize the state.
class cameraComponent extends Component {
this.state={ torchon:RNCamera.Constants.FlashMode.off };
toggleTorch=()=>
{
let tstate = this.state.torchon;
if (tstate == RNCamera.Constants.FlashMode.off){
tstate = RNCamera.Constants.FlashMode.torch;
} else {
tstate = RNCamera.Constants.FlashMode.off;
}
this.setState({torchon:tstate})
}
You can also initialize the state inside the constructor as well.

How to use item.key in other component instead of alert

FlatList Component working complete if i click Android it show in Android in aler but i have to pass that bind value into Subscribe component instead of alert.
should i have to pass data into state and for use it as a props in other component ?
import React, { Component } from 'react';
import { AppRegistry, FlatList, StyleSheet, Text, View,Alert } from 'react-native';
export default class FlatList extends Component {
constructor(props) {
super(props);
this.updateKey = this.updateKey.bind(this);
this.state = {};
}
updateKey(keyData) {
this.setState({ keyData: keyData });
}
getListViewItem = (item) => {
Alert.alert(item.key);
}
render() {
return (
<View style={styles.container}>
<FlatList
data={[
{key: 'Android'},{key: 'iOS'}, {key: 'Java'},{key: 'Swift'},
{key: 'Php'},{key: 'Hadoop'},{key: 'Sap'},
]}
renderItem={({item}) =>
<Text style={styles.item}
onPress={this.getListViewItem.bind(this, item)}>{item.key}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
})
AppRegistry.registerComponent('flatList', () => FlatList);
import React, { Component } from 'react'
import { View, Item } from 'react-native';
export default class Subscribe extends Component {
render() {
return (
<View>
<Text>{item.key}</Text>
</View>
)
}
}
Yes, if you want to pass it as prop to a child component you can set it inside your state and pass it to the child component you are talking about.
To accomplish this you just have to change your Alert to: this.setState( { selectedValue: item } )
Then your child would look something like:
<Child item = {this.state.selectedValue} />
And you will be able to access it in your child simply doing:
this.props.item

How To Get Props in another Screen in react navigation?

I have an issue with react-navigation in passing the props to another screen,
I need to pass some props to Detail screen when the user presses one of the List Places I need to push screen with some details about the place like a Name of place and Image of place,
Errors :
this is my Code
Reducer
import { ADD_PLACE, DELETE_PLACE } from "../actions/actionTypes";
const initialState = {
places: []
};
import placeImage from "../../assets/img.jpg";
const reducer = (state = initialState, action) => {
switch (action.type) {
case ADD_PLACE:
return {
...state,
places: state.places.concat({
key: Math.random(),
name: action.placeName,
// image: placeImage,
image: {
uri:
"https://images.unsplash.com/photo-1530009078773-9bf8a2f270c6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
}
})
};
case DELETE_PLACE:
return {
...state,
places: state.places.filter(place => {
return place.key !== state.selectedPlace.key;
})
};
default:
return state;
}
};
export default reducer;
Place List Component
import React from "react";
import { FlatList, StyleSheet, ScrollView } from "react-native";
import ListItem from "../ListItem/ListItem";
const PlaceList = props => {
return (
<FlatList
style={styles.listContainer}
data={props.places}
renderItem={info => (
<ListItem
placeName={info.item.name}
placeImage={info.item.image}
onItemPressed={() => props.onItemSelected(info.item.key)}
/>
)}
keyExtractor={index => String(index)}
/>
);
};
export default PlaceList;
Find Place Screen
import React, { Component } from "react";
import { View, Text } from "react-native";
import { connect } from "react-redux";
import { StackActions } from "react-navigation";
import PlaceList from "../../Components/PlaceList/PlaceList";
class FindPlaceScreen extends Component {
constructor() {
super();
}
itemSelectedHandler = key => {
const selPlace = this.props.places.find(place => {
return place.key === key;
});
this.props.navigation.push("PlaceDetail", {
selectedPlace: selPlace,
name: selPlace.name,
image: selPlace.image
});
};
render() {
return (
<View>
<PlaceList
places={this.props.places}
onItemSelected={this.itemSelectedHandler}
/>
</View>
);
}
}
const mapStateToProps = state => {
return {
places: state.places.places
};
};
export default connect(mapStateToProps)(FindPlaceScreen);
Place Details Screen
import React, { Component } from "react";
import { View, Text, Image, TouchableOpacity, StyleSheet } from "react-native";
import Icon from "react-native-vector-icons/Ionicons";
class PlaceDetail extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.modalContainer}>
<View>
<Image
source={this.props.navigation.state.params.image}
style={styles.placeImage}
/>
<Text style={styles.placeName}>
{this.props.navigation.state.params.namePlace}
</Text>
</View>
<View>
<TouchableOpacity onPress={props.onItemDeleted}>
<View style={styles.deleteButton}>
<Icon size={30} name="ios-trash" color="red" />
</View>
</TouchableOpacity>
<TouchableOpacity onPress={props.onModalClosed}>
<View style={styles.deleteButton}>
<Icon size={30} name="ios-close" color="red" />
</View>
</TouchableOpacity>
</View>
</View>
);
}
}
export default PlaceDetail;
You need to use react-native-navigation v2 for the find place screen
itemSelectedHandler = key => {
const selPlace = this.props.places.find(place => {
return place.key === key;
});
Navigation.push(this.props.componentId, {
component: {
name: 'PlaceDetail',
options: {
topBar: {
title: {
text: selPlace.name
}
}
},
passProps: {
selectedPlace: selPlace
}
}
});
};
make sure you import { Navigation } from "react-native-navigation";
Your PlaceDetail has some error
<TouchableOpacity onPress={props.onItemDeleted}>
<TouchableOpacity onPress={props.onModalClosed}>
Change props to this.props
<TouchableOpacity onPress={this.props.onItemDeleted}>
<TouchableOpacity onPress={this.props.onModalClosed}>
But I don't see onItemDeleted and onModalClosed anywhere, don't forget to pass those to PlaceDetail via props as well :)

Categories