Convert React Native functional components to class components - react-native

I'm new to React Native and after following some tutorials I hacked this together but now I want to load some gifs right when the app starts - not after the button click.
Did some research and it looks like it's not possible with functional components and I need to switch to class components to use lifecycle functions like:
componentWillMount(){
this.setState({data : inputObject});
}
All the examples I've read so far don't have functions in their components and I can't figure out what to do with them. So if it is possible to call a function when the app starts using this as is please let me know how, if not, how do I convert this code to class component style? Thanks!
import React, {useState} from 'react';
import {
Dimensions,
StyleSheet,
SafeAreaView,
View,
Image,
FlatList,
} from 'react-native';
import SearchInput from './SearchInput';
export default function App() {
const [allGifResults, setAllGifResults] = useState([]);
function addSearchResultsHandler(searchTerm) {
console.log(searchTerm);
setAllGifResults([]);
fetchResults(searchTerm);
}
function allGifResultsHandler(url) {
setAllGifResults(currentGifs => [...currentGifs, {id: url, value: url}]);
}
function fetchResults(searchTerm) {
fetch(
'http://api.giphy.com/v1/gifs/search?q=' +
searchTerm +
'&api_key=MKSpDwx7kTCbRp23VtVsP4d0EvfwIgSg&limit=50',
)
.then(response => response.json())
.then(responseJson => {
for (let item of responseJson.data) {
allGifResultsHandler(item.images.fixed_height.url);
console.log(item.images.fixed_height.url);
}
})
.catch(error => {
console.error(error);
});
}
return (
<SafeAreaView style={styles.container}>
<View style={styles.screen}>
<SearchInput onSearchButtonPressed={addSearchResultsHandler} />
</View>
<FlatList
keyExtractor={(item, index) => item.id}
data={allGifResults}
numColumns={2}
renderItem={itemData => (
<Image
source={itemData.item.value ? {uri: itemData.item.value} : null}
style={styles.images}
/>
)}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
screen: {
margin: 10,
},
images: {
width: Dimensions.get('window').width / 2 - 20,
height: Dimensions.get('window').width / 2 - 20,
margin: 10,
},
});
import React, {useState} from 'react';
import {
View,
TextInput,
TouchableOpacity,
Text,
StyleSheet,
} from 'react-native';
function SearchInput(props) {
const [searchTerm, setSearchTerm] = useState('');
function inputHandler(enteredText) {
setSearchTerm(enteredText);
}
return (
<View style={styles.inputContainer}>
<TextInput
placeholder="Search Term"
style={styles.input}
onChangeText={inputHandler}
value={searchTerm}
/>
<TouchableOpacity
style={styles.searchButton}
onPress={props.onSearchButtonPressed.bind(this, searchTerm)}>
<Text style={styles.searchButtonText}>Search</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
inputContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
marginBottom: 20,
},
input: {
width: '70%',
borderColor: 'black',
borderWidth: 1,
fontSize: 16,
},
searchButton: {
height: 50,
width: 100,
backgroundColor: 'lightblue',
marginLeft: 10,
},
searchButtonText: {
height: 50,
fontSize: 18,
textAlign: 'center',
textAlignVertical: 'center',
},
});
export default SearchInput;

import React, {useState} from 'react';
import {
Dimensions,
StyleSheet,
SafeAreaView,
View,
Image,
FlatList,
} from 'react-native';
import SearchInput from './SearchInput';
const [allGifResults, setAllGifResults] = useState([]);
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
};
this.addSearchResultsHandler = this.addSearchResultsHandler.bind(this);
this.allGifResultsHandler = this.allGifResultsHandler.bind(this);
this.fetchResults = this.fetchResults.bind(this);
}
addSearchResultsHandler(searchTerm) {
console.log(searchTerm);
setAllGifResults([]);
fetchResults(searchTerm);
}
allGifResultsHandler(url) {
setAllGifResults(currentGifs => [...currentGifs, {id: url, value: url}]);
}
fetchResults(searchTerm) {
fetch(
'http://api.giphy.com/v1/gifs/search?q=' +
searchTerm +
'&api_key=MKSpDwx7kTCbRp23VtVsP4d0EvfwIgSg&limit=50',
)
.then(response => response.json())
.then(responseJson => {
for (let item of responseJson.data) {
allGifResultsHandler(item.images.fixed_height.url);
console.log(item.images.fixed_height.url);
}
})
.catch(error => {
console.error(error);
});
}
render(){
return (
<SafeAreaView style={styles.container}>
<View style={styles.screen}>
<SearchInput onSearchButtonPressed={(data)=> this.addSearchResultsHandler(data)} />
</View>
<FlatList
keyExtractor={(item, index) => item.id}
data={allGifResults}
numColumns={2}
renderItem={itemData => (
<Image
source={itemData.item.value ? {uri: itemData.item.value} : null}
style={styles.images}
/>
)}
/>
</SafeAreaView>
);
}
}
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
screen: {
margin: 10,
},
images: {
width: Dimensions.get('window').width / 2 - 20,
height: Dimensions.get('window').width / 2 - 20,
margin: 10,
},
});
import React, {useState} from 'react';
import {
View,
TextInput,
TouchableOpacity,
Text,
StyleSheet,
} from 'react-native';
const [searchTerm, setSearchTerm] = useState('');
class SearchInput extends React.Component {
constructor(props) {
super(props);
this.state = {
};
this.inputHandler = this.inputHandler.bind(this);
}
inputHandler(enteredText) {
setSearchTerm(enteredText);
}
render(){
return (
<View style={styles.inputContainer}>
<TextInput
placeholder="Search Term"
style={styles.input}
onChangeText={inputHandler}
value={searchTerm}
/>
<TouchableOpacity
style={styles.searchButton}
onPress={props.onSearchButtonPressed.bind(this, searchTerm)}>
<Text style={styles.searchButtonText}>Search</Text>
</TouchableOpacity>
</View>
);
}
}
export default SearchInput;
const styles = StyleSheet.create({
inputContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
marginBottom: 20,
},
input: {
width: '70%',
borderColor: 'black',
borderWidth: 1,
fontSize: 16,
},
searchButton: {
height: 50,
width: 100,
backgroundColor: 'lightblue',
marginLeft: 10,
},
searchButtonText: {
height: 50,
fontSize: 18,
textAlign: 'center',
textAlignVertical: 'center',
},
});
export default SearchInput;

Related

Unable to Pass the data to API using react-native-element-dropdown

How to pass the data to API?
//Parent Componet - in updateval function, i m trying get the selected values from dropdown but i am not getting to know how to get that.
import ElementDropdown from '../Components/ElementDropdown';
class ScanScreen extends Component {
constructor(props) {
super(props);
}
updatedVal=(item,value)=>{
console.log("hgfgf",item,value);
}
render() {
return (
<ElementDropdown text={'Country'} label={['Germany','India']} updatedVal={this.updatedVal}/>
<ElementDropdown text={'Store'} label={['Dusseldolf','Bangalore']} updatedVal={this.updatedVal}/>
)
}
}
export default ScanScreen;
//Child component - I m trying to send selected values from dropdown list to parent in updatedval.
import React, { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Dropdown } from 'react-native-element-dropdown';
import BPText from './BPText';
import ThemeColors from '../themes/bp-themes/variables/themeColors';
const ElementDropdown = (props) => {
const { text, label,updatedVal } = props;
const [value, setValue] = useState(null);
const [isFocus, setIsFocus] = useState(false);
const data = [
{ label: label[0], value: "id1" },
{ label: label[1], value: "id2" },
];
return (
<View style={styles.container}>
<View style={styles.textContainer}>
<BPText type="Light" style={{ color: ThemeColors.themeColorYellow }}>
{text}
</BPText>
</View>
<View style={styles.dropContainer}>
<Dropdown
style={[styles.dropdown, isFocus && { borderColor: 'blue' }]}
selectedTextStyle={styles.selectedTextStyle}
iconStyle={styles.iconStyle}
placeholderStyle={styles.placeholderStyle}
data={data}
maxHeight={300}
labelField="label"
valueField="value"
item
placeholder={label[0]}
value={value}
onFocus={() => setIsFocus(true)}
onBlur={() => setIsFocus(false)}
onChange={item => {
setValue(item.value);
setIsFocus(false);
//setIsDefalut(false);
updatedVal(item,label[0],label[1]);
}}
/>
</View>
</View>
);
};
export default ElementDropdown;
const styles = StyleSheet.create({
container: {
borderBottomWidth: 0.5,
borderBottomColor: 'white',
flexDirection: 'row',
marginLeft: 40,
marginRight: 40,
marginTop: 10,
justifyContent: 'center',
alignItems: 'center',
},
textContainer:{
flex:1
},
dropContainer: {
flex: 2,
},
dropdown: {},
icon: {
marginRight: 5,
},
selectedTextStyle: {
color: 'white',
},
iconStyle: {
width: 20,
height: 20,
tintColor: 'white'
},
placeholderStyle:{
color:'white'
}
});

OnPress() using TouchableOpacity is not working in react-native application

When I click the RoundedButton the TouchableOpacity works i.e the opacity of the button reduces but the onPress function doesn't work, the data being passed to the onPress function is correct(as given in the code below). Also, when I tried to console.log("something") inside the onPress function, it doesn't get printed in the console of my terminal.
Here I have the code with function component.
Focus.js file
import React, { useState } from "react";
import { Text, View, StyleSheet } from "react-native";
import { TextInput } from "react-native-paper";
import { RoundedButton } from "../../component/RoundedButton";
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState();
return (
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.title}>What would you like to focus on?</Text>
<View style={styles.inputContainer}>
<TextInput
style={{ flex: 1, marginRight: 20 }}
onSubmitEditing={({ nativeEvent }) => {
setTmpItem(nativeEvent.text);
console.log("tmpItem value set " + tmpItem);
}}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
console.log("value passed!");
addSubject(tmpItem);
}}
/>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
titleContainer: {
flex: 0.5,
padding: 10,
justifyContent: "center",
},
title: {
color: "white",
fontWeight: "bold",
fontSize: 21,
},
inputContainer: {
paddingTop: 10,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
},
});
RoundedButton.js File
import React from "react";
import { TouchableOpacity, Text, StyleSheet } from "react-native";
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
...props
}) => {
return (
<TouchableOpacity style={[styles(size).radius, style]}>
<Text style={[styles.text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
);
};
const styles = (size) =>
StyleSheet.create({
radius: {
borderRadius: size / 2,
width: size,
height: size,
alignItems: "center",
justifyContent: "center",
borderColor: "white",
borderWidth: 2,
},
text: {
color: "white",
fontSize: size / 3,
},
});
App.js file
import React, { useState } from "react";
import { Text, View, StyleSheet } from "react-native";
import { Focus } from "./src/features/focus/Focus";
export default function App() {
const [focusSubject, setFocusSubject] = useState(null);
return (
<View style={styles.container}>
{focusSubject ? (
<Text style={{ flex: 1, color: "white", fontSize: 30 }}>
Here is where I am going to build a timer
</Text>
) : (
<Focus addSubject={setFocusSubject} />
)}
<Text style={{ flex: 1, color: "white", fontSize: 30 }}>
{focusSubject}
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 50,
backgroundColor: "#252250",
},
});
you need to extract your onPress props in RoundButton.js and pass to your TouchableOpacity
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
onPress,//<===this
...props
}) => {
return (
<TouchableOpacity onPress={onPress} style={[styles(size).radius, style]}>
<Text style={[styles.text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
);
};
it's seem that you forget to pass onPress function to TouchOpacity
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
onPress,
...props
}) => {
return (
<TouchableOpacity onPress={onPress} style={[styles(size).radius, style]}>
<Text style={[styles.text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
);
};
Now It's Working
Focus.js file
import React, { useState } from "react";
import { Text, View, StyleSheet } from "react-native";
import { TextInput } from "react-native-paper";
import { RoundedButton } from "../../component/RoundedButton";
export const Focus = ({ addSubject }) => {
const [tmpItem, setTmpItem] = useState();
return (
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.title}>What would you like to focus on?</Text>
<View style={styles.inputContainer}>
<TextInput
style={{ flex: 1, marginRight: 20 }}
onSubmitEditing={({ nativeEvent }) => {
setTmpItem(nativeEvent.text);
console.log("tmpItem value set " + tmpItem);
}}
/>
<RoundedButton
size={50}
title="+"
onPress={() => {
console.log("value passed!");
addSubject(tmpItem);
}}
/>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
titleContainer: {
flex: 0.5,
padding: 10,
justifyContent: "center",
},
title: {
color: "white",
fontWeight: "bold",
fontSize: 21,
},
inputContainer: {
paddingTop: 10,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
},
});
RoundedButton.js File
import React from "react";
import { TouchableOpacity, Text, StyleSheet } from "react-native";
export const RoundedButton = ({
style = {},
textStyle = {},
size = 125,
onPress,
...props
}) => {
return (
<TouchableOpacity onPress={onPress} style={[styles(size).radius, style]}>
<Text style={[styles.text, textStyle]}>{props.title}</Text>
</TouchableOpacity>
);
};
const styles = (size) =>
StyleSheet.create({
radius: {
borderRadius: size / 2,
width: size,
height: size,
alignItems: "center",
justifyContent: "center",
borderColor: "white",
borderWidth: 2,
},
text: {
color: "white",
fontSize: size / 3,
},
});
App.js file
import React, { useState } from "react";
import { Text, View, StyleSheet } from "react-native";
import { Focus } from "./src/features/focus/Focus";
export default function App() {
const [focusSubject, setFocusSubject] = useState();
return (
<View style={styles.container}>
{focusSubject ? (
<Text style={{ flex: 1, color: "white", fontSize: 30 }}>
Here is where I am going to build a timer
</Text>
) : (
<Focus addSubject={setFocusSubject} />
)}
<Text style={{ flex: 1, color: "white", fontSize: 30 }}>
{focusSubject}
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 50,
backgroundColor: "#252250",
},
});

Get back on a component after DeepLinking react native

I'm using deeplinking in react-native in order to redirect the user to a youtube channel. But when I'm going back to my app, I have a blank screen, how can I make the user going back to the homeScreen ?
Here is my youtube code :
import React from 'react';
import { View, Text, Linking } from 'react-native';
import Acceuil from './Accueil';
class ChaineYT extends React.Component {
state = {
isLoading:false,
isLinked: false
}
componentDidMount = () => {
Linking.openURL('vnd.youtube://' + 'www.youtube.com/channel/UC1UpcbyFVTZTDrvdjNmSzSg')
this.setState(isLoading=true, isLinked=true);
if(this.state.isLoading && this.state.isLinking){
return this.props.navigation.navigate("Acceuil")
}
}
render() {
return (
<View>
</View>
)
}
}
export default ChaineYT
I'm not sure about the states that I'm using.
Edit : I've updated with the Accueil.js screen.
import React from 'react';
import { StyleSheet, View, TextInput, Button, Text, FlatList, ListView, Linking, StatusBar } from 'react-native';
import voyantes from '../Helpers/voyantesData';
import VoyanteItem from './VoyanteItem';
import MyButton2 from './MyButton2';
const numColumns = 2;
class Accueil extends React.Component {
_displayDetailForVoyante = (idVoyante,photo, specialite, description, name) => {
console.log("Display film with id " + idVoyante);
this.props.navigation.navigate("VoyanteProfil", { idVoyante: idVoyante,photo: photo,specialite:specialite,description:description, name:name });
}
render() {
return (
<View style={styles.main_container}>
<View style={{ flexDirection:'row', justifyContent: 'space-around', marginVertical: 8 }}>
<MyButton2 style={{}} text={"Voyance privée\nouvert 24h/24\n01 44 01 77 01"} icone='icone-transfert' onPress={() => { Linking.openURL('tel:0144017701'); }}/>
<MyButton2 text={"Voyance sans CB\nouvert 24h/24\n32 32"} icone='icone-sonnerie' onPress={() => { Linking.openURL('tel:3232'); }}/>
</View>
<FlatList style={styles.flatList}
data={voyantes}
keyExtractor={(item) => item.id.toString()}
renderItem={({item}) => <VoyanteItem voyante={item} displayDetailForVoyante={this._displayDetailForVoyante} />}
numColumns={numColumns} />
</View>
)
}
}
const styles = StyleSheet.create({
main_container: {
flex: 1,
backgroundColor: '#dfdee1',
backgroundColor: 'white',
flexDirection: 'column',
},
textinput: {
marginLeft: 5,
marginRight: 5,
height: 50,
borderColor: '#000000',
borderWidth: 1,
paddingLeft: 5,
backgroundColor: 'white'
},
button: {
backgroundColor: '#EF3934',
borderColor: '#EF3934',
marginLeft: 20,
marginRight: 20
},
text: {
backgroundColor: '#EF3934',
borderColor: '#EF3934',
marginLeft: 20,
marginRight: 20
},
flatList: {
flex: 1,
flexDirection: 'column',
alignContent: 'flex-start',
//justifyContent: 'flex-start',
//alignItems: 'flex-start'
}
})
export default Accueil
``
I found solution :
In your ChaineYT you have written below line :
this.setState(isLoading=true, isLinked=true);
replace it with :
this.setState({isLoading:true, isLinked:true});

React native search onChange input text, code structure

I am building a searchBar, whenever I do search I get undefined error because the value doesn't exist in state till I finish the whole value so I know that I will get error yet I am unable to solve it so I am trying to render cards according to the search input I think I did hard code my homeScreen I am not sure if I am doing it even right and here it comes the question to the three if statements inside render that I have is it good practice ? is it professional ? can i do something else which makes code easier to read and shorter ? I was thinking of eliminating the third if but I wasn't able to change state inside the second if so I had to add the toggle search function to let it work any ideas on how to eliminate the third if would be nice ..! thank you in advance guys
homeScreen.js
import axios from 'axios';
import React from 'react';
import {
ActivityIndicator,
ScrollView,
Text,
View,
TouchableOpacity,
TextInput,
} from 'react-native';
import Card from '../Components/Card/card';
export default class HomeScreen extends React.Component {
state = {
shows: [],
isLoading: true,
search: false,
title: '',
};
componentDidMount() {
this.getData();
}
toggleSearch = () => {
console.log('hlelleloe');
this.setState({
search: true,
});
};
getData = () => {
const requestUrls = Array.from({length: 9}).map(
(_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`,
);
const handleResponse = data => {
this.setState({
isLoading: false,
shows: data,
});
};
const handleError = error => {
console.log(error);
this.setState({
isLoading: false,
});
};
Promise.all(requestUrls.map(url => axios.get(url)))
.then(handleResponse)
.catch(handleError);
};
render() {
const {isLoading, shows, search, title} = this.state;
if (isLoading) {
return <ActivityIndicator size="large" color="#0000ff" />;
} else if (!search) {
return (
<View>
<View>
<TouchableOpacity
onPress={this.toggleSearch}
style={{height: 300, width: 300}}>
<Text style={{textAlign: 'center', fontSize: 40}}>
Press to Search
</Text>
</TouchableOpacity>
</View>
<ScrollView style={{backgroundColor: '#E1E8E7'}}>
{shows.length &&
shows.map((show, index) => {
return (
<Card
key={show.data.id}
title={show.data.name}
rating={show.data.rating.average}
source={show.data.image.medium}
genres={show.data.genres}
language={show.data.language}
network={show.data.network}
schedule={show.data.schedule}
summary={show.data.summary}
navigation={this.props.navigation}
/>
);
})}
</ScrollView>
</View>
);
} else if (search) {
console.log(title);
return (
<View>
<TextInput
style={{
height: 100,
width: 100,
borderColor: 'gray',
borderWidth: 1,
}}
onChangeText={searchedTitle => (
<Card title={shows.data.searchedTitle} />
)}
/>
</View>
);
}
}
}
Card.js
import React from 'react';
import {
Image,
View,
Text,
Button,
StyleSheet,
TouchableOpacity,
} from 'react-native';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import Icon from 'react-native-vector-icons/FontAwesome';
const Card = props => {
return (
<View style={styles.container}>
<Image style={styles.Image} source={{uri: `${props.source}`}} />
<Text style={styles.title}>{props.title}</Text>
<View style={styles.ratingContainer}>
<Text style={styles.rating}>Rating: {props.rating}</Text>
<Icon name="star" size={30} color="grey" />
</View>
<TouchableOpacity
style={styles.button}
onPress={() => {
props.navigation.navigate('Details', {
title: props.title,
rating: props.rating,
source: props.source,
genres: props.genres,
language: props.language,
network: props.network,
schedule: props.schedule,
summary: props.summary,
});
}}>
<Text style={styles.buttonText}>Press for details </Text>
</TouchableOpacity>
</View>
);
};
export default Card;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
},
Image: {
flex: -1,
width: wp('90%'),
height: hp('65%'),
},
title: {
flex: 1,
fontSize: 40,
borderRadius: 10,
color: '#3C948B',
margin: 15,
justifyContent: 'center',
alignItems: 'center',
},
ratingContainer: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'white',
elevation: 6,
justifyContent: 'space-between',
borderWidth: 1,
width: 300,
},
rating: {
fontSize: 25,
paddingLeft: 15,
},
button: {
flex: 1,
color: '#3C948B',
backgroundColor: '#3C948B',
height: hp('7%'),
width: wp('70%'),
margin: 20,
alignItems: 'center',
borderBottomLeftRadius: 10,
borderTopRightRadius: 10,
},
buttonText: {
flex: 1,
fontSize: 25,
},
});
you Need to implement a constructor for your React component.
Typically, in React constructors are only used for two purposes:
Initializing local state by assigning an object to this.state
Binding event handler methods to an instance
Do
state = {
shows: [],
isLoading: true,
search: false,
title: '',
};
replace this with
constructor(props){
super(props);
this.state = {
shows: [],
isLoading: true,
search: false,
title: '',
};
}

React Native: Navigation not working in component

I can not open the third page screen with the On Press method in the List Component.js file. I do not understand the problem. I want to know what I'm doing wrong with this. Where is the problem? Thank you. Please help.
Thank you for your reply but this will not work, my friend. I've updated the ListComponent.js file. The ListComponent.js file is actually a list. Please can you look again. ?
App.js
import React, { Component } from 'react';
import {
WebView,
AppRegistry, StyleSheet, Text, View, Button
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import ListComponent from './ListComponent';
class App extends Component {
static navigationOptions =
{
title: 'App',
};
OpenSecondActivityFunction = () =>
{
this.props.navigation.navigate('Second');
}
render() {
return (
<View style={styles.container}>
<Button onPress = { this.OpenSecondActivityFunction } title = 'Open Second Activity'/>
</View>
);
}
}
class SecondActivity extends Component
{
static navigationOptions =
{
title: 'SecondActivity',
};
OpenThirdActivityFunction = () =>
{
this.props.navigation.navigate('Third');
}
render()
{
return(
<View style={{ flex: 1}}>
<ListComponents data={alapinCtrl} OpenThirdActivityFunction={this.OpenThirdActivityFunction} />
</View>
);
}
}
class ThirdActivity extends Component
{
static navigationOptions =
{
title: 'ThirdSecondActivity',
};
render()
{
return(
<View style={{ flex: 1}}>
<Text>3</Text>
</View>
);
}
}
export default ActivityProject = StackNavigator(
{
First: { screen: App },
Second: { screen: SecondActivity },
Third: { screen: ThirdActivity }
});
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},ActivityNameTextCss:
{
fontSize: 22,
color: 'black',
textAlign: 'center',
},
});
AppRegistry.registerComponent('ActivityProject', () => ActivityProject);
ListComponent.js
import React, { Component } from "react";
import {AppRegistry,View, Text, FlatList, ActivityIndicator} from "react-native";
import { List, ListItem, SearchBar } from "react-native-elements";
class ListComponents extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false
};
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: "98%",
backgroundColor: "#CED0CE",
marginLeft: "2%"
}}
/>
);
};
renderHeader = () => {
return <SearchBar placeholder="Type Here..." lightTheme round />;
};
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: "#CED0CE"
}}
>
<ActivityIndicator animating size="large" />
</View>
);
};
render() {
return (
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={this.props.data}
renderItem={({ item }) => (
<ListItem
roundAvatar
title={`${item.name}`}
subtitle={item.coders}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() => this.props.OpenThirdActivityFunction(item.coders)}
/>
)}
keyExtractor={item => item.coders}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
/>
</List>
);
}
}
export default ListComponents;
Only SecondActivity has the navigation prop; you need to explicitly pass it to child component:
<ListComponent navigation={this.props.navigation} />
Alternatively,
<ListComponent onPress={() => this.props.navigation.navigate('Third')} />;
Then just do <Button onPress={this.props.onPress} in your ListComponent.