how to pass data between components using props in react native - react-native

I'm new in react-native and I want to pass data from the Home component to the Product component and I import the Product component in the Home component and I map the Product component but I get an error and it says undefined is not an object
Home.js
import * as React from 'react';
import { View, Text, StyleSheet, ScrollView } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { Card, Button } from 'react-native-elements';
import Product from './components/Product';
const BASE_URL = 'https://raw.githubusercontent.com/sdras/sample-vue-shop/master/dist';
const products = [
{
name: 'Khaki Suede Polish Work Boots',
price: 149.99,
img: `${BASE_URL}/shoe1.png`
},
{
name: 'Camo Fang Backpack Jungle',
price: 39.99,
img: `${BASE_URL}/jacket1.png`
},
{
name: 'Parka and Quilted Liner Jacket',
price: 49.99,
img: `${BASE_URL}/jacket2.png`
},
{
name: 'Cotton Black Cap',
price: 12.99,
img: `${BASE_URL}/hat1.png`
},
];
function HomeScreen({ navigation }) {
return (
<ScrollView
style={{
flexGrow: 0,
width: "100%",
height: "100%",
}}>
{
products.map((product, index) => {
return(
<View style={styles.row} key={index}>
<View style={styles.col}>
<Product/>
</View>
</View>
)
})
}
</ScrollView>
);
}
const styles = StyleSheet.create({
row: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
},
col: {
flex: 1,
},
});
export default HomeScreen;
Product.js:
import * as React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Card, Button } from 'react-native-elements';
import { useNavigation } from '#react-navigation/native';
function Product(props){
const navigation = useNavigation();
return(
<Card
image={{uri: this.props.product.img}}>
<Text style={{marginBottom: 10, marginTop: 20 }} h2>
{this.props.product.name}
</Text>
<Text style={styles.price} h4>
{this.props.product.price}
</Text>
<Text h6 style={styles.description}>
added 2h ago
</Text>
<Button
type="clear"
title='Buy now'
onPress={() => navigation.navigate('Details')}
/>
</Card>
);
}
const styles = StyleSheet.create({
name: {
color: '#5a647d',
fontWeight: 'bold',
fontSize: 30
},
price: {
fontWeight: 'bold',
marginBottom: 10
},
description: {
fontSize: 10,
color: '#c1c4cd'
}
});
export default Product;
Error screenshot:
how to solve my problem

Please update your home component to this
function HomeScreen({ navigation }) {
return (
<ScrollView
style={{
flexGrow: 0,
width: "100%",
height: "100%",
}}>
{
products.map((product, index) => {
return(
<View style={styles.row} key={index}>
<View style={styles.col}>
<Product product={product}/>
</View>
</View>
)
})
}
</ScrollView>
);
}
Basically you need to pass the product as a prop to Product component.
There is no this in functional component. Please update your product component
function Product(props){
const navigation = useNavigation();
return(
<Card
image={{uri: this.props.product.img}}>
<Text style={{marginBottom: 10, marginTop: 20 }} h2>
{props.product.name}
</Text>
<Text style={styles.price} h4>
{props.product.price}
</Text>
<Text h6 style={styles.description}>
added 2h ago
</Text>
<Button
type="clear"
title='Buy now'
onPress={() => navigation.navigate('Details')}
/>
</Card>
);
}

Pass props in home component to product like this.
const products = [
{
name: 'Khaki Suede Polish Work Boots',
price: 149.99,
img: `${BASE_URL}/shoe1.png`,
},
{
name: 'Camo Fang Backpack Jungle',
price: 39.99,
img: `${BASE_URL}/jacket1.png`,
},
{
name: 'Parka and Quilted Liner Jacket',
price: 49.99,
img: `${BASE_URL}/jacket2.png`,
},
{
name: 'Cotton Black Cap',
price: 12.99,
img: `${BASE_URL}/hat1.png`,
},
];
function HomeScreen({navigation}) {
return (
<ScrollView
style={{
flexGrow: 0,
width: '100%',
height: '100%',
}}>
{products.map((product, index) => {
return (
<View style={styles.row} key={index}>
<View style={styles.col}>
<Product product={products} />
</View>
</View>
);
})}
</ScrollView>
);
}
------------Product.js-----------
function Product({product}) {
const navigation = useNavigation();
return (
<Card image={{uri: product.img}}>
<Text style={{marginBottom: 10, marginTop: 20}} h2>
{product.name}
</Text>
<Text style={styles.price} h4>
{product.price}
</Text>
<Text h6 style={styles.description}>
added 2h ago
</Text>
<Button
type="clear"
title="Buy now"
onPress={() => navigation.navigate('Details')}
/>
</Card>
);
}

Related

I am unable to delete items in my React Native app

I am unable to delete items.
This is App.js file main file:
import { useState } from "react";
import {
StyleSheet,
Text,
View,
Button,
TextInput,
FlatList,
} from "react-native";
import Goalresults from "./Componets/Goalresult";
export default function App() {
const [comingdata, SetData] = useState("");
const [listdata, setlistdata] = useState([]);
function fetchText(enteredText) {
SetData(enteredText);
}
function buttonPress() {
setlistdata((newdata) => [
...newdata,
{ text: comingdata, id: Math.random.toString() },
]);
}
I am passing id as parameter here and used filter method so that it filter all the id and delete id from the array list.
function deleteitem(id) {
setlistdata((newdata) => {
return newdata.filter((goal) => goal.id !== id);
});
}
return (
<View style={styles.container}>
<View>
<Text style={styles.goalsc}>Your Goals</Text>
</View>
<View style={styles.container1}>
<TextInput
style={styles.textInput}
placeholder="Add Your Goals here..."
onChangeText={fetchText}
/>
<Button title="Add Goal" onPress={buttonPress} />
</View>
<View style={styles.hello}>
<FlatList
data={listdata}
renderItem={(itemdata) => {
return (
<Goalresults
id={itemdata.item.id}
onDeleteItem={deleteitem}
text={itemdata.item.text}
/>
);
}}
keyExtractor={(item, index) => {
return item.id;
}}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 50,
paddingHorizontal: 16,
},
container1: {
flex: 1,
height: 120,
// paddingTop: 10,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 20,
borderBottomWidth: 1,
borderBottomColor: "#808080",
},
textInput: {
width: "70%",
borderWidth: 1,
borderRadius: 10,
marginRight: 10,
padding: 8,
},
hello: {
flex: 3,
},
goalsc: {
fontSize: 20,
fontWeight: "bold",
paddingLeft: 140,
},
});
Second separated file:
import { View, Text, StyleSheet,Pressable} from "react-native";
function Goalresults(props) {
I used bind there to bind id:
return (
<Pressable onPress={props.onDeleteItem.bind(this,props.id)}>
<View style={styles.goalInput}>
<Text style={styles.textcolor}>{props.text}</Text>
</View>
</Pressable>
);
}
export default Goalresults;
const styles = StyleSheet.create({
goalInput: {
flex: 5,
borderRadius: 5,
paddingTop: 10,
backgroundColor: "#A020F0",
padding: 10,
margin: 10,
},
textcolor: {
color: "white",
},
});
There are a few issues with your code. I will list them as follows.
Inside Goalresults function change the bind on Pressable as
follows: <Pressable onPress={props.onDeleteItem.bind(props, props.id)}>
Inside buttonPress function correct this line { text: comingdata, id: Math.random().toString() }, you missed '()' paranthesis on random
Also on Goalresults add a key={itemdata.item.id}. It will help resolve the warning "duplicate keys".
Following is the complete code
App.js
export default function App() {
const [comingdata, SetData] = useState("");
const [listdata, setlistdata] = useState([]);
function fetchText(enteredText) {
SetData(enteredText);
}
function buttonPress() {
setlistdata((newdata) => [
...newdata,
{ text: comingdata, id: Math.random().toString() },
]);
}
function deleteitem(id) {
console.log('id: ', id)
setlistdata((newdata) => {
return newdata.filter((goal) => goal.id !== id);
});
}
return (
<View style={styles.container}>
<View>
<Text style={styles.goalsc}>Your Goals</Text>
</View>
<View style={styles.container1}>
<TextInput
style={styles.textInput}
placeholder="Add Your Goals here..."
onChangeText={fetchText}
/>
<Button title="Add Goal" onPress={buttonPress} />
</View>
<View style={styles.hello}>
<FlatList
data={listdata}
renderItem={(itemdata) => {
return (
<Goalresults
key={itemdata.item.id}
id={itemdata.item.id}
onDeleteItem={deleteitem}
text={itemdata.item.text}
/>
);
}}
keyExtractor={(item, index) => {
return item.id;
}}
/>
</View>
</View>
);
}
GoalResults.js
function Goalresults(props) {
return (
<Pressable onPress={props.onDeleteItem.bind(props, props.id)}>
<View style={styles.goalInput}>
<Text style={styles.textcolor}>{props.text}</Text>
</View>
</Pressable>
);
}

React Native TouchableOpacity onPress using index/key of the item in FlatList

We created a FlatList component and a Contact screen in our app. We want to add 'heart' icon to the near of the images in Contact screen. We added heart icon near to all of items. But, if we pressed one of these icons, it changes all of theirs colors to red, not only one of them. We want to change the color of clicked item.
Screenshot of our program:
This is our FlatList component:
import React, { Component } from 'react';
import { View, Text, SafeAreaView, StyleSheet, FlatList, Image, TouchableOpacity,
TouchableWithoutFeedback, TextInput } from 'react-native';
import { Right, Icon } from 'native-base';
import data from '../../data';
export default class FlatListComponent extends Component {
state = {
text: '',
contacts: data,
like: false,
color: 'white',
}
toggleLike=()=>{
this.setState({
like: !this.state.like
})
if(this.state.like){
this.setState({
color: 'red',
})
}else{
this.setState({
color: 'white',
})
}
}
renderContactsItem = ({item, index}) => {
return (
<View style={[styles.itemContainer]}>
<Image
style={styles.avatar}
source={{ uri: item.image }} />
<View style={styles.textContainer}>
<Text style={[styles.name], {color: '#fafafa'}}>{item.first_name}</Text>
<Text style={{ color: '#fafafa' }}>{item.last_name}</Text>
</View>
<Right style={{justifyContent: 'center'}}>
<TouchableWithoutFeedback onPress={this.toggleLike}>
{/*{this.like ? (
<Icon name="heart" type='FontAwesome' style={{paddingRight: 10, fontSize: 30, color: 'red'}} />
) :
( <Icon name="heart" type='FontAwesome' style={{paddingRight: 10, fontSize: 30, color: 'white'}} /> )
}*/}
<Icon name='heart' type='FontAwesome' size={32} style={{color: this.state.color === "white" ? 'white' :'red', paddingRight: 10 }}/>
{/*<Icon name="heart" type='FontAwesome' style={{paddingRight: 10, fontSize: 30, color: this.state.color}} />*/}
</TouchableWithoutFeedback>
</Right>
</View>
);
}
searchFilter = text => {
const newData = data.filter(item => {
const listItems = `${item.first_name.toLowerCase()}`
return listItems.indexOf(text.toLowerCase()) > -1;
});
this.setState({
contacts: newData,
});
};
renderHeader = () => {
const {text} = this.state;
return (
<View style={styles.searchContainer}>
<TextInput
onChangeText = {text => {
this.setState ({
text,
});
this.searchFilter(text);
}}
value={text}
placeholder="Search..."
style={styles.searchInput} />
</View>
)
}
render() {
return (
<FlatList
ListHeaderComponent={this.renderHeader()}
renderItem={this.renderContactsItem}
keyExtractor={item => item.id}
data={this.state.contacts}
/>
);
}
}
const styles = StyleSheet.create({
itemContainer: {
flex: 1,
flexDirection: 'row',
paddingVertical: 10,
borderBottomWidth: 1,
borderBottomColor: '#eee'
},
avatar: {
width: 50,
height: 50,
borderRadius: 25,
marginHorizontal: 10,
},
textContainer: {
justifyContent: 'space-around',
},
name: {
fontSize: 16,
},
searchContainer: {
padding: 10
},
searchInput: {
fontSize: 16,
backgroundColor: '#f9f9f9',
padding: 10,
}
});
Our Contact screen is just:
import React from 'react';
import 'SafeAreaView' from 'react-native';
import FlatList from './FlatList';
export default function Contact() {
<SafeAreaView style={{ flex: 1 }}>
<FlatList />
</SafeAreaView>
}
How can we implement this?
I've run into this recently :) One option is to make the renderContactsItem its own component. For example:
const RenderContactsItem = ({item, index}) => {
const [like, setLike] = useState(false);
const [color, setColor] = useState("white");
const toggleLike = () => {
setLike(!like)
if(like) {
setColor("red");
} else {
setColor("white");
}
}
return (
<View style={[styles.itemContainer]}>
<Image
style={styles.avatar}
source={{ uri: item.image }} />
<View style={styles.textContainer}>
<Text style={[styles.name], {color: '#fafafa'}}>{item.first_name}</Text>
<Text style={{ color: '#fafafa' }}>{item.last_name}</Text>
</View>
<Right style={{justifyContent: 'center'}}>
<TouchableWithoutFeedback onPress={toggleLike}>
<Icon name='heart' type='FontAwesome' size={32} style={{color, paddingRight: 10 }}/>
</TouchableWithoutFeedback>
</Right>
</View>
);
}
In this case, each item manages its own state, so setting like doesn't set it for every item.
Another option would be to build an object with "like" states and set the values as the hearts are pressed. For example:
state = {
text: '',
contacts: data,
like: {},
color: 'white', // You don't need this
}
Then, when a heart is pressed, you can send toggleLike the index, and set the state like so:
toggleLike = (index) => {
let newLike = {...this.state.like};
newLike[index] = !Boolean(newLike[index]);
this.setState({
like: newLike,
});
}
And render the color conditionally depending on the index value of the like state, like so:
<Icon name='heart' type='FontAwesome' size={32} style={{color: this.state.like[index] ? 'red' :'white', paddingRight: 10 }}/>

how to use the state hook for dynamically created components in react native

I am trying to do is use useState for dynamically created components in React. In the code below I am, rendering the new components, but I cannot find a way to keep track of their state like I did for the hardcoded components. The new components are rendered when the user creates a new "post", causing new "posts" to be generated.
return (
{
results.map( (eachPost) =>
{ const [status, setStatus] = React.useState(true); },
<TouchableOpacity>
<Card>
<Text>
{JSON.parse(eachPost).title}
</Text>
<Collapsible collapsed = {status}>
{JSON.parse(eachPost).content}
</Collapsible>
</Card>
</TouchableOpacity>
)
}
)
UPDATE: I need to know how I can re-render the page
import * as React from 'react';
import { StyleSheet, Button, TextInput, Image, TouchableOpacity } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { Card } from 'react-native-elements';
import Collapsible from 'react-native-collapsible';
import Accordion from 'react-native-collapsible/Accordion';
import { CardStyleInterpolators } from '#react-navigation/stack';
import AsyncStorage from '#react-native-community/async-storage';
import { useState, useCallback } from 'react';
import Post from './Post'
import RenderToLayer from 'material-ui/internal/RenderToLayer';
import { useForceUpdate } from './useForceUpdate'
async function createNewPost (titleAndContent : string){
const post = {titleAndContent_: titleAndContent}
try {
await AsyncStorage.setItem('post' + Math.floor(100000 + Math.random() * 900000), JSON.stringify(post))
} catch (e) {
console.log(e)
}
//console.log(newPosts)
}
export default function NewsScreen({ navigation }: { navigation: any }) {
const [status, setStatus] = React.useState(true);
const [status2, setStatus2] = React.useState(true);
const [status3, setStatus3] = React.useState(true);
const [renderedData, setRenderedData] = React.useState(new Array<string>());
const [input, setInput] = React.useState('Please enter the details of the post in the format of title,content');
const [, forceUpdate] = useState();
const getData = async () => {
try {
const keys = await AsyncStorage.getAllKeys();
const result = await AsyncStorage.multiGet(keys);
console.log(result)
return result;
} catch (e) {
console.log(e);
}
};
async function parseData() {
const payments = await getData();
if (payments) {
const res = payments
//.filter((e: any[]) => e[1] && e.includes('{'))
//.map((e: any[]) => e[1]);
setRenderedData(res);
console.log(res)
}
return renderedData;
}
const results: string[] = []
renderedData.forEach( (eachPost) => {
if ((/\{"title.*}/g.test(eachPost[1]))) results.push(eachPost[1])
})
console.log(results)
React.useEffect(() => {
if (renderedData.length === 0) {
parseData();
}
forceUpdate
},[]);
return (
<View style={styles.container}>
<Text style={{ fontSize: 25}}>News</Text>
<View style = {{flexDirection: "row"}}>
<TextInput
style={{ height: 40, width: 700, borderColor: 'gray', borderWidth: 1 }}
value = {input}
onChangeText={text=>setInput(text)}
/>
<Button
onPress={()=> createNewPost(input)}
title="Add post"
color="blue"
accessibilityLabel="A button to allow the admin to create a new post"
/>
<Button
onPress = {useForceUpdate()}
title="submit"
/>
</View>
<View>
{
results.map( (eachPost) =>
<Post titleAndContent={JSON.parse(eachPost)}/>
)
}
<TouchableOpacity onPress={() => setStatus(!status)}>
<Card>
<Text>
Moore Park Lift Outage
</Text>
<Image
source={{
uri: 'https://i.imgur.com/Etr5xBn.png'
}}
style={{width: 20, height: 20, marginLeft: 10}}
>
</Image>
<Collapsible collapsed = {status}>
<Text style={{fontWeight: 'bold'}}>
UPDATED 6 Aug 09:30 {'\n'}
Details: Ongoing {'\n'}
Lift 2 at Moore Park Light Rail is temporarily out of service. For assistance, ask staff.. {'\n'}
</Text>
<Image
source={{
uri: 'https://svg-clipart.com/svg/blue/PGaAIh0-blue-wheelchair-vector.svg',
}}
style={{width: 70, height: 90, marginTop: 30}}
>
</Image>
</Collapsible>
</Card>
</TouchableOpacity>
<TouchableOpacity onPress={() => setStatus2(!status2)}>
<Card>
<Text>Dulwich Hill Line running slow</Text>
<Image
source={{
uri: 'https://i.imgur.com/iNjXQMW.png'
}}
style={{width: 20, height: 20, marginLeft: 10}}
>
</Image>
<Collapsible collapsed = {status2}>
<Text>
The Dulwich Hill Line is running slow due to track-work being conducted between Lilyfield and Rozelle Bay
</Text>
</Collapsible>
</Card>
</TouchableOpacity>
<TouchableOpacity onPress={() => setStatus3(!status3)}>
<Card >
<Text>Extra services running</Text>
<Image
source={{
uri: 'https://imgur.com/Etr5xBn'
}}
style={{width: 20, height: 20, marginLeft: 10}}
>
</Image>
<Image
source={{
uri: 'https://i.imgur.com/Etr5xBn.png'
}}
style={{width: 20, height: 20, marginLeft: 10}}
>
</Image>
<Collapsible collapsed = {status3}>
<Text>
Extra services will be running this week to help students get back to school
</Text>
</Collapsible>
</Card>
</TouchableOpacity>
</View>
<View style={styles.button}>
<Button
onPress={() => navigation.navigate('HomeScreen')}
title="Go back"
color="blue"
accessibilityLabel="A button to click so that you can go back to the home page"
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'flex-start',
justifyContent: 'flex-start',
flexDirection: 'column',
},
title: {
fontSize: 20,
fontWeight: 'bold',
alignItems: 'center',
justifyContent: 'center',
},
separator: {
marginVertical: 30,
height: 1,
width: '80%',
},
button: {
margin: 10,
flexDirection: 'row',
},
news:{
flexDirection:'column',
backgroundColor: 'white',
},
eachnews:{
margin: 500,
fontWeight: 'bold',
alignItems: 'flex-start',
justifyContent: 'flex-start',
},
textnews:{
fontSize: 20,
},
});
I think you need more knowledge related to basics of react.
You need a Post component
Post.js
export default (props) => {
const [status, setStatus] = useState();
return (<TouchableOpacity>
<Card>
<Text>
{props.title}
</Text>
<Collapsible collapsed = {status}>
{props.content}
</Collapsible>
</Card>
</TouchableOpacity>);
};
When u call Post
App.js
import Post from './Post.js'
export default App = ()
{
const result = [];
return (
results.map( (eachPost) =>{
const eachPost = JSON.parse(eachPost);
return (<Post title={eachPost.title} content={eachPost.content})/>)
}
}
)

navigate to another screen using react native

I am trying to navigate to another screen while pressing on a button using onpress in react native but getting error. Front page is App.js which contains multiple buttons, I am working on event button for now. when I press on event button then it should redirect to the contain in event.js I am a newbie in react.
App.js
import React from "react";
import {StyleSheet,Text,View,Button,Image,ProgressViewIOS} from "react-native";
import event from './event.js';
export default class App extends React.Component {
render() {
return (
<View>
<Text style={styles.h1}>WELCOME TO </Text>
<Image
style={styles.logo}
source={require('./logo_tiny.jpg')}
/>
<View style={styles.container}>
<View style={styles.b1}>
<Button
title="Events"
onPress={() => this.onPress('navigateToevent')}
color="#fff"
/>
</View>
<View style={styles.b1}>
<Button
title="Package"
onPress={() => this.onPress()}
color="#fff"
/>
</View>
</View>
<View style={styles.container}>
<View style={styles.b1}>
<Button
title="Promotion"
onPress={() => this.onPress()}
color="#fff"
/>
</View>
<View style={styles.b1}>
<Button
title="Support"
onPress={() => this.onPress()}
color="#fff"
/>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
h1: {
textAlign: 'center',
color: '#1E7778',
fontSize: 32,
marginTop: 18,
width: 400,
fontWeight: 'bold',
},
container: {
flexDirection: 'row',
},
b1: {
width: '40%',
margin: 20,
padding: 10,
backgroundColor: '#D16B11',
borderRadius: 20,
},
logo: {
alignItems: 'center',
justifyContent:'center',
left: '20%',
},
});
event.js
import React from 'react';
export default class event extends React.Component {
navigateToevent = () => {
this.props.navigation.navigate('event');
};
constructor(props) {
super(props);
this.state = {
country: null,
city: null,
cities: []
};
}
changeCountry(item) {
let city = null;
let cities;
switch (item.value) {
case 'fr':
cities = [
{label: 'Paris', value: 'paris'}
];
break;
case 'es':
cities = [
{label: 'Madrid', value: 'madrid'}
];
break;
}
this.setState({
city,
cities
});
}
changeCity(item) {
this.setState({
city: item.value
});
}
render() {
return (
<>
<DropDownPicker
items={[
{label: 'France', value: 'fr'},
{label: 'Spain', value: 'es'},
]}
defaultNull
placeholder="Select your country"
containerStyle={{height: 40}}
onChangeItem={item => this.changeCountry(item)}
/>
<DropDownPicker
items={this.state.cities}
defaultNull={this.state.city === null}
placeholder="Select your city"
containerStyle={{height: 40}}
onChangeItem={item => this.changeCity(item)}
/>
</>
);
}
}
// event.js
import React from "react";
import DropDownPicker from "react-native-dropdown-picker";
export default class event extends React.Component {
constructor(props) {
super(props);
this.state = {
country: null,
city: null,
cities: [],
};
}
changeCountry(item) {
let city = null;
let cities;
switch (item.value) {
case "fr":
cities = [{ label: "Paris", value: "paris" }];
break;
case "es":
cities = [{ label: "Madrid", value: "madrid" }];
break;
}
this.setState({
city,
cities,
});
}
changeCity(item) {
this.setState({
city: item.value,
});
}
render() {
return (
<>
<DropDownPicker
items={[
{ label: "France", value: "fr" },
{ label: "Spain", value: "es" },
]}
defaultNull
placeholder="Select your country"
containerStyle={{ height: 40 }}
onChangeItem={(item) => this.changeCountry(item)}
/>
<DropDownPicker
items={this.state.cities}
defaultNull={this.state.city === null}
placeholder="Select your city"
containerStyle={{ height: 40 }}
onChangeItem={(item) => this.changeCity(item)}
/>
</>
);
}
}
// main.js
import React from "react";
import {
StyleSheet,
Text,
View,
Button,
Image,
ProgressViewIOS,
} from "react-native";
import event from "./event.js";
export default class Main extends React.Component {
navigateToevent = () => {
this.props.navigation.navigate("event");
};
render() {
return (
<View>
<Text style={styles.h1}>WELCOME TO </Text>
<Image style={styles.logo} />
<View style={styles.container}>
<View style={styles.b1}>
<Button
title="Events"
onPress={() => this.navigateToevent()}
color="#fff"
/>
</View>
<View style={styles.b1}>
<Button
title="Package"
onPress={() => this.onPress()}
color="#fff"
/>
</View>
</View>
<View style={styles.container}>
<View style={styles.b1}>
<Button
title="Promotion"
onPress={() => this.onPress()}
color="#fff"
/>
</View>
<View style={styles.b1}>
<Button
title="Support"
onPress={() => this.onPress()}
color="#fff"
/>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
h1: {
textAlign: "center",
color: "#1E7778",
fontSize: 32,
marginTop: 18,
width: 400,
fontWeight: "bold",
},
container: {
flexDirection: "row",
},
b1: {
width: "40%",
margin: 20,
padding: 10,
backgroundColor: "#D16B11",
borderRadius: 20,
},
logo: {
alignItems: "center",
justifyContent: "center",
left: "20%",
},
});
// App.js
import React from "react";
import {
StyleSheet,
Text,
View,
Button,
Image,
ProgressViewIOS,
} from "react-native";
import event from "./event.js";
import main from "./main.js";
import { createAppContainer } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
const AppNavigator = createStackNavigator({
main: {
screen: main,
},
event: {
screen: event,
},
});
class App extends React.Component {
render() {
return (
<View>
<AppNavigator />
</View>
);
}
}
export default AppContainer = createAppContainer(AppNavigator);
Try this works for you
This contains most of what you need with navigation on react native. https://reactnative.dev/docs/navigation
Need to wrap your code in <NavigationContainer>

React navigation status bar alert

I'm using react-native-status-bar-alert in combination with react-navigation.
In the latest version of react-navigation there's a problem with the height.
The height of the header is too big when the alert is active.
Anyone else experienced this issue and has a solution?
I think you should use a plugin: navigationbar-react-native
First, if you use react-navigation you should hide header-bar and use custom header-bar
export const RootStack = createStackNavigator(
{
Home: {
screen: HomeComponent,
navigationOptions: {
header: null,
},
},
},
{
initialRouteName: 'Home',
}
);
1, Install package
npm i navigationbar-react-native --save
2, Using
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,Image,
View,
TouchableOpacity,
} from 'react-native';
import NavigationBar from 'navigationbar-react-native';
const ComponentLeft = () => {
return(
<View style={{ flex: 1, alignItems: 'flex-start'}} >
<TouchableOpacity style={ {justifyContent:'center', flexDirection: 'row'}}>
<Image
source={require('./img/ic_back.png')}
style={{ resizeMode: 'contain', width: 20, height: 20, alignSelf: 'center' }}
/>
<Text style={{ color: 'white', }}>Back Home</Text>
</TouchableOpacity>
</View>
);
};
const ComponentCenter = () => {
return(
<View style={{ flex: 1, }}>
<Image
source={require('./img/ic_logo.png')}
style={{resizeMode: 'contain', width: 200, height: 35, alignSelf: 'center' }}
/>
</View>
);
};
const ComponentRight = () => {
return(
<View style={{ flex: 1, alignItems: 'flex-end', }}>
<TouchableOpacity>
<Text style={{ color: 'white', }}> Right </Text>
</TouchableOpacity>
</View>
);
};
class App extends Component {
render() {
return (
<View style={styles.container}>
<NavigationBar
componentLeft = { () => {<ComponentLeft /> }
componentCenter = { () => {<ComponentCenter /> }
componentRight = { () => {<ComponentRight /> }
navigationBarStyle= {{ backgroundColor: ''#215e79'' }}
statusBarStyle = {{ barStyle: 'light-content', backgroundColor: '#215e79' }}
/>
</View>
);
}
}
Easy create custom header bar in react native