*hi everyone
i am new in React native programming and Java script i want to build a list item and when i press an item i should go to another screen i used the method onPress *
*but it doesn't work i hope that i will find the answer here as soon as possible: *
import React, { Component } from 'react';
import { AppRegistry, Image , StyleSheet, Text, View } from 'react-native';
import { ListItem } from 'react-native-elements';
import { Icon,navigationOptions } from 'react-native-elements';
export default class HomeScreen extends Component {
goToOtherScreen(ScreenName) {
this.props.navigation.navigate('Item');
}
render() {
let pic = {
uri: 'https://www.lscoiffure.fr/images/assistance.jpg'
};
return (
<View style={styles.container}>
//Image "jai utilisé juste une autre photo pour essayer"
<View>
<Image source={pic} style={{width: 350, height: 200}}
/>
//Text(title)
<View style={{position: 'absolute', left: 0, right: 0, bottom: 0, justifyContent: 'center',marginBottom:20, alignItems: 'center'}}>
<Text style={{color :'#ffffff',fontSize:24}}>Assistance</Text>
</View>
</View>
{
list.map((item, i) => (
<ListItem
key={i}
title={item.title}
leftIcon={{ name: item.icon ,color:'black'}}
onPress={() => this.goToOtherScreen(item.ScreenName)}
/>
))
}
</View>
);
}
}
const list = [
{
title: 'Appeler le service clientèle',
icon: 'perm-phone-msg',
ScreenName : 'SecondScreen',
},
{
title: 'FAQ',
icon: 'help'
},
{
title: 'Conditions et mentions légal',
icon :'error'
},
]
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor:'#ffffff'
},
item: {
padding: 50,
fontSize: 18,
height: 44,
},
})
please help me to know where is my mistake
Change this in your code
goToOtherScreen(ScreenName) {
this.props.navigation.navigate(ScreenName);
}
Related
I have an issue in my project. I want to show elements after I get them from the JSON. When I am trying to observe content of JSON I see it, but when I am trying to show it in my component it doesn't appear. Also debugger don't show any errors or problrms and app compiles sucessfully. I am really stuck, so I really need your help guys
App.js code:
import React, { Component } from 'react'
import { View, ScrollView, StyleSheet } from 'react-native'
import { Header, ImageCard } from './src/components/uikit'
const url = 'https://s3.eu-central-1.wasabisys.com/ghashtag/RNForKids/00-Init/data.json'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
title: 'STAR GATE',
data: []
};
}
componentDidMount = async () => {
try {
const response = await fetch(url)
const data = await response.json()
this.setState({ data })
}
catch (e) {
console.log(e)
throw e
}
}
render() {
const { title, data } = this.state
const { container } = style
return (
<View>
<Header title={title} />
<ScrollView>
<View style={container}>
{data.map(item => {
<ImageCard data={item} key={item.id} />
})
}
</View>
</ScrollView>
</View>
)
}
}
const style = StyleSheet.create({
container: {
marginTop: 30,
flexDirection: 'row',
flexWrap: 'wrap',
flexShrink: 2,
justifyContent: 'space-around',
marginBottom: 150,
backgroundColor: 'gold',
width: 150
}
})
My problem happens in App.js inside the
And ImageCard code:
import React from 'react'
import { Image, View, Text, StyleSheet } from 'react-native'
import { h, w } from '../../../constants'
const ImageCard = ({data}) => {
const {container, sub, h2, cover} = styles
const {image, name} = data
return (
<View style={container}>
<View style={sub}>
<Image
style={cover}
source={{
uri: image,
}}
/>
</View>
<Text style={h2}>{name.toUpperCase()}</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
width: w / 2.1,
paddingVertical: 10,
},
sub: {
padding:10,
shadowColor: 'black',
shadowRadius: 8,
shadowOffset: { width: 0, height: 5 },
shadowOpacity: 0.4,
},
h2: {
fontFamily: 'AvenirNext-DemiBold',
fontSize: 16,
alignSelf: 'center',
textAlign: 'center',
width: w / 2.4
},
cover: {
width: w / 2.4,
height: w * 0.63,
borderRadius: 10
}
})
export { ImageCard }
It should be ok, I made it by guide, but something went wrong.
It looks like you're not returning anything from map!
data.map(item => {
<ImageCard data={item} key={item.id} />
})
should become
data.map(item => {
return <ImageCard data={item} key={item.id} />
})
// OR
data.map(item => ( // <-- Note the bracket change
<ImageCard data={item} key={item.id} />
))
1
I am a beginner and still learning to react native.
In my react native App, I have 2 screens. In the first page, I have JSON data ; I want to pass this JSON data to the next page.
I used react-navigation for navigating between pages. I need to passed each parameter for a new book screen for each book.
But I couldn't figure out, how to pass JSON data to next page! In BookScreen.js the function "getParam" is not been seen.
First Screen: ExploreScreen.js
import React, { useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
Image,
TouchableOpacity,
} from "react-native";
export default function ExploreScreen({ navigation, route }) {
const [data, setData] = useState([]);
useEffect(() => {
loadData();
}, []);
const loadData = async () => {
await fetch(
"http://www.json-generator.com/api/json/get/bTvNJudCPS?indent=2"
)
.then((response) => response.json())
.then((receivedData) => setData(receivedData));
};
return (
<View style={styles.container}>
<FlatList
data={data}
renderItem={({ item }) => (
<TouchableOpacity
style={styles.book}
onPress={() => navigation.navigate("Book", item)}
>
<Image
style={styles.bookImage}
source={{ uri: item.book_image }}
></Image>
<View>
<Text style={styles.bookTitleText}>{item.title}</Text>
<Text style={styles.bookAuthor}>{item.author}</Text>
<Text style={styles.bookGenre}>
<Text styles={styles.gen}>Genul: </Text>
{item.genre_id}
</Text>
</View>
</TouchableOpacity>
)}
></FlatList>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
alignSelf: "center",
paddingVertical: "15%",
},
book: {
flex: 1,
flexDirection: "row",
marginBottom: 3,
},
bookImage: {
width: 100,
height: 100,
margin: 5,
},
bookTitleText: {
color: "#8B0000",
fontSize: 15,
fontStyle: "italic",
fontWeight: "bold",
},
bookAuthor: {
color: "#F41313",
},
});
Second Screen: BookScreen.js
import React from "react";
import { View, Text, StyleSheet } from "react-native";
export default function BookScreen({ navigation, route }) {
const { item } = route.params;
return (
<View style={styles.container}>
<Text style={styles.text}>{navigation.getParam("name")}</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
alignSelf: "center",
paddingVertical: "100%",
},
text: {
fontSize: 20,
},
});
In your BookScreen, change it to the following:
export default function BookScreen({ navigation, route }) {
const { item } = route.params;
return (
<View style={styles.container}>
<Text style={styles.text}>{item.name}</Text>
</View>
);
}
Edit:
I think you should pass the data like this:
navigation.navigate('Book', {item: item});
I'm studying React Native with this site https://www.tutorialspoint.com/react_native/react_native_animations.htm
However, there is a problem while i'm trying to open app on iPhone. According to error it cannot find variable, though it's imported.
import React, { Component } from 'react';
import { View, LayoutAnimation, TouchableOpacity, Text, StyleSheet} from 'react-native';
export default class Animations extends Component {
state = {
myStyle: {
height: 100,
backgroundColor: 'red'
}
};
expandElement = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
this.setState({
myStyle: {
height: 400,
backgroundColor: 'red'
}
})
};
collapseElement = () => {
LayoutAnimation.configureNext(LayoutAnimation.Presets.linear);
this.setState({
myStyle: {
height: 100,
backgroundColor: 'red'
}
})
};
render() {
return (
<View>
<View>
<View style={this.state.myStyle}/>
</View>
<TouchableOpacity>
<Text style={styles.button} onPress = {this.expandElement}>
Expand
</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text style={styles.button} onPress = {this.collapseElement}>
Collapse
</Text>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create({
button: {
borderWidth: 1,
borderColor: 'red',
color: 'red',
textAlign: 'center',
marginTop: 50,
padding: 10
}
});
Ah... I've found the problem. It was in other component which had styles but no elements to them and had no imported StylesSheet since I corrected it to new conditions but forgot about block with styles.
I am trying to pass some row data from a list to next screen to display details but cannot seem to achieve it.
This is how i pass props when navigating like:
_renderRow(row,sectionId, rowId, highlightRow) {
var self = this;
let navigate=this.props.navigation;
return (
<TouchableOpacity onPress={() => navigate('ChatList',{row})}>
........//ignored code
And on the other screen ChatList.js:
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
TextInput,
Image
} from 'react-native';
import { StackNavigator } from 'react-navigation';
const ChatList = () => {
return (
<View>
</View>
);
}
ChatList.navigationOptions = {
//trying to set the title from the data sent around here
title: 'ChatList Title',
headerStyle: {
backgroundColor: '#2196F3',
},
headerTitleStyle: {
color: 'white',
},
headerBackTitleStyle: {
color: 'white',
},
headerTintColor: 'white',
};
export default ChatList
Also to note, i have a different implementation on stacknavigation unlike the docs from reactnavigation .Checkout my entire implementation here https://gist.github.com/SteveKamau72/f04b0a3dca03a87d604fe73767941bf2
Here is the full class from which _renderRow resides:
ChatGroup.js
/** ChatGroup.js**/
//This code is component for file App.js to display group of chats
import React, { Component } from 'react';
import {
StyleSheet,
ListView,
Text,
View,
Image,
TouchableOpacity
} from 'react-native';
const data = [
{
name: "Kasarini",
last_chat: {
updated_at:"22:13",
updated_by: "Steve Kamau",
chat_message: "Lorem Ipsum is pretty awesome if you know it"
},
thumbnail: "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
{
name: "Kabete",
last_chat: {
updated_at:"20:34",
updated_by: "Tim Mwirabua",
chat_message: "Lorem Ipsum is pretty awesome if you know it"
},
thumbnail: "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
{
name: "Kiambuu",
last_chat: {
updated_at:"19:22",
updated_by: "Maureen Chubi",
chat_message: "Lorem Ipsum is pretty awesome if you know it"
},
thumbnail: "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
{
name: "UnderPass",
last_chat: {
updated_at:"17:46",
updated_by: "Faith Chela",
chat_message: "Lorem Ipsum is pretty awesome if you know it"
},
thumbnail: "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
]
export default class UserListView extends Component {
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: this._rowHasChanged});
this.state = {
dataSource: ds.cloneWithRows(data)
}
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow.bind(this)}
enableEmptySections={true} />
)
}
_renderRow(row,sectionId, rowId, highlightRow) {
var self = this;
return (
<TouchableOpacity activeOpacity={0.9} onPress={() => navigate('ChatList',{ user: 'Lucy' })}>
<View style={styles.container}>
<Image
style={styles.groupChatThumbnail}
source={{uri: row.thumbnail}}/>
<View>
<View style={{flexDirection:'row', justifyContent:'space-between', width:280}}>
<Text style={styles.groupNameText}>{row.name} </Text>
<Text style={styles.groupUpdatedAtText}>{row.last_chat.updated_at}</Text>
</View>
<View style={{ flexDirection:'row', alignItems:'center', marginTop: 5}}>
<Text style={styles.groupUpdatedByText}>{row.last_chat.updated_by} : </Text>
<View style={{flex: 1}}>
<Text ellipsizeMode='tail' numberOfLines={1}style={styles.groupChatMessageText}>{row.last_chat.chat_message} </Text>
</View>
</View>
</View>
</View>
</TouchableOpacity>
)
}
_rowHasChanged(r1, r2) {
return r1 !== r2
}
highlightRow() {
alert('Hi!');
}
}
const styles = StyleSheet.create({
container:{
alignItems:'center',
padding:10,
flexDirection:'row',
borderBottomWidth:1,
borderColor:'#f7f7f7',
backgroundColor: '#fff'
},
groupChatContainer:{
display: 'flex',
flexDirection: 'row',
},
groupNameText:{
marginLeft:15,
fontWeight:'600',
marginTop: -8,
color: '#000'
},
groupUpdatedAtText :{
color:'#333', fontSize:10, marginTop: -5
},
groupChatThumbnail:{
borderRadius: 30,
width: 50,
height: 50 ,
alignItems:'center'
},
groupUpdatedByText:{
fontWeight:'400', color:'#333',
marginLeft:15, marginRight:5
},
});
There are two ways to access navigation props on second screen:
Inside like
navigationOptions = ({navigation}) => ({title:`${navigation.state.params.name}`});
If you access inside any method like render etc is
{user}= this.props.navigation.state.params
ChatList.navigationOptions this could written be as
ChatList.navigationOptions= ({navigation}) => ({// props access here });
and const ChatList = () inside this you can write this.props.navigation.state.params
I have a component for listing items, I want to add the function that can go to a different page, and that page has the detail about that item. Currently, this is my code for listing items.
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import axios from 'axios';
import CarDetail from './CarDetail';
const API_URL = 'http://localhost:3000';
class CarList extends Component {
state = { cars: [] };
componentWillMount() {
console.log('Mount');
axios.get(`${API_URL}/cars`)
.then(response => this.setState({ cars: response.data.cars }));
}
renderCars() {
return this.state.cars.map(car => <CarDetail key={car.id} car={car} />
);
}
render() {
console.log(this.state.cars);
return (
<ScrollView>
{this.renderCars()}
</ScrollView>
);
}
}
export default CarList;
and this is the code for describing items
import React from 'react';
import { Text, View, Image } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Card from '../material/Card';
import CardSection from '../material/CardSection';
const CarDetail = ({ car }) => {
const imageURI = 'https://yt3.ggpht.com/-HwO-2lhD4Co/AAAAAAAAAAI/AAAAAAAAAAA/p9WjzQD2-hU/s900-c-k-no-mo-rj-c0xffffff/photo.jpg';
const { make, model } = car;
function showCarDetail() {
Actions.showCar();
}
return (
<Card>
<CardSection>
<View style={styles.containerStyle}>
<Image
style={styles.imageStyle}
source={{ uri: imageURI }}
/>
</View>
<View style={styles.headContentStyle}>
<Text
style={styles.headerTextStyle}
onPress={showCarDetail()}
>
{make}
</Text>
<Text>{model}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={styles.picStyle}
source={require('./car.jpg')}
/>
</CardSection>
</Card>
);
};
const styles = {
headContentStyle: {
flexDirection: 'column',
justifyContent: 'space-around'
},
headerTextStyle: {
fontSize: 18
},
imageStyle: {
height: 50,
width: 50
},
containerStyle: {
justifyContent: 'center',
alignItems: 'center',
marginLeft: 10,
marginRight: 10
},
picStyle: {
height: 300,
flex: 1,
width: null
}
};
export default CarDetail;
How can I change my code for that? Can anyone give me an example?
You have to use some sort of navigation component. There are many out there, but personally I use the one that is built into React Native. https://facebook.github.io/react-native/docs/navigator.html