How to call a parent function within child in Native React - function

After hours spent googling around without finding an answer ... I'm asking for your help.
So what I want to do : Call the function named _toggleSearchBar() (which is in the parent) within the Child so when the onPress event (which is in the child) fire it changes the value 'isVisible' inside the parent.
Parent
class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {isVisible: false};
}
static navigationOptions = {
title: 'P O S T E R',
headerStyle: { backgroundColor: '#CECECE' },
headerTitleStyle: { color: 'black', fontSize: 30, fontFamily: 'HelveticaNeue-CondensedBlack'},
headerRight: <DisplayIcon src={require('./ressources/icon_search.png')} myMethod={'HERE'}/>,
headerLeft: <DisplayIcon src={require('./ressources/icon_aroundMe.png')}/>,
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<View style={styles.bck}>
<ScrollView>
<DisplayImage src={require('./ressources/logo.jpg')} />
<DisplayImage src={require('./ressources/logo1.jpeg')} />
<DisplayImage src={require('./ressources/logo2.jpg')} />
<DisplayImage src={require('./ressources/logo3.jpeg')} />
<DisplayImage src={require('./ressources/logo4.jpg')} />
<DisplayImage src={require('./ressources/logo5.jpeg')} />
<DisplayImage src={require('./ressources/bde.jpeg')} />
</ScrollView>
</View>
<Display enable={this.state.isVisible} style={styles.ViewIn}>
<View>
<TextInput style={styles.textIn}></TextInput>
</View>
</Display>
</View>
)
}
_toggleSearchBar() {
this.setState(previousState => {
return { isVisible: !this.state.isVisible };
});
}
}
Child
class DisplayIcon extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<TouchableHighlight onPress={this.myMethod} activeOpacity= {0.4} underlayColor={ 'rgb(206, 206, 206)' }>
<Image style={styles.Picture} source={this.props.src}/>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
Picture: {
marginLeft: 10,
marginRight: 10,
height: 30,
width: 30,
}
});
Bind didn't work. Nor passing the function via props ...
Thanks for your help and your time !

In the Child component you should invoke this.props.myMethod and not this.myMethod.
Example:
<TouchableHighlight onPress={this.props.myMethod} activeOpacity= {0.4} underlayColor={ 'rgb(206, 206, 206)' }>
In your Parent you should pass in a prop to the child - myMethod={this._toggleSearchBar}.
Example:
<DisplayIcon src={require('./ressources/icon_search.png')} myMethod={this._toggleSearchBar}/>
Note that you should bind _toggleSearchBar to the class.
Do it in the constructor:
constructor(props){
super(props);
this._toggleSearchBar = this._toggleSearchBar.bind(this);
}

HELP FOR COMPREHENSION
Inside the child.
This is not working (via Parent function)
<TouchableHighlight onPress={this.props.myMethod} activeOpacity= {0.4} underlayColor={ 'rgb(206, 206, 206)' } style={styles.lol}>
<Image style={styles.Picture} source={this.props.src}/>
</TouchableHighlight>
This is working (via child function)
lol() {
alert('lol');
}
render() {
return (
<TouchableHighlight onPress={this.lol} activeOpacity= {0.4} underlayColor={ 'rgb(206, 206, 206)' } style={styles.lol}>
<Image style={styles.Picture} source={this.props.src}/>
</TouchableHighlight>

Related

How to start a countdown by clicking on a touchableOpacity in react native?

How do I start a <CountDown/> when a TouchableOpacity is pressed?
I recently discovered the countdown component of react-native.
The countdown starts automatically, but I want it to start running when I click on a TouchableOpacity. How can it be done?
This is very basic example which helps you
constructor(props: Object) {
super(props);
this.state ={ timer: 3}
}
componentDidUpdate(){
if(this.state.timer === 1){
clearInterval(this.interval);
}
}
componentWillUnmount(){
clearInterval(this.interval);
}
startTimer(){
this.interval = setInterval(
() => this.setState((prevState)=> ({ timer: prevState.timer - 1 })),
1000
);
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'center', }}>
<Text> {this.state.timer} </Text>
<Button title="Start" onPress={() => this.startTimer() } />
</View>
)
}

Need to dynamically add items into a drawer menu in React Native

I need to have some items dynamically in my app's drawer after some categories get fetched from a json file (https://www.rallyssimo.it/wp-json/wp/v2/categories)
json example (I need that information)
[
{
"id": 44,
.
.
"name": "ALTRI RALLY",
.
.
},
Tis is the drawer:
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{flex:1}}>
<View style={{height:80, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}>
<Image
source={{uri: 'https://www.rallyssimo.it/wp-content/uploads/2016/08/rallyssimo-logo.png'}}
style={{ height: 60, width: 180}}
/>
</View>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppNavigator = createDrawerNavigator(
{
Home: DashboardStackNavigator,
},
{
contentComponent: CustomDrawerComponent
}
);
const AppContainer = createAppContainer(AppNavigator);
//Main class
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
How can I put the items (I'm going to get from the JSON) in the drawer?
As you have noticed, you need to create your own custom drawer to achieve this, which is done with contentComponent: CustomDrawerComponent.
Now you cannot use DrawerItems within CustomDrawerComponent since you want full control on the items listed. But you can recreate the items yourself using basic and elements.
Finally you need to fetch the API and store the data in your state in order to render the result as a list in the drawer.
Here is a basic example for :
import React, { Component } from 'react';
import { ScrollView, Text, View, Image } from 'react-native';
import { NavigationActions } from 'react-navigation';
class CustomDrawerComponent extends Component {
constructor(props) {
super(props);
this.state = { data: null };
}
async componentDidMount() {
fetch('https://www.rallyssimo.it/wp-json/wp/v2/categories')
.then(res => res.json())
.then(data => this.setState({ data }))
}
navigateToScreen(routeName, params) {
return () => { this.props.navigation.dispatch(NavigationActions.navigate({ routeName, params })) };
}
render() {
if (this.state.data === null) {
return <Text>...</Text>;
}
return (
<View style={{ flex: 1, paddingTop: 30 }}>
<View style={{height:80, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}>
<Image
source={{uri: 'https://www.rallyssimo.it/wp-content/uploads/2016/08/rallyssimo-logo.png'}}
style={{ height: 60, width: 180}}
/>
</View>
<ScrollView>
<View>
{this.state.data.map(x => (
<Text
key={x.id}
style={{ fontSize: 16, lineHeight: 30, textAlign: 'center' }}
onPress={this.navigateToScreen('page2')}
>
{x.name}
</Text>
))}
</View>
</ScrollView>
</View>
);
}
}
export default CustomDrawerComponent;
And here is a working snack.

JSON Parse Error : Unexpected Identifier "Undefined"(React Native)

I'm trying to use Async storage to store two Text Input values stored as an object and pass it to a different view where they'll be displayed on a button press.
As mentioned in other StackOverflow posts I've used JSON.parse and JSON.stringify to pass the object as JSON data, still for some reason I;m getting the error JSON Parse Error: Unexpected Identifier "Undefined"(React Native)
Add Data
class AddData extends React.Component {
constructor(props) {
super(props);
this.state = {
text1: '' ,
text2: ''
};
}
render() {
function BtnPress() {
alert('Hi')
}
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
<TextInput
style={{height: 40,width:200}}
onChangeText={(text1) => this.setState({input1: text1})}
/>
<TextInput
style={{height: 40,width:200}}
onChangeText={(text2) => this.setState({input2: text2})}
/>
<Button
onPress={() => {
AsyncStorage.setItem('user', JSON.stringify({
name:'Rohit',
email: 'rohitgird12gmail.com'
}));
this.props.navigation.navigate('Home', {});
}}
title="Submit"
/>
</View>
);
}
}
View to Display Data
class DetailsScreen extends React.Component {
displayName = async ()=> {
try {
const myArray = await AsyncStorage.getItem('user');
if (myArray !== null) {
alert(JSON.parse(myArray.name));
}
} catch (error) {
alert(error)
}
}
render() {
return (
<View style={{flex: 1, flexDirection: 'column', justifyContent:'center', alignItems: 'center'}}>
<Button
onPress={this.displayName}
title="Get Data"
/>
</View>
);
}
}
It looks like const myArray = await AsyncStorage.getItem('user'); is returning undefined while you defended yourself from null only, which is not sufficient here.
Antoher possible problem lies here : JSON.parse(myArray.name). Are you sure it's not supposed to be JSON.parse(myArray).name?

How to set this.props.key into the Firebase database reference in react native

I have retrieved the values from the other component and displayed in the TextInput for users to edit the values which are the (itemTitle: this.props.title, itemIng: this.props.ing, itemSteps: this.props.steps) and now
I'm trying to update the values back to firebase after user pressed the button in modal. But I'm having a problem to get the firebase database reference, I'm able get the {this.props._key} from another component but when I write as a .child(itemKey) it's not working and shows "Can't find variable: itemKey" Does anyone has the similar problem?
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
ScrollView,
Button,
TouchableHighlight,
Modal,
TextInput,
ImageBackground
} from 'react-native';
import {Actions}from 'react-native-router-flux';
import firebase from './firebase';
const remote = 'http://l.rgbimg.com/cache1oCOq1/users/b/ba/ba1969/600/mxc1dae.jpg';
export default class RecipeDetails extends React.Component{
constructor(props){
super(props);
this.state={
modalVisible: false,
itemTitle: this.props.title,
itemIng: this.props.ing,
itemSteps: this.props.steps,
itemKey: this.props._key.toString(),
};
this.vegeRef = this.getRef().child('Vegetarian').child(itemKey);
this.fastRef = this.getRef().child('Fast Food');
this.hpRef = this.getRef().child('Healthy');
}
setModalVisible(visible){
this.setState({modalVisible:visible});
}
getRef(){
return firebase.database().ref();
}
updateItem(){
this.setModalVisible(true);
}
render(){
return(
<View style={styles.container}>
<Modal
visible={this.state.modalVisible}
animationType={'slide'}
onRequestClose={() => {}}
>
<Text>Edit the details and Update.</Text>
<TextInput
value={this.state.itemTitle}
onChangeText ={(itemTitle) => this.setState({ itemTitle })}
/>
<TextInput
value={this.state.itemIng}
onChangeText ={(itemIng) => this.setState({itemIng})}
/>
<TextInput
value={this.state.itemSteps}
onChangeText ={(itemSteps) => this.setState({itemSteps})}
/>
<View style={styles.modalContainer}>
<View style={styles.innerContainer}>
<Button onPress={() => {
this.vegeRef.update({title:this.state.itemTitle, ing:this.state.itemIng, steps:this.state.itemSteps});
this.setModalVisible(!this.state.modalVisible)
}}
title="Save Recipe"
>
</Button>
<Button
onPress={() => this.setModalVisible(!this.state.modalVisible)}
title="Cancel"
>
</Button>
</View>
</View>
</Modal>
<ImageBackground
style={{
flex: 1,
justifyContent: 'center',
paddingVertical: 35
}}
source={{ uri: remote }}
>
<ScrollView style={styles.container2} showsVerticalScrollIndicator={false}>
<Text style={styles.heading1}>
Ingredients
</Text>
<Text style={styles.heading2}>
{this.props.ing}
{this.props._key}
</Text>
<Text style={styles.heading1}>
Steps
</Text>
<Text style={styles.heading2}>
{this.props.steps}
</Text>
</ScrollView>
</ImageBackground>
<View style={styles.action}>
<TouchableHighlight
underlayColor='#24ce84'
onPress={this.updateItem.bind(this)}
>
<Text style = {styles.actionText}>Update Recipe</Text>
</TouchableHighlight>
</View>
</View>
);
}
}
This is the Firebase JSON format
"Vegetarian" : {
"-L3RaWBQchF5rKmVtpNk" : {
"ing" : "Aasaaaa",
"steps" : "Aa",
"title" : "Eeww"
},
"-L3WdmePSwkWNN4xB51M" : {
"ing" : "This is good",
"steps" : "Nice",
"title" : "Salad"
},
You need to change the value ot itemKey to this.state.itemKey and that will not be inside constructor as your are initialising the states in constructor. Also whenever you are calling any function like you have called update to update the values. Try to use the update query of firebase inside a function and use that in onPress event of Button react element. Please check modified code.
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
ScrollView,
Button,
TouchableHighlight,
Modal,
TextInput,
ImageBackground
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import firebase from './firebase';
const remote = 'http://l.rgbimg.com/cache1oCOq1/users/b/ba/ba1969/600/mxc1dae.jpg';
export default class RecipeDetails extends React.Component {
constructor(props) {
super(props);
this.state = {
modalVisible: false,
itemTitle: this.props.title,
itemIng: this.props.ing,
itemSteps: this.props.steps,
itemKey: this.props._key.toString(),
};
// this.vegeRef = this.getRef();
this.fastRef = this.getRef().child('Fast Food');
this.hpRef = this.getRef().child('Healthy');
}
componentDidMount() {
this.getRef().child('Vegetarian').on('child_added', s => {
if (s.exists()) {
console.log(s.val()) // It will return the new updated object
console.log(s.key) // It will return the timestamp key
this.setState({
itemTitle: s.val().title,
itemIng: s.val().ing,
itemSteps: s.val().steps,
})
}
})
}
setModalVisible(visible) {
this.setState({ modalVisible: visible });
}
getVegRef = () => {
this.getRef().child('Vegetarian').child(this.state.itemKey)
}
getRef = () => {
return firebase.database().ref();
}
updateVeg = () => {
this.getVegRef().update(
{
title: this.state.itemTitle,
ing: this.state.itemIng,
steps: this.state.itemSteps
});
this.setModalVisible(!this.state.modalVisible)
}
updateItem() {
this.setModalVisible(true);
}
render() {
return (
<View style={styles.container}>
<Modal
visible={this.state.modalVisible}
animationType={'slide'}
onRequestClose={() => { }}
>
<Text>Edit the details and Update.</Text>
<TextInput
value={this.state.itemTitle}
onChangeText={(itemTitle) => this.setState({ itemTitle })}
/>
<TextInput
value={this.state.itemIng}
onChangeText={(itemIng) => this.setState({ itemIng })}
/>
<TextInput
value={this.state.itemSteps}
onChangeText={(itemSteps) => this.setState({ itemSteps })}
/>
<View style={styles.modalContainer}>
<View style={styles.innerContainer}>
<Button onPress={
this.updateVeg
}
title="Save Recipe"
>
</Button>
<Button
onPress={() => this.setModalVisible(!this.state.modalVisible)}
title="Cancel"
>
</Button>
</View>
</View>
</Modal>
<ImageBackground
style={{
flex: 1,
justifyContent: 'center',
paddingVertical: 35
}}
source={{ uri: remote }}
>
<ScrollView style={styles.container2} showsVerticalScrollIndicator={false}>
<Text style={styles.heading1}>
Ingredients
</Text>
<Text style={styles.heading2}>
{this.props.ing}
{this.props._key}
</Text>
<Text style={styles.heading1}>
Steps
</Text>
<Text style={styles.heading2}>
{this.props.steps}
</Text>
</ScrollView>
</ImageBackground>
<View style={styles.action}>
<TouchableHighlight
underlayColor='#24ce84'
onPress={this.updateItem.bind(this)}
>
<Text style={styles.actionText}>Update Recipe</Text>
</TouchableHighlight>
</View>
</View>
);
}
}

Mode option in google map using react native linking

The following function open the map in driver mode. Is there any option available to set up map mode like driver, transport etc.
startNavigation(url) {
Linking.canOpenURL(url).then(supported => {
if (supported) {
Linking.openURL(url);
} else {
console.log('Don\'t know how to open URI: ' + url);
}
});
}
Check this sample code
import React, {
Component
} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Linking,
TouchableHighlight,
} from 'react-native';
class StackOverflow extends Component {
startNavigation(url) {
Linking.canOpenURL(url).then(supported => {
if (supported) {
Linking.openURL(url);
} else {
console.log('Don\'t know how to open URI: ' + url);
}
});
}
_onPressButton(mode) {
//driving d
//walking walking
//bicycling bicycle
//transit transit
this.startNavigation("google.navigation:q=American Century Investments&mode="+mode);
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={this._onPressButton.bind(this,'d')}>
<Text>Driving</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this._onPressButton.bind(this,'walking')}>
<Text>Walking</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this._onPressButton.bind(this,'bicycle')}>
<Text>Bicycle</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this._onPressButton.bind(this,'transit')}>
<Text>Transit</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
AppRegistry.registerComponent('StackOverflow', () => StackOverflow);
Verified in Android device