React Native NavigatorIOS - javascript

I'm a newbie to ReactNative
I Crated NavigatorEX class and it renders normally the MiladView, but it's not navigating to HadiView class. what'is the problem with route or push methods.
This code written by React-Native 0.25 with ES6.
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
NavigatorIOS
} from 'react-native';
class NavigatorEX extends Component {
render() {
return (
<NavigatorIOS
style={styles.nav}
titleTextColor="#212121"
navigationBarHidden={false}
initialRoute={{
component: MiladView,
title: 'Milad',
rightButtonTitle: 'Go',
onRightButtonPress: () => {
this.props.navigator.push({
component: HadiView,
title: 'Hadi',
leftButtonTitle: 'Back',
onLeftButtonPress: () => this.props.navigator.pop(),
});
},
}}
/>
);
}
}
class HadiView extends Component {
render(){
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Hadi
</Text>
</View>
)
}
}
class MiladView extends Component {
render(){
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Milad
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#FAFAFA',
},
nav: {
flex: 1,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('NavigatorEX', () => NavigatorEX);

Try adding ref={navigator => this.navigator = navigator} to the NavigatorIOS, and then this.navigator.push vs this.props.navigator.push
<NavigatorIOS
ref={navigator => this.navigator = navigator}
style={styles.nav}
titleTextColor="#212121"
navigationBarHidden={false}
initialRoute={{
component: MiladView,
title: 'Milad',
rightButtonTitle: 'Go',
onRightButtonPress: () => {
this.refs.navigator.push({
component: HadiView,
title: 'Hadi',
leftButtonTitle: 'Back',
onLeftButtonPress: () => this.refs.navigator.pop(),
});
},
}}
/>

Related

Adding a DOM element with the press of a button in react native

I want to be able to add a <Text> element with the press of a button in react native
Is this possible to make ? and how can i do it ?
my code :
import React, { Component } from 'react'
import { StyleSheet, Text, View, Button } from 'react-native'
export default class App extends Component {
onPress = () => {
//some script to add text
}
render() {
return (
<View style = { styles.container }>
<View style = { styles.ButtonContainer }>
//i want to add text here
<Button
onPress={this.onPress}
title="Add item"
color="#FB3640"
accessibilityLabel="Add item"
containerViewStyle={{width: '100%', marginLeft: 0}}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
backgroundColor: '#fff',
alignItems: 'center',
},
text: {
marginTop: 100,
},
ButtonContainer: {
margin: 20,
width: '90%',
}
});
Thank you !
You need to define a piece of state and initialized it with false. When the user presses the button you have to switch this piece of state to true. Have a look here for more information about the local state: https://reactjs.org/docs/state-and-lifecycle.html#adding-local-state-to-a-class
Something like that should work:
import React, { Component } from 'react'
import { StyleSheet, Text, View, Button } from 'react-native'
export default class App extends Component {
state = {
displayText: false
}
onPress = () => {
this.setState({ displayText: true });
}
render() {
return (
<View style = { styles.container }>
<View style = { styles.ButtonContainer }>
{displayText && <Text>This is my text</Text>}
<Button
onPress={this.onPress}
title="Add item"
color="#FB3640"
accessibilityLabel="Add item"
containerViewStyle={{width: '100%', marginLeft: 0}}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
backgroundColor: '#fff',
alignItems: 'center',
},
text: {
marginTop: 100,
},
ButtonContainer: {
margin: 20,
width: '90%',
}
});

Can't Navigate To Custom Screen - React Navigation?

I want to navigate from Order screen To Home Screen but he doesn't work very well, every screen in the route is work, But Home screen Nope, Just back me to the Map screen, And I want Home Screen Not Map !! I already tell them to navigate to Home.
Here is structure I'm Dowing
Home -> Map -> Order, then Order -> Home
and in the Home, I have side menu Drawer check under the code.
Route.js
import React, { Component } from 'react';
import {
View,
TouchableOpacity,
} from 'react-native';
//Import required react-navigation component
import {
createDrawerNavigator,
createStackNavigator,
createAppContainer,
createSwitchNavigator
} from 'react-navigation';
//Import all the screens for Drawer/ Sidebar
import Home from "../screens/Home";
import Splash from "../screens/Splash";
import SignUp from "../screens/SignUp";
import SignIn from "../screens/SignIn";
import ForgetPassword from "../screens/ForgetPassword";
import Order from "../screens/Order";
import MapApp from "../screens/MapApp";
import Profile from "../screens/Profile";
import Icon from 'react-native-vector-icons/Ionicons';
//Navigation Drawer Structure for all screen
class NavigationDrawerStructure extends Component {
//Structure for the navigatin Drawer
toggleDrawer = () => {
//Props to open/close the drawer
this.props.navigationProps.toggleDrawer();
};
render() {
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={this.toggleDrawer.bind(this)}>
<Icon name="md-menu" size={30} color='#fff' style={{ marginLeft: 10 }} />
</TouchableOpacity>
</View>
);
}
}
// Stack Navigator for app
const AuthStackNavigator = createStackNavigator({
//All the screen from the Screen1 will be indexed here
SignUp: {
screen: SignUp,
navigationOptions: () => ({
// header: null
title: "Sign Up",
headerLeft: null,
headerTintColor: "#0496FF",
headerStyle: {
borderBottomColor: "white"
},
headerTitleStyle: {
color: "#0496FF",
textAlign: "center",
flex: 1,
elevation: 0,
fontSize: 25,
justifyContent: "center"
}
})
},
SignIn: {
screen: SignIn,
navigationOptions: {
title: "Sign In",
headerRight: <View />,
headerTintColor: "#0496FF",
headerStyle: {
borderBottomColor: "white"
},
headerTitleStyle: {
color: "#0496FF",
textAlign: "center",
flex: 1,
elevation: 0,
fontSize: 25,
justifyContent: "center"
}
}
},
ForgetPassword: {
screen: ForgetPassword,
navigationOptions: {
title: "Forget Password",
headerRight: <View />,
headerTintColor: "#0496FF",
headerStyle: {
borderBottomColor: "white"
},
headerTitleStyle: {
color: "#0496FF",
textAlign: "center",
flex: 1,
elevation: 0,
fontSize: 25,
justifyContent: "center"
}
}
},
});
//Stack Navigator for First Option of Navigation Drawer
const HomeDrawer = createStackNavigator({
Home: {
screen: Home,
navigationOptions: ({ navigation }) => ({
title: 'Home',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerRight: <View />,
headerStyle: {
backgroundColor: '#258fdb',
shadowOpacity: 0,
elevation: 0,
marginBottom: 20
},
headerTintColor: '#fff',
headerTitleStyle: {
textAlign: "center",
flex: 1,
elevation: 0,
fontSize: 25,
justifyContent: "center"
}
}),
},
MapApp: {
screen: MapApp,
navigationOptions: {
title: "Map",
headerRight: <View />,
headerLeft: <View />,
headerTintColor: "#fff",
headerStyle: {
backgroundColor: "#258fdb",
borderBottomColor: "white",
},
headerTitleStyle: {
textAlign: "center",
flex: 1,
elevation: 0,
fontSize: 25,
justifyContent: "center"
}
}
}
});
//Stack Navigator for Second Option of Navigation Drawer
const OrderDrawer = createStackNavigator({
Order: {
screen: Order,
navigationOptions: ({ navigation }) => ({
title: 'Order',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#258fdb',
},
headerTintColor: '#fff',
}),
},
});
const ProfileDrawer = createStackNavigator({
Profile: {
screen: Profile,
navigationOptions: ({ navigation }) => ({
title: 'Profile',
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#258fdb',
},
headerTintColor: '#fff',
}),
},
})
//Drawer Navigator for the Navigation Drawer / Sidebar
const DrawerNavigator = createDrawerNavigator({
Home: {
screen: HomeDrawer,
navigationOptions: {
drawerLabel: 'Home',
drawerIcon: () => (
<Icon name="ios-home" size={30} color='#0496FF' />
),
},
},
Order: {
screen: OrderDrawer,
navigationOptions: {
drawerLabel: 'Order',
drawerIcon: () => (
<Icon name="ios-list-box" size={30} color='#0496FF' />
),
},
},
Profile: {
screen: ProfileDrawer,
navigationOptions: {
drawerLabel: 'Profile',
drawerIcon: () => (
<Icon name="ios-contact" size={30} color='#0496FF' />
),
},
},
});
const Navigations = createSwitchNavigator({
Authloading: Splash,
Auth: AuthStackNavigator, // the Auth stack
App: DrawerNavigator, // the App stack
})
export default MyApp = createAppContainer(Navigations);
Order.js
import React, { Component } from 'react';
import styles from "../Style/styles";
import firebase from "react-native-firebase";
import ImagePicker from "react-native-image-picker";
import { View, Text, StyleSheet, TextInput, ScrollView, KeyboardAvoidingView, TouchableOpacity, Image } from 'react-native';
// create a component
class Order extends Component {
constructor(props) {
super(props);
this.state = {
userId: null,
nameOfProblem: '',
description: '',
imageOfPrblem: '',
timeDate: {},
providerId: this.props.navigation.dangerouslyGetParent().getParam('providerId'),
}
}
componentDidMount() {
const userId = firebase.auth().currentUser.uid;
this.setState({ userId });
}
handleOrder = () => {
const { nameOfProblem, description, userId, imageOfPrblem, providerId } = this.state;
const PushData = firebase.database().ref("request/" + providerId + "/" + userId + "/orders/");
const ref = firebase.storage().ref("users/" + userId + "/UserImageOrders/" + path);
let file = imageOfPrblem.uri;
const path = "img_" + imageOfPrblem.fileName;
if (file) {
return (
PushData.update({
nameOfProblem: nameOfProblem,
description: description,
// ...this.state.nameOfProblem,
// ...this.state.description,
imageOfPrblem: imageOfPrblem
}).then(() => {
ref.put(file).then(() => {
console.log("File uploaded..")
setTimeout(() => {
this.props.navigation.navigate("Home"); // not working and get me back to Map screen, but when i navigate to other screen it's work fine!
}, 3000);
});
})
)
}
else {
return (
PushData.push({
nameOfProblem: nameOfProblem,
description: description,
}).then(() => {
setTimeout(() => {
this.props.navigation.navigate("Home"); // Not work
}, 3000);
})
)
}
// else {
// }
}
handleImages = () => {
const options = {
title: "Select Images!",
storageOptions: {
skipBackup: true,
path: "images"
}
};
ImagePicker.showImagePicker(options, response => {
console.log("Response = ", response);
if (response.uri) {
this.setState({ imageOfPrblem: response });
}
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("ImagePicker Error: ", response.error);
} else if (response.customButton) {
console.log("User tapped custom button: ", response.customButton);
alert(response.customButton);
}
});
};
render() {
const { nameOfProblem, description, imageOfPrblem, timeDate } = this.state;
const { getParam } = this.props.navigation.dangerouslyGetParent();
const providerId = getParam('providerId');
const providerName = getParam('providerName');
return (
<ScrollView scrollEnabled={true}>
<KeyboardAvoidingView behavior="padding" keyboardVerticalOffset={70}>
<View style={[styles.container, { marginTop: 20 }]}>
<Text>Send Order To: {JSON.stringify(providerName)}, ID:{JSON.stringify(providerId)}</Text>
<TextInput
style={styles.textInput}
placeholder="Name of Problem"
value={nameOfProblem}
onChangeText={(nameOfProblem) => this.setState({ nameOfProblem })}
returnKeyType="next"
returnKeyLabel="next"
/>
<TextInput
style={[styles.textInput, {
borderRadius: 5,
borderWidth: 1,
height: 120,
fontSize: 16,
padding: 10,
marginTop: 8
}]}
placeholder="Description"
multiline={true}
numberOfLines={12}
textAlignVertical="top"
value={description}
onChangeText={(description) => this.setState({ description })}
returnKeyType="next"
returnKeyLabel="next"
/>
<TouchableOpacity onPress={this.handleImages}>
<View
style={{
backgroundColor: "#DBDBDB",
borderRadius: 100,
alignSelf: "center",
margin: 10,
paddingBottom: 2,
width: 120,
height: 120
}}
>
<Text
style={{
position: "absolute",
zIndex: 1,
fontSize: 40,
top: 67,
color: "#1567d3",
left: 99
}}
>
+
</Text>
<Image
source={{ uri: imageOfPrblem.uri }}
style={[styles.uploadAvatar, { borderRadius: 100 }]}
resizeMode="cover"
/>
</View>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, { backgroundColor: "#1567d3" }]}
onPress={this.handleOrder}
>
<Text style={{ color: "#fff", fontSize: 18 }}>Send</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</ScrollView>
);
}
}
// define your styles
//make this component available to the app
export default Order;
You have two routes with the name "Home", one in HomeDrawer and one in DrawerNavigator. Rename the one in DrawerNavigator and it should navigate to the correct "Home".
For example:
HomeDrawer: { // renamed this from Home to HomeDrawer
screen: HomeDrawer,
navigationOptions: {
drawerLabel: 'Home',
drawerIcon: () => (
<Icon name="ios-home" size={30} color='#0496FF' />
),
},
},
When exporting Home.js, export it like this (using withNavigation ).
import React, { Component } from 'react'
import { Text, View } from 'react-native'
import { withNavigation } from 'react-navigation';
class Home extends Component {
render() {
return (
<View>
<Text> Home </Text>
</View>
)
}
}
export default withNavigation(Home);

Pass data between two components in React Native

I have a component that encapsulates three components one of them is the DrawerLayoutAndroid. Now I want to pass the reference of the drawer from the drawer component to the main component and then pass it to the header component so I can trigger it from the header component.
I have no idea how to do that.
Here is the main component 'cases.js'
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import Header from '#components/header';
import BottomBar from '#components/bottom-bar';
import SideBar from '#components/drawer';
export default class Cases extends Component {
state = {
title : 'Cases'
}
change_text = () => {
this.setState({ title : 'Test' })
}
open_drawer = (ref) => {
ref.openDrawer();
}
close_drawer = (ref) => {
ref.closeDrawer();
}
render() {
return (
<SideBar style={ styles.container }>
<Header title={ this.state.title } change_text={ this.change_text } open={ this.state.side_bar } />
<View style={ styles.body }>
<Text style={ styles.text }> { this.state.name } </Text>
<TouchableOpacity onPress={ () => this.change_text() } style={ styles.button }>
<Text> Change State </Text>
</TouchableOpacity>
</View>
<BottomBar ref={ this.state.side_bar } />
</SideBar>
)
}
}
const styles = StyleSheet.create({
container : {
flex : 1,
flexDirection: 'column',
},
body : {
flex : 1,
backgroundColor: '#ccc',
justifyContent: 'center',
alignItems: 'center'
},
text : {
color : '#fff'
},
button : {
backgroundColor : '#eee',
paddingVertical: 5,
paddingHorizontal: 10
}
})
Here is my header:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native';
import DrawerLayoutAndroid from 'DrawerLayoutAndroid';
import LinearGradient from 'react-native-linear-gradient';
export default class Header extends Component {
change_text = () => {
this.props.change_text();
}
open = ()
render () {
return (
<LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={['#a4d294', '#3ac6f3']} style={ styles.header }>
<TouchableOpacity onPress={ () => this.props.change_text() }>
<Image source={ require('#media/images/add.png') } style={ styles.add_button } />
</TouchableOpacity>
<Text style={ styles.title }> { this.props.title } </Text>
<TouchableOpacity onPress={ () => this.props.open() }>
<Image source={ require('#media/images/more.png') } style={ styles.more_button } />
</TouchableOpacity>
</LinearGradient>
)
}
}
const styles = StyleSheet.create({
header : {
height: 70,
backgroundColor: '#eee',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
title : {
color : '#fff',
textAlign: 'center',
fontSize: 20,
letterSpacing: 3
},
add_button : {
width: 30,
height: 30,
marginHorizontal: 10
},
more_button : {
width: 30,
height: 30,
marginHorizontal: 10
}
})
And here is my drawer.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import DrawerLayoutAndroid from 'DrawerLayoutAndroid';
import LinearGradient from 'react-native-linear-gradient';
export default class Drawer extends Component {
render () {
const NavigationMenu = (
<LinearGradient start={{x: 0, y: 0}} end={{x: 0, y: 1}} colors={['#a4d294', '#3ac6f3']} style={{ flex: 1 }}>
<View style={{ flex : 6, justifyContent: 'center' }}>
<Text>He There</Text>
</View>
</LinearGradient>
)
return (
<DrawerLayoutAndroid
drawerWidth={250}
drawerPosition={ DrawerLayoutAndroid.positions.Right }
renderNavigationView={ () => NavigationMenu }
ref={ (drawer) => this.props.ref = drawer }
>
{ this.props.children }
</DrawerLayoutAndroid>
)
}
}
I am going to answer your question by giving a simple example.
Lets take 2 components parent and child. You want to pass some message from parent to child and get a callback from child to parent when an event occurs in child.
export default class Parent extends React.Component<any, any> {
callback (paramFromChild) => {
// implement what to do when certain event occurs in child component
}
render () {
<View>
<Child message={"some text"} callbackFromChild={this.callback}/>
</View>
}
}
Child component
Interface childProps {
message: string
callbackFromChild(paramFromChild);
}
export default class Child extends React.Component<childProps, any> {
render () {
<View>
<Button title={this.props.message} onPress={this.props.callbackFromChild("some message from child")}/>
</View>
}
}
In this way you can communicate between different components using props.

E-commerce like feature for selecting product sizes or color

I have searched the whole web to the best of my ability on how to create an interface for selecting products just like the ones implemented in most of the major e-commerce apps(amazon,taobao,shopify..).The goal is to highlight or change the styles of the selected item in the list by simultaneously removing the styles of the previously selected item. I am trying to use react-native to clone such a feature. Any references or guides on how to do this will be highly appreciated!
import React, { Component } from 'react';
import { View, Text ,StyleSheet, TouchableOpacity, } from 'react-native';
class Selections extends Component {
state={
highlighted: false,
id: null
}
// The purpose of this function is to set the state to the target index on press
indexStateHandler = (i) =>{
if(this.state.id === null){
this.setState({
id: i
})
}else{
this.setState({
id:i
})
}
console.log("index: "+i)
console.log("state: "+this.state.id)
}
//The purpose of this function is to set styles for the targeted index
highlightStateHandler = (i) =>{
if(this.state.id === i){
if(!this.state.highlighted){
this.setState({
highlighted:true
})
}
else{
this.setState({
highlighted:false
})
}
}
}
highlightHandler = (i) =>{
// console.log(i)
this.indexStateHandler(i)
this.highlightStateHandler(i)
}
render() {
return (
<View style={styles.selectionWrapper}>
<View style={styles.label}><Text style={{color: "black"}}>{this.props.label}</Text></View>
<View style={styles.listContainer}>
{this.props.options.map((options, i) => (
<TouchableOpacity onPress={()=>this.highlightHandler(i)} key={i}>
<View style={this.state.highlighted&&this.state.id == i?styles.highlighted:styles.options} > <Text style={styles.text}>{options}</Text> </View>
</TouchableOpacity>
)
)}
</View>
</View>
);
}
}
const styles= StyleSheet.create({
selectionWrapper:{
width: '100%',
height: 100,
borderWidth: 1,
borderColor: 'red',
},
label:{
flex: 1,
}
,
listContainer:{
flex: 3,
flexDirection: "row",
justifyContent: "space-around",
alignItems: 'center',
// backgroundColor: "#7fffd4"
},
options:{
borderRadius: 10,
padding: 5,
borderWidth: 1,
borderColor: "#d0b783",
// backgroundColor: ""
},
text:{
color: 'black',
textAlign: 'center'
},
highlighted:{
borderRadius: 10,
padding: 5,
borderWidth: 1,
// borderColor: "#d0b783",
backgroundColor: "#d0b783"
}
})
export default Selections
.....
.....
.....
<TouchableOpacity
style={[styles.buttonStyle,{
backgroundColor : item.id === this.state.selectedItem.id ? "red" : "blue"
}]}
>
{
...
...
}
</TouchableOpacity>
.....
.....
.....
Have a look on TouchableOpacity and TouchableHighlight and try to run examples to see how they work. Also you can combine them to changing visual changes by changing styles.
import React, { Component } from 'react' import { AppRegistry, StyleSheet, TouchableOpacity, Text, View, } from 'react-native'
export default class App extends React.Component { constructor(props) {
super(props)
this.state = {
itemEn1: true,
itemEn2: false,
itemEn3: false,
} }
onPress1 = () => {
this.setState({
itemEn1: true,
itemEn2: false,
itemEn3: false,
}) }
onPress2 = () => {
this.setState({
itemEn1: false,
itemEn2: true,
itemEn3: false,
}) }
onPress3 = () => {
this.setState({
itemEn1: false,
itemEn2: false,
itemEn3: true,
}) }
render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={this.state.itemEn1 ? styles.buttonEnabled : styles.buttonDisabled}
onPress={this.onPress1}>
<Text> Item 1 </Text>
</TouchableOpacity>
<TouchableOpacity
style={this.state.itemEn2 ? styles.buttonEnabled : styles.buttonDisabled}
onPress={this.onPress2}>
<Text> Item 2 </Text>
</TouchableOpacity>
<TouchableOpacity
style={this.state.itemEn3 ? styles.buttonEnabled : styles.buttonDisabled}
onPress={this.onPress3}>
<Text> Item 3 </Text>
</TouchableOpacity>
</View>
) } }
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 10
},
buttonDisabled: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
marginTop: 20
},
buttonEnabled: {
alignItems: 'center',
backgroundColor: 'green',
padding: 10,
marginTop: 20
},
countContainer: {
alignItems: 'center',
padding: 10
},
})
this is by map function:
export default class DataCollector extends React.Component {
constructor(props) {
super(props);
this.SendBack = this.SendBack.bind(this);
}
SendBack(info) {
console.log("Key is :", info);
this.props.callback(info);
}
render() {
let testData = this.props.data.map(function (articleData, index) {
return (
<View key={index}>
<TouchableOpacity
activeOpacity={0.6}
key={index}
onPress={() => this.callBack([articleData.id, articleData.name])}>
</TouchableOpacity>
</View>
)
}, this);
return (
<View>
{testData}
</View>
);
}
}
so now you have access to the clicked item and can use it for enable/disable etc..

React Native and Refs - Why does this function not return my content?

I have the following code in react native:
'use strict'
import React, { Component } from 'react';
import { AppRegistry, Animated, Dimensions, Easing, Image, Text, View, StyleSheet, TouchableOpacity, ScrollView } from 'react-native';
const categoryTwoLinks = [
{ label: 'Subcategory1' },
{ label: 'Subcategory2' },
{ label: 'Subcategory3' },
{ label: 'Subcategory4' },
{ label: 'Subcategory5' },
{ label: 'Subcategory6' },
]
const categoryTouts = [
{ image: require('./assets/images/image01.jpg'), title: 'Category1' },
{ image: require('./assets/images/image02.jpg'), title: 'Category2', links: categoryTwoLinks },
{ image: require('./assets/images/image03.jpg'), title: 'Category3' },
]
class Tout extends Component {
render() {
console.log('tout')
return (
<Image
source={this.props.image}
ratioGrow
alignItems='center'
style={{ alignItems: 'center', justifyContent: 'center' }}
>
<Text
style={{ color: 'white', fontSize: 24, backgroundColor: 'transparent', fontWeight: 'bold' }}
>
{this.props.title}
</Text>
</Image>
)
}
}
export default class scrollAccordion extends Component {
handleScroll = ({ nativeEvent: { contentOffset } }: Object) => {
const scrollY = contentOffset.y
this.scrollOffsetValue.setValue(scrollY)
}
setScrollRef = node => {
console.log('set scroll ref')
if (node) {
this.scrollRef = node
}
}
renderCategoryTouts = () => {
console.log('render category tout')
categoryTouts.map((tout, index) => {
return (
<Tout
key={tout.title}
{...tout}
scrollViewRef={this.state.scrollRef}
scrollOffset={this.scrollOffsetValue}
/>
)
})
}
render() {
console.log('render')
let categoryTouts = this.scrollRef ? this.renderCategoryTouts() : null
return (
<View style={styles.container}>
<ScrollView
scrollEventThrottle={1}
ref={this.setScrollRef}
onScroll={this.handleScroll}
>
<View>
{categoryTouts}
</View>
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 40,
backgroundColor: 'white',
},
toutText: {
color: 'white', backgroundColor: 'transparent', fontWeight: 'bold', fontSize: 24
}
});
AppRegistry.registerComponent('scrollAccordion', () => scrollAccordion);
which is not returning any content from the renderCategoryTouts function.
I know that initially, this.scrollRef is undefined, so the main render function will return {null} for the {categoryTouts} variable. But after the scrollRef is set, I need it to return the results of renderCategoryTouts. How do I get this to work?
In renderCategoryTouts function of yours you have a variable categoryTouts variabke. You have never declared a variable like that in this function so I assume it is a global variable.
renderCategoryTouts = () => {
categoryTouts.map((tout, index) => {
return (
<Tout
key={tout.title}
{...tout}
scrollViewRef={this.state.scrollRef}
scrollOffset={this.scrollOffsetValue}
/>
)
})
}
And in this function you're using this.state.scrollRef, this.scrollOffsetValue so you need to bind this function.(I suggest you do that in the constructor of class)
this.renderCategoryTouts = this.renderCategoryTouts.bind(this)
also in case this does not work full code would be very helpful

Categories