I have item that are in array. I want to change the line after setting the first item and so on. I am getting the values in a row. But I want it in column. I am getting value as:
015245088 9823178404 9851108404
But I want value as:
015245088
9823178404
9823178404
I have implemented as follows:
this.state = {
contact: [
{
id: 0,
name: '015245088'
},
{
id: 1,
name: '9823178404'
},
{
id: 2,
name: '9851108404'
}
]
}
<CardSection>
<FontAwesomeIcon style={styles.contentStyle} icon={faPhone} />
{
this.state.contact.map((item, index) => (
<TouchableOpacity
key={item.id}
style={styles.opacityStyle}
onPress={()=>Linking.openURL(`tel:${item.name}`)}>
<Text style={styles.contactStyle}>{item.name} </Text>
</TouchableOpacity>
))
}
</CardSection>
this.state = {
contact: [
{
id: 0,
name: '015245088'
},
{
id: 1,
name: '9823178404'
},
{
id: 2,
name: '9851108404'
}
]
}
<CardSection>
<FontAwesomeIcon style={styles.contentStyle} icon={faPhone} />
<View style={{flexDirection:'column'}}>
{
this.state.contact.map((item, index) => (
<TouchableOpacity
key={item.id}
style={styles.opacityStyle}
onPress={()=>Linking.openURL(`tel:${item.name}`)}>
<Text style={styles.contactStyle}>{item.name} </Text>
</TouchableOpacity>
}
</View>
</CardSection>
You need to change the flexDirection to column.
So, Just add the following styles to styles.contentStyle. Or wrap your map function with a View and add the following styles to it.
flexDirection: 'column'
flex: 1
Related
First of all, sorry about my bad English. I'm having an issue that when I click on one location, it will show the "Checked" text on the corner, but when I click on another location, it will show the "checked" like the first, but the first "Checked" one reset to "not check", so how to keep the first result?
Here is my code:
export default function App() {
const [selectedId, setSelectedId] = useState(null)
const renderView = ({item}) => (
<TouchableOpacity onPress={() => setSelectedId(item.id) }
style={{
marginBottom:15,
marginHorizontal:7,
width:'46%',
height:200,
}}>
<Image style={{width:'100%',height:'100%', borderRadius:20,}} source={{uri:item.image}}/>
<Text style={{position:'absolute',bottom:0,padding:15,color:'yellow', fontWeight:'bold'}}>{item.title}</Text>
<View style={{
position:'absolute',
right:0,
padding:15,
}}>
{
item.id === selectedId?<Text style={{fontWeight:'bold',color:'red'}}>Checked</Text>:<Text style={{fontWeight:'bold',color:'red'}}>Not check</Text>
}
</View>
</TouchableOpacity>
)
return (
<SafeAreaView style={styles.container}>
<View style={styles.top}>
<View style={{
height:44,
width:44,
backgroundColor:'green',
alignItems:'center',
justifyContent:'center',
borderRadius:30,
}}>
<Text style={{fontSize:25,color:'white'}}>=</Text>
</View>
<Text style={{fontSize:25,color:'blue',fontWeight:'bold'}}>Packages</Text>
<View style={{
height:44,
width:44,
backgroundColor:'green',
alignItems:'center',
justifyContent:'center',
borderRadius:30,
}}>
<Text style={{fontSize:25,color:'white'}}>#</Text>
</View>
</View>
<View style={{
marginVertical:10,
flex:1,
paddingHorizontal: 15
}}>
<FlatList
data = {DATA}
showsVerticalScrollIndicator={false}
numColumns={2}
renderItem={renderView}
keyExtractor={(item,index) => index.toString()}
/>
</View>
</SafeAreaView>
)
}
const DATA = [
{
id: 1,
image: 'https://c0.wallpaperflare.com/preview/298/610/503/vietnam-ho-chi-minh-city-cityscape-dusk-thumbnail.jpg',
title: 'Ho Chi Minh city',
},
{
id: 2,
image: 'https://c0.wallpaperflare.com/preview/582/203/631/ha-noi-city-vietnam-lake-thumbnail.jpg',
title: 'Ha Noi city',
},
{
id: 3,
image: 'https://media.istockphoto.com/photos/sunny-beach-in-the-pearl-island-of-phu-quoc-vietnam-picture-id1307905856?b=1&k=20&m=1307905856&s=170667a&w=0&h=MMd7neh6NOOxeUUlo6eCeU49vWp7HhQXtgTw0VNjogo=',
title: 'Phu Quoc island',
},
{
id: 4,
image: 'https://media.istockphoto.com/photos/panorama-of-the-city-of-nha-trang-in-vietnam-from-drone-point-of-view-picture-id827359312?k=20&m=827359312&s=612x612&w=0&h=4QigU_O-sGaDhuFBOS_K66A4cXxc5IUoT4NrbsPw7Oo=',
title: 'Nha Trang city',
},
{
id: 5,
image: 'https://c0.wallpaperflare.com/preview/298/610/503/vietnam-ho-chi-minh-city-cityscape-dusk-thumbnail.jpg',
title: 'Ho Chi Minh city',
},
{
id: 6,
image: 'https://c0.wallpaperflare.com/preview/582/203/631/ha-noi-city-vietnam-lake-thumbnail.jpg',
title: 'Ha Noi city',
},
{
id: 7,
image: 'https://media.istockphoto.com/photos/sunny-beach-in-the-pearl-island-of-phu-quoc-vietnam-picture-id1307905856?b=1&k=20&m=1307905856&s=170667a&w=0&h=MMd7neh6NOOxeUUlo6eCeU49vWp7HhQXtgTw0VNjogo=',
title: 'Phu Quoc island',
},
{
id: 8,
image: 'https://media.istockphoto.com/photos/panorama-of-the-city-of-nha-trang-in-vietnam-from-drone-point-of-view-picture-id827359312?k=20&m=827359312&s=612x612&w=0&h=4QigU_O-sGaDhuFBOS_K66A4cXxc5IUoT4NrbsPw7Oo=',
title: 'Nha Trang city',
},
]
You are storing checkedId in your checked component and it rerenders every time one more is checked, it goes to default. You can add isChecked property to your data, it will be false as default. And you just change it to true on press.
This is how you data will look:
const DATA = [
{
id: 1,
image: 'https://c0.wallpaperflare.com/preview/298/610/503/vietnam-ho-chi-minh-city-cityscape-dusk-thumbnail.jpg',
title: 'Ho Chi Minh city',
isChecked:false,
},
{
id: 2,
image: 'https://c0.wallpaperflare.com/preview/582/203/631/ha-noi-city-vietnam-lake-thumbnail.jpg',
title: 'Ha Noi city',
isChecked:false,
}]
You will is element checked based on your data state. And you will have onPress function. You will store you data in use State.
const handlePress=(id)=>{
let arr=data;
arr.map((item)=>{
if(item.id===id){
item.isChecked=!item.isChecked
}
//here you will just set you data to arr
setData(arr)
})
}
I'm trying to figure out how to use const objects to create 3 categories in my trivia game. I'm defining each one of them like this:
const questions = [
{
question: "Qual o tipo de arquitetura utilizada na Igreja da Madre de Deus?",
answers: [
{ id: "1", text: "Colonial" },
{ id: "2", text: "Maneirista" },
{ id: "3", text: "Gótico" },
{ id: "4", text: "Barroco", correct: true }
]
},
{
question: "No século XIX, o pintor que pintou os painéis da igreja foi:",
answers: [
{ id: "1", text: "Sebastião Canuto da Silva Tavares", correct: true },
{ id: "2", text: "Frans Janszoon Post" },
{ id: "3", text: "Oscar Pereira da Silva" },
{ id: "4", text: "João de Deus Sepúlveda" }
],
quiz_answer: "Esse é o cara!"
}
]
export default questions;
There is a file called IndexQuiz, where I'm calling them through a menu of categories (inside TouchableOpacity):
export default ({ navigation }) => (
<ScrollView>
<SafeAreaView style={{alignItems: "center", flexDirection: "column"}}>
<TouchableOpacity onPress={() =>
navigation.navigate("Quiz", {
title: "Arquitetura",
questions: arquitetura,
color: "rgb(32, 53, 70)"
})}
style={DesafiosStyles.cardContainer}>
</TouchableOpacity>
<TouchableOpacity onPress={() =>
navigation.navigate("Quiz", {
title: "Curiosidades",
questions: curiosidades,
color: "rgb(32, 53, 70)"
})}
style={DesafiosStyles.cardContainer}>
</TouchableOpacity>
<TouchableOpacity onPress={() =>
navigation.navigate("Quiz", {
title: "História",
questions: historia,
color: "rgb(32, 53, 70)"
})}
style={DesafiosStyles.cardContainer}>
</TouchableOpacity>
</SafeAreaView>
</ScrollView>
);
But when it comes to the Quiz file, inside render I have this:
render() {
const questions = this.props.route.params.questions.length;
const question = questions[this.state.activeQuestionIndex];
//console.log(question);
return (
<View
style={[
styles.container,
{ backgroundColor: this.props.route.params.color }
]}
>
<StatusBar barStyle="light-content" />
<SafeAreaView style={styles.safearea}>
<View>
<Text style={styles.text}>{question.question}</Text>
<ButtonContainer>
{answers.map(answer => (
<Button
key={answer.id}
text={answer.text}
onPress={() => this.answer(answer.correct)}
/>
))}
</ButtonContainer>
</View>
<Text style={styles.text}>
{`${this.state.correctCount}/${this.state.totalCount}`}
</Text>
</SafeAreaView>
<Alert
correct={this.state.answerCorrect}
visible={this.state.answered}
/>
</View>
);
}
Every time I try to call any of these categories, I got the "undefined is not an object" exception. I've tried to import the files and the "questions" const itself, but it didn't work. As simple as that must be, I'm stuck in this (yep, I'm kinda slow and basically a newbie with react native lol):
<Text style={styles.text}>{question.question}</Text>
<ButtonContainer>
{answers.map(answer => (
<Button
key={answer.id}
text={answer.text}
onPress={() => this.answer(answer.correct)}
/>
))}
</ButtonContainer>
Without this code, it shows the counter: "this.state.correctCount}/${this.state.totalCount", but that's all. How can I call these questions and answers properly?
I think the problem is that you try to get questions from length property, not from questions object itself:
const questions = this.props.route.params.questions.length;
const question = questions[this.state.activeQuestionIndex];
I'm displaying a list of items on a page which i provide users the ability to delete.
With my code when the users taps on delete i get this error
undefined is not an object (evaluating this.state.myGroups)
JS
handleExistGroup(item) {
var array = [...this.state.myGroups];
var index = array.indexOf(item.target.value)
if (index !== -1) {
array.splice(index, 1);
this.setState({myGroups: array});
}
}
Array
state = {
myGroups : [
{
name: 'Karate Group',
description: 'Test Group',
icon: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg'
},
{
name: 'Choir Group',
description: 'Test 2',
icon: 'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg'
}
]
}
VIEW
<View style={styles.container}>
<ScrollView >
{
groupList.map((item, i) => {
return (
<View key={i} style={styles.user}>
<Card >
<ListItem
roundAvatar
title={item.name}
avatar={{uri:'https://s3.amazonaws.com/uifaces/faces/twitter/brynn/128.jpg'}}
/>
<View>
<Button
containerViewStyle={{width:'50%', alignSelf:'flex-end', position:"absolute", top:0, right:-25}}
onPress={()=>(handleExistGroup(item))}
rounded = {true}
style={{margin:10}}
icon={{name: 'trash'}}
backgroundColor='#DC143C'
buttonStyle={{borderRadius: 0, marginLeft: 0, marginRight: 0, marginBottom: 0}}
title='Exit Group'
/>
</View>
<Text style={{alignSelf:'center', padding:5, fontFamily:'HelveticaNeue-Light', fontSize:16}}>
Jonied: 24th January, 2019
</Text>
</Card>
</View>
);
})
}
</ScrollView>
</View>
How do i make it work so it can delete the particular row a use want to delete from the array?
You need to bind handleExistGroup() function with this in your constructor.
constructor(props) {
super(props);
this.handleExistGroup = this.handleExistGroup.bind(this);
}
I want to display the FlatList that I created. I want to show the title and artist that is in my data. There is no error but my output would not appear anything.
This is my data:
var track =
[
{ List: 'list1',
data:
[
{id: '1', url: 'http://tegos.kz/new/mp3_full/Luis_Fonsi_feat._Daddy_Yankee_-_Despacito.mp3',title: 'Despacito',artist:'Luis Fonsi'},
{id: '2', url: 'http://tegos.kz/new/mp3_full/5_Seconds_Of_Summer_-_Youngblood.mp3',title: 'YoungBlood',artist:'5SOS'},
]
},
{ List: 'list2',
data:
[
{id: '1111', url: 'http://tegos.kz/new/mp3_full/Yellow_Claw_and_San_Holo_-_Summertime.mp3',title: 'Summertime',artist:'Yelow Claw'},
{id: '2222', url: 'http://tegos.kz/new/mp3_full/Post_Malone_-_Better_Now.mp3',title: 'Better Now',artist:'Post Malone'},
]},
];
module.exports = {track:track};
And this is my FlatList:
export default class SongList extends Component{
render(){
const { navigate } = this.props.navigation;
return(
<View>
<FlatList
data={track}
renderItem={({item,index})=>{
return(
<FlatListItem item={item} index={index}>
</FlatListItem>);
}}
>
</FlatList>
</View>
);
}
}
class FlatListItem extends Component{
render(){
return(
<View style={styles.list}>
<View>
<Text style={styles.itemTitle}>{this.props.item.title}</Text>
<Text style={styles.itemArtist}>{this.props.item.artist}</Text>
</View>
</View>
);
}
}
Basically I am able to run the program. But there is nothing showing up on the screen. There is only a blank background.
const styles = StyleSheet.create({
itemArtist:{
textAlign: 'center',
justifyContent: 'center',
fontSize: 23,
borderBottomWidth: 4,
borderBottomColor: '#ccc',
marginTop: 10,
padding: 10,
color: 'blue',
},
itemTitle:{
textAlign: 'center',
justifyContent: 'center',
fontSize: 23,
borderBottomWidth: 4,
borderBottomColor: '#ccc',
marginTop: 10,
padding: 10,
color: 'blue',
},
list:{
flex:1,
}
You should write your code as below:
Your data:
export default [
{
List: 'list1',
data: [
{
id: '1',
url: 'http://tegos.kz/new/mp3_full/Luis_Fonsi_feat._Daddy_Yankee_-_Despacito.mp3',
title: 'Despacito',
artist: 'Luis Fonsi',
},
{
id: '2',
url: 'http://tegos.kz/new/mp3_full/5_Seconds_Of_Summer_-_Youngblood.mp3',
title: 'YoungBlood',
artist: '5SOS',
},
],
},
{
List: 'list2',
data: [
{
id: '1111',
url: 'http://tegos.kz/new/mp3_full/Yellow_Claw_and_San_Holo_-_Summertime.mp3',
title: 'Summertime',
artist: 'Yelow Claw',
},
{
id: '2222',
url: 'http://tegos.kz/new/mp3_full/Post_Malone_-_Better_Now.mp3',
title: 'Better Now',
artist: 'Post Malone',
},
],
},
];
Import your data like this, I assume the data file and your code are in a same folder:
import track from './data';
Your components:
export default class App extends Component {
render() {
const { navigate } = this.props.navigation;
return (
<View>
<FlatList
data={track}
renderItem={({ item, index }) => {
return <FlatListItem item={item} index={index} />;
}}
/>
</View>
);
}
}
class FlatListItem extends Component {
render() {
return (
<View style={styles.list}>
<View>
<Text style={styles.itemTitle}>{this.props.item.data[0].title}</Text>
<Text style={styles.itemArtist}>{this.props.item.data[0].artist}</Text>
</View>
<View>
<Text style={styles.itemTitle}>{this.props.item.data[1].title}</Text>
<Text style={styles.itemArtist}>{this.props.item.data[1].artist}</Text>
</View>
</View>
);
}
}
And if you want to show only the data of list1 in your FlatList you should change your code as below:
export default class App extends Component {
render() {
const { navigate } = this.props.navigation;
return (
<View>
<FlatList
data={track[0].data}
renderItem={({ item, index }) => {
return <FlatListItem item={item} index={index} />;
}}
/>
</View>
);
}
}
class FlatListItem extends Component {
render() {
return (
<View style={styles.list}>
<View>
<Text style={styles.itemTitle}>{this.props.item.title}</Text>
<Text style={styles.itemArtist}>{this.props.item.artist}</Text>
</View>
</View>
);
}
}
You can make your data schema better to show them better too.
Steps to debug :-
try to console track, check if data is coming properly.
add console in componentDidMount and check if item if coming there or not.
Add keyExtractor in flatlist, keyExtractor tells the list to use the ids for the react keys instead of the default key property.
<FlatList
data={track}
keyExtractor={(item, index) => ""+index}
renderItem={({ item, index }) => {
return <FlatListItem item={item} index={index} />;
}}
/>
renderAvail(user, sectionId, rowId, highlightRow){
return(
<ImageBackground source={require('../../../asset/available_card_medium.png')} style={styles.containerA}>
if(user.type == 'Wear'){
return(
<Image
source={require('../../../icon.png')}
resizeMode = 'cover' style={styles.thumbImage}>)
}
<View style={styles.body}>
<Text style={styles.message1}>{user.desc}</Text>
<Text style={styles.message1}>+{user.points} <Image source={require('../../../icon_large.png')} resizeMode ='contain' style ={{height:50,width:60}}/></Text>
</View>
<ImageButton
appearance={{
normal: require("../../../asset/btn.png"),
highlight: require("../../../asset/btn2.png")}}
onPress={ this.onPressButton }/>
</ImageBackground>
);
}
{
id: 0,
type: 'Survey',
desc: 'Keep Your Apple Watch on for 8 Hours Today',
title: 'Test1',
date: '09/06/2018',
},
{
id: 1,
type: 'Wear',
desc: 'Keep Your Apple Watch on for 8 Hours Today',
title: 'Test1',
date: '09/06/2018',
},
{
id: 2,
type: 'meal',
desc: 'Keep Your Apple Watch on for 8 Hours Today',
title: 'Test1',
date: '09/06/2018',
},
{
id: 3,
type: 'Survey',
desc: 'Keep Your Apple Watch on for 8 Hours Today',
title: 'Test1',
date: '09/06/2018',
},
{
id: 4,
type: 'Wear',
desc: 'Keep Your Apple Watch on for 8 Hours Today',
title: 'Test1',
date: '09/06/2018',
}
];
You cant return use return directly inside a return block because it will be already returned if condition meets. instead of above code, you can use this.
return (<ImageBackground source={require('../../../asset/available_card_medium.png')} style={styles.containerA}>
{user.type == 'Wear' && <Image
source={require('../../../icon.png')}
resizeMode='cover' style={styles.thumbImage}>)
}
<View style={styles.body}>
<Text style={styles.message1}>{user.desc}</Text>
<Text style={styles.message1}>+{user.points} <Image source={require('../../../icon_large.png')} resizeMode='contain' style={{ height: 50, width: 60 }} /></Text>
</View>
<ImageButton
appearance={{
normal: require("../../../asset/btn.png"),
highlight: require("../../../asset/btn2.png")
}}
onPress={this.onPressButton} />
</ImageBackground>
);
Going through your code i can understand that you are new to react native.
As #Ranvir Gorai answered previously, you can not use if statement inside a render(). please spare some time and go through JSX elements.
Assuming you are calling a function renderAvail() from render of a class.
import React from 'react';
import {
View,
Text,
// add other elements which are used.
} from 'react-native';
export default class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
user:'some data',
sectionId:'some data',
rowId: 'some data',
highlightRow: 'some data',
}
}
// add the data to state using this.setState({key,value});
renderAvail() {
return (
<ImageBackground source={require('../../../asset/available_card_medium.png')} style={styles.containerA}>
{user.type == 'Wear' && <Image
source={require('../../../icon.png')}
resizeMode='cover' style={styles.thumbImage}>)
}
<View style={styles.body}>
<Text style={styles.message1}>{user.desc}</Text>
<Text style={styles.message1}>+{user.points} <Image source={require('../../../icon_large.png')} resizeMode='contain' style={{ height: 50, width: 60 }} /></Text>
</View>
<ImageButton
appearance={{
normal: require("../../../asset/btn.png"),
highlight: require("../../../asset/btn2.png")
}}
onPress={this.onPressButton} />
</ImageBackground>
);
}
render() {
return (
{this.renderAvail(this.state.user, this.state.sectionId, this.state.rowId, this.state.highlightRow)}
);
}
}