Related
I'm using a flatlist with rowNumber={4} and I want to display some elements with a Width-max.
But I got this result :
As you can see some elements protrude on the left side. How can I make it fit automatically ?
Expected result :
There is my code :
<SafeAreaView>
<View
style={{
height: "100%",
maxWidth: "100%",
right: "10%",
}}
>
<FlatList
style={{width: "120%"}}
data={brands}
numColumns={4}
keyExtractor={(_, item) => item}
renderItem={({item}) => (
<View style={styles.card} key={item["id"]}>
<TouchableOpacity
onPress={() => {
var index = brandId.indexOf(item["id"]);
if (index > -1) {
brandId.splice(index, 1);
cpt = cpt - 1;
} else {
brandId.push(item["id"]);
cpt = cpt + 1;
}
console.log("ici ! ", cpt);
console.log("Il existe deja bro", brandId);
}}
>
<Text style={styles.text}>{item["name"]}</Text>
</TouchableOpacity>
</View>
)}
/>
</View>
</SafeAreaView>
CSS :
card: {
height: 30,
justifyContent: "center",
backgroundColor: "#E4E4E4",
margin: 5,
borderRadius: 10,
},
text: {
paddingRight: "2%",
textAlign: "center",
width: "100%",
fontSize: 12,
color: "black",
},
don't use flatlist. with flatlist you will always have fixed numberOfColumns but your item widths could be diff from each other. use map instead inside scrollview.
updated code :
<View style={[{ flexDirection: 'row', flexWrap: 'wrap' }]}>
{brands.map(element => {
return <View style={styles.card}>
<Text>{element.name}</Text>
</View>
})
}
</View>
styles:
card: {
height: 30,
justifyContent: "center",
backgroundColor: "#E4E4E4",
margin: 5,
borderRadius: 10,
paddingHorizontal: 5
},
Modify style of card:
card: {
flex:1,
flexDirection:"row"
height: 30,
justifyContent: "center",
backgroundColor: "#E4E4E4",
margin: 5,
borderRadius: 10,
},
or If you don't use flatlist then below code will solve your issue:
<View style={[{flexDirection: 'row', flexWrap: ' wrap'}]}>
data.map(element => {
return <Text style={{height:100}}>element.content</Text>
})
</View>
I'm new to React native, I'm creating a online store app my problem is : when the person selects a repeated item it does not appear in the cart it just updates , I would like it to include and list in the cart this repeated item ... as I said I'm new to react native, but I believe the problem is in the listing and not in the register ...
Function add in cart in AddCart.js
const addToCart = async (id) => {
let itemArray = await AsyncStorage.getItem('cartItems');
itemArray = JSON.parse(itemArray);
if (itemArray) {
let array = itemArray;
array.push(id);
try {
await AsyncStorage.setItem('cartItems', JSON.stringify(array));
ToastAndroid.show(
'Item Added Successfully to cart',
ToastAndroid.SHORT,
);
navigation.navigate('Home');
} catch (error) {
return error;
}
} else {
let array = [];
array.push(id);
try {
await AsyncStorage.setItem('cartItems', JSON.stringify(array));
ToastAndroid.show(
'Item Added Successfully to cart',
ToastAndroid.SHORT,
);
navigation.navigate('Home');
} catch (error) {
return error;
}
}
};
MyCart.js
import React, {useState, useEffect} from 'react';
import {
View,
Text,
TouchableOpacity,
Image,
Alert
} from 'react-native';
import AsyncStorage from '#react-native-async-storage/async-storage';
const MyCart = ({navigation}) => {
const [product, setProduct] = useState();
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
getDataFromDB();
});
return unsubscribe;
}, [navigation]);
const getDataFromDB = async id =>{
let items = await AsyncStorage.getItem('cartItems');
items = JSON.parse(items);
if(items.length===0){
Alert.alert(
"Ops",
"The cart is empty",
[
{
text: "Ok",
onPress: () => navigation.navigate('Home'),
style: "cancel"
}
]
);
}else{
let productData = [];
if (items) {
Items.forEach(data => {
if (items.includes(data.id)) {
productData.push(data);
return;
}
});
setProduct(productData);
getTotal(productData);
} else {
setProduct(false);
getTotal(false);
}
}
};
const renderProducts = (data, index) => {
return (
<TouchableOpacity
key={data.key}
onPress={() => navigation.navigate('ProductInfo', {productID: data.id})}
style={{
width: '100%',
height: 100,
marginVertical: 6,
flexDirection: 'row',
alignItems: 'center',
}}>
<View
style={{
width: '30%',
height: 100,
padding: 14,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: COLOURS.backgroundLight,
borderRadius: 10,
marginRight: 22,
}}>
<Image
source={data.productImage}
style={{
width: '100%',
height: '100%',
resizeMode: 'contain',
}}
/>
</View>
<View
style={{
flex: 1,
height: '100%',
justifyContent: 'space-around',
}}>
<View style={{}}>
<Text
style={{
fontSize: 14,
maxWidth: '100%',
color: COLOURS.black,
fontWeight: '600',
letterSpacing: 1,
}}>
{data.productName},
</Text>
<View
style={{
marginTop: 4,
flexDirection: 'row',
alignItems: 'center',
opacity: 0.6,
}}>
<Text
style={{
fontSize: 14,
fontWeight: '400',
maxWidth: '85%',
marginRight: 4,
}}>
R$ {data.productPrice2}.00 , {data.id}
</Text>
<Text>
</Text>
</View>
</View>
<View
style={{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}}>
<View
style={{
flexDirection: 'row',
alignItems: 'center',
}}>
<View
style={{
borderRadius: 100,
marginRight: 20,
padding: 4,
borderWidth: 1,
borderColor: COLOURS.backgroundMedium,
opacity: 0.5,
}}>
<MaterialCommunityIcons
name="minus"
style={{
fontSize: 16,
color: COLOURS.backgroundDark,
}}
/>
</View>
<Text>1</Text>
<View
style={{
borderRadius: 100,
marginLeft: 20,
padding: 4,
borderWidth: 1,
borderColor: COLOURS.backgroundMedium,
opacity: 0.5,
}}>
<MaterialCommunityIcons
name="plus"
style={{
fontSize: 16,
color: COLOURS.backgroundDark,
}}
/>
</View>
</View>
<TouchableOpacity onPress={() => removeItemFromCart(data.id)}>
<MaterialCommunityIcons
name="delete-outline"
style={{
fontSize: 16,
color: COLOURS.backgroundDark,
backgroundColor: COLOURS.backgroundLight,
padding: 8,
borderRadius: 100,
}}
/>
</TouchableOpacity>
</View>
</View>
</TouchableOpacity>
);
};
return (
<View> {product ? product.map(renderProducts) : null} </View>
);
};
export default MyCart;
I would be grateful to help me
I am trying to use an icon "ic_shuffle_white.png" and the image is clearly in my directory, so I am not sure why I am getting the "Unable to resolve..." error.
I restarted my Xcode after adding the pngs, imported Image from react-native, and there does not appear to be a syntax error.
I am following this guide: https://hackernoon.com/building-a-music-streaming-app-using-react-native-6d0878a13ba4
Is it because I am using expo? or is the guide too old?
Screenshot:
Code:
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
Image,
TouchableOpacity,
} from 'react-native';
const Controls = ({
paused,
shuffleOn,
repeatOn,
onPressPlay,
onPressPause,
onBack,
onForward,
onPressShuffle,
onPressRepeat,
forwardDisabled,
}) => (
<View style={styles.container}>
<TouchableOpacity activeOpacity={0.0} onPress={onPressShuffle}>
<Image style={[styles.secondaryControl, shuffleOn ? [] : styles.off]}
source={require('../img/ic_shuffle_white.png')}/>
</TouchableOpacity>
<View style={{width: 40}} />
<TouchableOpacity onPress={onBack}>
<Image source={require('../img/ic_skip_previous_white_36pt.png')}/>
</TouchableOpacity>
<View style={{width: 20}} />
{!paused ?
<TouchableOpacity onPress={onPressPause}>
<View style={styles.playButton}>
<Image source={require('../img/ic_pause_white_48pt.png')}/>
</View>
</TouchableOpacity> :
<TouchableOpacity onPress={onPressPlay}>
<View style={styles.playButton}>
<Image source={require('../img/ic_play_arrow_white_48pt.png')}/>
</View>
</TouchableOpacity>
}
<View style={{width: 20}} />
<TouchableOpacity onPress={onForward}
disabled={forwardDisabled}>
<Image style={[forwardDisabled && {opacity: 0.3}]}
source={require('../img/ic_skip_next_white_36pt.png')}/>
</TouchableOpacity>
<View style={{width: 40}} />
<TouchableOpacity activeOpacity={0.0} onPress={onPressRepeat}>
<Image style={[styles.secondaryControl, repeatOn ? [] : styles.off]}
source={require('../img/ic_repeat_white.png')}/>
</TouchableOpacity>
</View>
);
export default Controls;
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
paddingTop: 8,
},
playButton: {
height: 72,
width: 72,
borderWidth: 1,
borderColor: 'white',
borderRadius: 72 / 2,
alignItems: 'center',
justifyContent: 'center',
},
secondaryControl: {
height: 18,
width: 18,
},
off: {
opacity: 0.30,
}
})
Cannot figure out why I keep getting a ReferenceError cant find variable MarkAsRead for a mobile app I am building in react. Unless I am missing something the variable has been assigned below is the code for your reference. Hopefully, someone can help me get this bug resolved in a timely matter thanks in advance!
import React from 'react';
import { View,
Text,
StyleSheet,
SafeAreaView,
TouchableOpacity,
TextInput,
FlatList
} from 'react-native';
import BookCount from './components/BookCount';
import {Ionicons} from '#expo/vector-icons';
class App extends React.Component {
constructor() {
super()
this.state = {
totalCount: 0,
readingCount: 0,
readCount: 0,
isAddNewBookVisible:false,
textInputData: '',
books: [],
bookData: {
author: '',
publisher: ''
}
};
}
showAddNewBook = () => {
this.setState({isAddNewBookVisible:true});
};
hideAddNewBook = () => {
this.setState({isAddNewBookVisible:false})
};
addBook = book => {
this.setState(
(state, props) => ({
books: [...state.books, book],
totalCount: state.totalCount + 1,
readingCount:state.readingCount + 1,
isAddNewBookVisible: false
}),
() => {
console.log(this.state);
}
);
};
markAsRead = (selectedBook, index) => {
let newList = this.state.books.filter(book => book !==
selectedBook);
this.setState(prevState => ({
books: newList,
readingCount: prevState.readingCount - 1,
readCount: prevState.readCount + 1
}));
};
renderItem = (item, index) => (
<View style={{ height:50, flexDirection: 'row'}}>
<View style={{ flex:1, justifyContent: 'center', paddingLeft: 5
}}>
<Text>{item}</Text>
</View>
<TouchableOpacity onPress={() => markAsRead(item,index)} >
<View
style={{
width: 100,
height: 50,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#160b1a'
}}
>
<Text style={{ fontWeight: 'bold', color: 'white'}}>Mark as Read</Text>
</View>
</TouchableOpacity>
</View>
);
render() {
return (
<View style={{flex: 1}}>
<SafeAreaView/>
<View style={{
height: 70,
borderBottomWidth: 0.5,
borderBottomColor: '#5e3c7d',
alignItems: 'center',
justifyContent: 'center'
}}
>
<Text style={{fontSize: 24}}>VekTorfy AI</Text>
</View>
<View style={{ flex: 1}}>
{this.state.isAddNewBookVisible &&
<View style={{height:50, flexDirection: 'row'}}>
<TextInput
onChangeText={(text)=>this.setState({textInputData:text})}
style={{ flex:1, backgroundColor: '#c6c0cb',
paddingLeft: 5}}
placeholder='Enter book name.'
placeholderTextColor='black'
/>
<TouchableOpacity
onPress={() => this.addBook(this.state.textInputData)} >
<View style={{
width: 50,
height: 50,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#160b1a'}}>
<Ionicons name ='ios-checkmark' color='white' size={40}/>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={this.hideAddNewBook}>
<View style={{
width: 50,
height: 50,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#160b1a'}}>
<Ionicons name ='ios-close' color='red' size={40}/>
</View>
</TouchableOpacity>
</View>
}
<FlatList
data={this.state.books}
renderItem={({item}, index) => this.renderItem(item, index)}
keyExtractor={(item, index)=> index.toString()}
ListEmptyComponent={
<View style={{marginTop: 50, alignItems: 'center'}}>
<Text style={{fontWeight: 'bold'}}>Not Reading anything.</Text>
</View>
}
/>
<TouchableOpacity
onPress={this.showAddNewBook}
style={{position: 'absolute', bottom: 20, right: 20}}>
<View
style={{
width:50,
heght:50,
alignItems: 'center',
justifyContent: 'center',
borderRadius:25,
backgroundColor: '#2d2337'}}>
<Text style={{color: 'white', fontSize: 30}}>+</Text>
</View></TouchableOpacity>
</View>
<View
style={{
height: 70,
flexDirection: 'row',
borderTopWidth: 0.5,
borderTopColor: '#5e3c7d' }}>
<BookCount title='Total' count={this.state.totalCount}/>
<BookCount title='Reading' count={this.state.readingCount}/>
<BookCount title='Read' count={this.state.readCount}/>
</View>
<SafeAreaView/>
</View>
);
}
}
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
You forgot to add the keyword this to your function call.
<TouchableOpacity onPress={() => this.markAsRead(item,index)}>
It looks like you have declared markAsRead as a method on your App class, so the correct way to refer to it is this.markAsRead()
<TouchableOpacity onPress={() => this.markAsRead(item, index)}>
hope all is well.
I seem to be having difficulty with a basic button functionality. All I need is the state of the class to change and the button style to change every-time the button is pressed. Unlike TouchableHighlight, I need to color change to stay until the button is pressed again (to go back to the original color).
I have tried to use SwitchIOS but it doesn't seem to be easily styled into a circular button, and therefore doesn't really work out. I am a novice so still learning and would greatly appreciate your help. Here is what I have so far:
'use strict';
var React = require('react-native');
var Dimensions = require('Dimensions');
var window = Dimensions.get('window');
var Icon = require('react-native-vector-icons/FontAwesome');
var {
AppRegistry,
StyleSheet,
Text,
View,
NavigatorIOS,
Image,
TouchableHighlight,
TextInput,
} = React;
class LS1 extends React.Component{
constructor(props){
super(props);
this.state = {
paleo: false,
vegan: false,
vegetarian: false,
nutfree: false,
dairyfree: false,
healthy: false,
glutenfree: false,
}
}
SkipLogin() {
var num = window.height/8.335;
console.log(num);
}
render() {
return (
<View style={styles.container}>
<Image source={require('image!LS1')} style={styles.bgImage}>
<Text style={styles.icontext}>Help us get to know your dietary lifestyle.</Text>
<View style={styles.container}>
<View style={{flex: 1, alignItems: 'center', flexDirection: 'row',justifyContent: 'center',marginTop:-20}}>
<TouchableHighlight underlayColor='rgba(73,182,77,1,0.9)' style={styles.bubblechoice}>
<Image style={styles.bubblechoice} source={require('image!vegan')}>
<View style={styles.overlay}>
<Text style={styles.choicetext}>Vegan</Text>
</View>
</Image>
</TouchableHighlight>
<TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
<Image style={styles.bubblechoice} source={require('image!paleo')}>
<View style={styles.overlay}>
<Text style={styles.choicetext}>Paleo</Text>
</View>
</Image>
</TouchableHighlight>
<TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
<Image style={styles.bubblechoice} source={require('image!nutfree')}>
<View style={styles.overlay}>
<Text style={styles.choicetext}>Nut-Free</Text>
</View>
</Image>
</TouchableHighlight>
<TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
<Image style={styles.bubblechoice} source={require('image!glutenfree')}>
<View style={styles.overlay}>
<Text style={styles.choicetext}>Gluten-Free</Text>
</View>
</Image>
</TouchableHighlight>
</View>
<View style={{flex: 1, alignItems: 'center', flexDirection: 'row',justifyContent: 'center',marginTop:-50}}>
<TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
<Image style={styles.bubblechoice} source={require('image!dairyfree')}>
<View style={styles.overlay}>
<Text style={styles.choicetext}>Dairy-Free</Text>
</View>
</Image>
</TouchableHighlight>
<TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
<Image style={styles.bubblechoice} source={require('image!vegetarian')}>
<View style={styles.overlay}>
<Text style={styles.choicetext}>Vegetarian</Text>
</View>
</Image>
</TouchableHighlight>
<TouchableHighlight underlayColor='rgba(73,182,77,1,1)' style={styles.bubblechoice} >
<Image style={styles.bubblechoice} source={require('image!healthy')}>
<View style={styles.overlay}>
<Text style={styles.choicetext}>Healthy</Text>
</View>
</Image>
</TouchableHighlight>
</View>
</View>
<Image source={require('image!nextbtn')} style={{resizeMode: 'contain', width:200, height:50, alignSelf: 'center', marginBottom: 50}}/>
<TouchableHighlight onPress={this.SkipLogin.bind(this)} underlayColor='transparent'>
<View style={{backgroundColor: 'transparent', alignItems: 'center', marginBottom: 8}}>
<Text>skip this step</Text>
</View>
</TouchableHighlight>
</Image>
</View>
);
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'transparent'
},
bgImage: {
flex: 1,
width: window.width,
resizeMode: 'cover',
},
icontext: {
color: '#5d5d5d',
fontWeight: '400',
fontSize: 20,
backgroundColor: 'transparent',
paddingLeft: 10,
alignItems: 'center',
marginTop: window.height/2.2,
textAlign: 'center',
margin: 10,
},
bubblechoice_click: {
height: window.height/8.335,
borderRadius: (window.height/8.3350)/2,
marginRight: 2,
width: window.height/8.335,
},
bubblechoice: {
height: window.height/8.335,
borderRadius: (window.height/8.3350)/2,
marginRight: 2,
width: window.height/8.335,
},
row: {
flex: 1,
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'center',
marginTop: -30,
},
choicetext: {
alignItems: 'center',
alignSelf: 'center',
color: 'white',
marginTop: 35,
fontWeight: '600',
marginLeft: -18,
fontSize: 14,
flex: 1,
textAlign: 'center'
},
overlay: {
backgroundColor:'rgba(80,94,104,0.7)',
height: 100,
width: 100,
alignItems:'center'
},
});
module.exports = LS1;
And here is a visual of what that produces:
Here's what the button should look like after being selected:
I think you should take a step back and do some basic React tutorials before digging too much into React Native - this is a fairly straightforward problem to solve :) Here's a solution for you:
'use strict';
var React = require('react-native');
var Dimensions = require('Dimensions');
var window = Dimensions.get('window');
var {
AppRegistry,
StyleSheet,
Text,
View,
NavigatorIOS,
Image,
TouchableHighlight,
TextInput,
} = React;
class ToggleButton extends React.Component {
render() {
return (
<TouchableHighlight underlayColor='rgba(73,182,77,1,0.9)' style={styles.bubblechoice} onPress={this.props.onPress}>
<Image style={styles.bubblechoice} source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}>
<View style={[styles.overlay, this.props.selected ? {backgroundColor: 'rgba(80,94,104,0)'} : {}]}>
<Text style={styles.choicetext}>{this.props.label}</Text>
</View>
</Image>
</TouchableHighlight>
);
}
}
class LS1 extends React.Component{
constructor(props){
super(props);
this.state = {
paleo: false,
vegan: false,
vegetarian: false,
}
}
updateChoice(type) {
let newState = {...this.state};
newState[type] = !newState[type];
this.setState(newState);
}
SkipLogin() {
var num = window.height/8.335;
console.log(num);
}
render() {
return (
<View style={styles.container}>
<View style={styles.bgImage}>
<Text style={styles.icontext}>Help us get to know your dietary lifestyle.</Text>
<View style={styles.container}>
<View style={{flex: 1, alignItems: 'center', flexDirection: 'row',justifyContent: 'center',marginTop:-20}}>
<ToggleButton label='Vegan' onPress={() => { this.updateChoice('vegan') }} selected={this.state.vegan} />
<ToggleButton label='Paleo' onPress={() => { this.updateChoice('paleo') }} selected={this.state.paleo} />
<ToggleButton label='Vegetarian' onPress={() => { this.updateChoice('vegetarian') }} selected={this.state.vegetarian} />
</View>
</View>
<TouchableHighlight onPress={this.SkipLogin.bind(this)} underlayColor='transparent'>
<View style={{backgroundColor: 'transparent', alignItems: 'center', marginBottom: 8}}>
<Text>skip this step</Text>
</View>
</TouchableHighlight>
</View>
</View>
);
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'transparent'
},
bgImage: {
flex: 1,
width: window.width,
resizeMode: 'cover',
},
icontext: {
color: '#5d5d5d',
fontWeight: '400',
fontSize: 20,
backgroundColor: 'transparent',
paddingLeft: 10,
alignItems: 'center',
marginTop: window.height/2.2,
textAlign: 'center',
margin: 10,
},
bubblechoice_click: {
height: window.height/8.335,
borderRadius: (window.height/8.3350)/2,
marginRight: 2,
width: window.height/8.335,
},
bubblechoice: {
height: window.height/8.335,
borderRadius: (window.height/8.3350)/2,
marginRight: 2,
width: window.height/8.335,
},
row: {
flex: 1,
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'center',
marginTop: -30,
},
choicetext: {
alignItems: 'center',
alignSelf: 'center',
color: 'white',
marginTop: 35,
fontWeight: '600',
marginLeft: -18,
fontSize: 14,
flex: 1,
textAlign: 'center'
},
overlay: {
backgroundColor:'rgba(80,94,104,0.7)',
height: 100,
width: 100,
alignItems:'center'
},
});
module.exports = LS1;
AppRegistry.registerComponent('main', () => LS1);
You can try it out by downloading Exponent to your phone from http://exponentjs.com/ (app store or beta, whichever you prefer) then loading up exp://exp.host/#brentvatne/button-color-exp
Simplest way with TouchableOpacity and active styles:
<TouchableOpacity
style={ this.state.active? styles.btnActive : styles.btn}
onPress={() => this.setState({active: !this.state.active})}>
</TouchableOpacity>