React Native - Setting item width according to the screen - javascript

I want 3 items to appear in each row and I want their size to be adjusted according to the screen itself, how can I do this?
I tried giving justifyContent to the flatlist columnWrapperStyle prop but the display turned out to be ridiculous
const renderSearchItem = ({
item: { id, type, title, original_title, poster },
}) => (
<Item
id={id}
type={type}
title={title == null ? original_title : title}
poster={poster}
navigation={navigation}
style={{ width: 115, height: 175 }}
/>
);
<FlatList
data={data?.datas}
renderItem={renderSearchItem}
keyExtractor={(item, index) => index.toString()}
key={search}
numColumns={3}
onEndReachedThreshold={1}
onEndReached={() => {
fetchMore({
variables: {
search,
offset: data?.datas?.length + 18,
},
updateQuery: (
previousResult,
{ fetchMoreResult }
) => {
if (
!fetchMoreResult ||
fetchMoreResult?.datas?.length === 0
) {
return previousResult;
}
return {
datas: previousResult?.datas?.concat(
fetchMoreResult?.datas
),
};
},
});
}}
ListHeaderComponent={headerComponent()}
showsVerticalScrollIndicator={false}
/>

You can get screen's width from Dimensions.
const width = Dimensions.get('screen').width
this will be the whatever the size of width the application running on.

export default function Item(props) {
const { id, type, title, poster, navigation, style } = props;
return (
<TouchableHighlight
style={styles.container}
onPress={() =>
navigation.navigate(
type == 'movie' ? 'MovieDetail' : 'SeriesDetail',
{
id,
title: title == null ? original_title : title,
}
)
}
>
<Image
style={[{ ...style }, { borderRadius: 5 }]}
source={{ uri: poster }}
/>
</TouchableHighlight>
);
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
marginBottom: 18,
marginLeft: 6,
},
});

Related

add a condition according to the presence of a database data

I have a list in which I want to add an image.
Basically my code worked fine and the API database I use has unfortunately changed ... Some products in my database don't have an image so it gives me an error when I call the line in question...
So, I want to create a condition: If there is an image for the product in question in the database, I want it to be displayed
Image source={{uri: URL + item.photo.1.url}}
Otherwise I want it to be a preset logo.
<Image source={require('../../../assets/images/logo.png')}
I did it this way:
<ListItem.Content style={{flexDirection: 'row', justifyContent: 'space-between'}}>
{item.photo !== null && item.photo > 0 ? (
<Image
source={{uri: URL + item.photo._1_.url}}
style={{ width: 25, height: 25}}/>
) : (
<Image
source={require('../../../assets/images/logo.png')}
style={{ width: 25, height: 25}}
/>
)};
<ListItem.Title style={{width: '65%', fontSize: 16}}>{ ( item.name.length > 20 ) ? item.name.substring(0, 20) + ' ...' : item.name}</ListItem.Title>
<ListItem.Subtitle style={{ color: '#F78400', position: "absolute", bottom: 0, right: 0 }}>{item.cost}{i18n.t("products.money")}</ListItem.Subtitle>
</ListItem.Content>
But I have 2 errors:
undefined is not an object (evaluating 'item.photo.1.url')
[Unhandled promise rejection: Error: Text strings must be rendered
within a component.]
To show you how the data looks :
And the full code of that screen :
export default class Products extends Component {
constructor(props) {
super(props);
this.state = {
productId: (props.route.params && props.route.params.productId ? props.route.params.productId : -1),
listData: '',
selectedId: '',
setSelectedId: '',
currentPage: 1,
loadMoreVisible: true,
loadMoreVisibleAtEnd: false,
displayArray: []
}
};
initListData = async () => {
let list = await getProducts(1);
if (list) {
this.setState({
displayArray: list,
loadMoreVisible: (list.length >= 10 ? true : false),
currentPage: 2
});
}
};
setNewData = async (page) => {
let list = await getProducts(parseInt(page));
if (list) {
this.setState({
displayArray: this.state.displayArray.concat(list),
loadMoreVisible: (list.length >= 10 ? true : false),
loadMoreVisibleAtEnd: false,
currentPage: parseInt(page)+1
});
}
};
loadMore() {
this.setNewData(this.state.currentPage);
}
displayBtnLoadMore() {
this.setState({
loadMoreVisibleAtEnd: true
});
}
async componentDidMount() {
this.initListData();
}
render() {
//console.log('url', URL );
//console.log('displayArray', this.state.displayArray);
//console.log('name', this.state.displayArray.name);
//console.log('photo', this.state.displayArray.photo);
return (
<View style={{flex: 1}}>
{this.state.displayArray !== null && this.state.displayArray.length > 0 ? (
<View style={{ flex: 1}}>
<SafeAreaView>
<FlatList
data={this.state.displayArray}
extraData={this.selectedId}
style={{width: '98%'}}
onEndReached={() => this.displayBtnLoadMore()}
renderItem={({item, index, separators })=>
<View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
<ListItem
style={{width:'100%'}}
containerStyle= {{backgroundColor: index % 2 === 0 ? '#fde3a7' : '#FFF'}}
bottomDivider
onPress={() => this.props.navigation.navigate('ProductDetails', {productId:parseInt(item.id)})}>
<ListItem.Content style={{flexDirection: 'row', justifyContent: 'space-between'}}>
{item.photo !== null && item.photo > 0 ? (
<Image
source={{uri: URL + item.photo._1_.url}}
style={{ width: 25, height: 25}}/>
) : (
<Image
source={require('../../../assets/images/logo.png')}
style={{ width: 25, height: 25}}
/>
)};
<ListItem.Title style={{width: '65%', fontSize: 16}}>{ ( item.name.length > 20 ) ? item.name.substring(0, 20) + ' ...' : item.name}</ListItem.Title>
<ListItem.Subtitle style={{ color: '#F78400', position: "absolute", bottom: 0, right: 0 }}>{item.cost}{i18n.t("products.money")}</ListItem.Subtitle>
</ListItem.Content>
</ListItem>
</View>
}
keyExtractor={(item,index)=>index.toString()}
style={{width:"100%"}}
/>
{this.state.loadMoreVisible === true && this.state.loadMoreVisibleAtEnd === true ? (
<Button title=" + " onPress={()=>{this.loadMore()}}></Button>
) : null
}
<View style={styles.container}>
<Text>{"\n"}</Text>
<TouchableOpacity
style={styles.touchable2}
onPress={() => this.props.navigation.goBack()}
>
<View style={styles.container}>
<Button
color="#F78400"
title= 'Back'
onPress={() => this.props.navigation.goBack()}>BACK
</Button>
</View>
</TouchableOpacity>
</View>
<Text>{"\n\n"}</Text>
</SafeAreaView>
</View>
) : (
<View style={styles.container}>
<Text>{"\n\n" + (this.state.displayArray === null ? i18n.t("products.searching") : i18n.t("products.nodata")) + "\n\n\n"}</Text>
<Button
color="#F78400"
title= 'Back'
onPress={() => this.props.navigation.goBack()}>BACK
</Button>
</View>
)}
</View>
);
};
}
I'm a little lost in how to do it, so if you have any clue to help me, any lead it would be great. Thanks a lot
This test:
item.photo !== null && item.photo > 0
Will not return what you expect. The reason is that when there is no photo, the property is set to an empty string. So the first part of that test should be:
item.photo !== ''
Next, when there is a photo, the photo property is an object. So the second part should be:
item.photo.constructor === 'Object'
But, that will be compounded if there are more than one photos. Your code suggests you only want the first photo (regardless of how many there may be).
So if you make the changes I've suggested, it should work as you expect.
If I were you, I would skip the first test altogether as it isn't necessary now that the second test covers both cases. I recommend just doing this:
{item.photo.constructor === 'Object' ? (

unique "key" prop error using RN FlatList with List ITem

I have a screen in which I display a list of products.
I am trying to set up a pagination. I am using List item from react-native-elements and looking at Using RN FlatList as possible in the documentation for this package.
I set up the ability to do pagination, but I got confused in my code. I don't know how to fix it anymore. I would like to know if it would be possible for you to give me a boost and reread my code to give me your opinion.
There for the moment I have the error:
Each child in a list should have a unique "key" prop
I'm a bit lost and need some guidance please. Thanks for any explanation.
The code :
export default class Products extends Component {
constructor(props) {
super(props);
this.state = {
productId: (props.route.params && props.route.params.productId ? props.route.params.productId : -1),
listData: '',
currentPage: 1,
loadMoreVisible: true,
loadMoreVisibleAtEnd: false,
displayArray: []
}
};
initListData = async () => {
let list = await getProducts(1);
if (list) {
this.setState({
displayArray: list,
loadMoreVisible: (list.length >= 10 ? true : false),
currentPage: 2
});
}
};
setNewData = async (page) => {
let list = await getProducts(parseInt(page));
if (list) {
this.setState({
displayArray: this.state.displayArray.concat(list),
loadMoreVisible: (list.length >= 10 ? true : false),
loadMoreVisibleAtEnd: false,
currentPage: parseInt(page)+1
});
}
};
loadMore() {
this.setNewData(this.state.currentPage);
}
displayBtnLoadMore() {
this.setState({
loadMoreVisibleAtEnd: true
});
}
async UNSAFE_componentWillMount() {
this.initListData();
}
renderItem = ({ item, i }) => (
<ListItem key={i}
bottomDivider
containerStyle={{backgroundColor: i % 2 === 0 ? '#fde3a7' : '#fff' }}
onPress={() => this.props.navigation.navigate('ProductDetails', {productId:parseInt(item.id)})}>
<Icon name='shopping-cart' />
<ListItem.Title style={{width: '65%', fontSize: 14, color: i % 2 === 0 ? '#212121' : '#F78400' }}>{item.name}</ListItem.Title>
<ListItem.Subtitle style={{ color: '#F78400'}}>{i18n.t("information.cost")}:{item.cost}</ListItem.Subtitle>
</ListItem>
);
render() {
//console.log('displayArray', this.state.displayArray)
return (
<View style={{flex: 1}}>
{this.state.displayArray !== null && this.state.displayArray.length > 0 ? (
<View style={{ flex: 1}}>
<SafeAreaView>
{
this.state.displayArray.map((item, i) => (
<FlatList
keyExtractor={(item, i) => {
return item.id;
}}
data={this.state.displayArray}
onEndReached={() => this.displayBtnLoadMore()}
renderItem={this.renderItem}
/>
))
}
</SafeAreaView>
{this.state.loadMoreVisible === true && this.state.loadMoreVisibleAtEnd === true ? (
<Button title=" + " onPress={()=>{this.loadMore()}}></Button>
) : null
}
<View style={styles.container}>
<Text>{"\n"}</Text>
<TouchableOpacity
style={styles.touchable2}
onPress={() => this.props.navigation.goBack()}
>
<View style={styles.container}>
<Button
color="#F78400"
title= 'Back'
onPress={() => this.props.navigation.goBack()}>BACK
</Button>
</View>
</TouchableOpacity>
</View>
<Text>{"\n\n"}</Text>
</View>
) : (
<View style={styles.container}>
<Text>{"\n\n" + (this.state.displayArray === null ? i18n.t("products.searching") : i18n.t("products.nodata")) + "\n\n\n"}</Text>
<Button
color="#F78400"
title= 'Back'
onPress={() => this.props.navigation.goBack()}>BACK
</Button>
</View>
)}
</View>
);
};
}
The problem is not in your list items but in the FlatList itself - you are rendering an array of FlatList components but they don't have unique keys.
this.state.displayArray.map((item, i) => (
<FlatList
key={item.id} // or key={i} if item doesn't have ID
... rest of your flat list props
/>
))

Camera Roll adding borderColor

So I want to create a beautiful UI of Camera Roll that has a borderColor instead of margin or padding because it will make the images do not fit on the width of the screen. I do not want to add borderColor to the right and left the side of the images too. It just likes on Instagram.
This is what I want to achieve:
Here are my codes:
CameraRoll.js
setIndex = (index) => {
if (index === this.state.index) {
index = null
}
this.setState({ index });
};
getPhotos = () => {
CameraRoll.getPhotos({
first: 200,
assetType: 'All'
})
.then(res => {
this.setState({
photos: res.edges,
});
})
.catch((err) => {
console.log('Error image: ' + err);
});
};
render() {
return(
<View style={styles.container}>
<Image
source={{uri: this.state.pickedImage}}
style={styles.image}
/>
<ScrollView contentContainerStyle={styles.scrollView} showsVerticalScrollIndicator={false}>
{this.state.photos.map((photos, index) => {
return(
<TouchableHighlight
style={{opacity: index === this.state.index ? .5 : 1}}
onPress={() => this.setState({pickedImage: photos.node.image.uri})}
key={index}
underlayColor='transparent'
>
<Image
style={[{width: width / 3, height: width /3}]}
source={{uri: photos.node.image.uri}}
resizeMode='cover'
/>
</TouchableHighlight>
);
})}
</ScrollView>
</View>
);
}
}
Change style of TouchableHighlight or Image, adding borderColor:"red", borderWidth:10
setIndex = (index) => {
if (index === this.state.index) {
index = null
}
this.setState({ index });
};
getPhotos = () => {
CameraRoll.getPhotos({
first: 200,
assetType: 'All'
})
.then(res => {
this.setState({
photos: res.edges,
});
})
.catch((err) => {
console.log('Error image: ' + err);
});
};
render() {
return(
<View style={styles.container}>
<Image
source={{uri: this.state.pickedImage}}
style={styles.image}
/>
<ScrollView contentContainerStyle={styles.scrollView} showsVerticalScrollIndicator={false}>
{this.state.photos.map((photos, index) => {
return(
<TouchableHighlight
style={{
opacity: index === this.state.index ? .5 : 1,
borderColor:"red", borderWidth:10
}}
onPress={() => this.setState({pickedImage: photos.node.image.uri})}
key={index}
underlayColor='transparent'
>
<Image
style={[{width: width / 3, height: width /3}]}
source={{uri: photos.node.image.uri}}
resizeMode='cover'
/>
</TouchableHighlight>
);
})}
</ScrollView>
</View>
);
}
}

Child component inside modal unexpectedly resets to default state, React Native

I have a parent component--LeagueSelect--and a child component TeamSelect.
LeagueSelect is a React Native modal.
When I open LeagueSelect, make adjustments in the LeagueSelect modal, collapse the modal, and open it again, the state changes are preserved.
If I open LeagueSelect, make adjustments to TeamSelect in the LeagueSelect modal, collapse the modal, and open it again, the state changes are not preserved.
To provide context, when the modal (LeagueSelect) is open, this is what it looks like; the first red box is part of LeagueSelect, and the second red box is part of TeamSelect:
This is my LeagueSelect component; I think the issue is happening in setModalVisible, because the console logs read the correct state when I console.log the state on componentWillUnmount:
class LeagueSelect extends Component {
constructor(props) {
super(props)
this.state = {
modalVisible: false,
checked: [],
checkedLeagues: [],
uncheckedLeagues: [],
checkMessage: '',
firstString: []
}
}
setModalVisible(visible) {
this.setState({modalVisible: visible})
if(this.state.checked.length === 0) {
this.props.league.map(
(v, i) => {
this.state.checked.push(true)
this.state.checkedLeagues.push(v.acronym)
}
)
}
this.setState({ checkMessage: '' })
matchedTeams = []
if(undefined !== this.props.teamObject) {
this.props.teamObject.map(
(v, i) => {
if(this.state.checkedLeagues.includes(v.league.acronym)){
matchedTeams.push(v.team_name)
}
}
)
}
queryString = []
//encodes the teams that have their leagues selected
matchedTeams.map(
(v, i) => {
if (queryString.length < 1) {
queryString.push(`?team=${v}`)
} else if (queryString.length >= 1 ) {
queryString.push(`&team=${v}`)
}
}
)
queryString = queryString !== undefined ? queryString.join('') : ''
axios.get(`http://localhost:4000/reports${queryString}`)
.then(response => {
this.props.loadCards(response.data)
})
}
componentDidMount() {
this.props.loadLeagues()
this.props.loadTeams()
}
componentDidUpdate(){
console.log(this.props.checkedLeagues)
console.log('in league - in update - checked Teams', this.props.checkedTeams)
this.props.changeLeagues(this.props.league, this.state.checkedLeagues, this.props.checkedTeams, this.props.queryTeams, this.props.teamObject)
}
render(){
return (
<View style={{ position: 'relative'}}>
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}
>
<View
style={{
marginTop: 100
}}
>
<TouchableHighlight
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}
>
<Image
source={require('../assets/exit.png')}
style={{
height: 20,
width: 20,
left: 320,
resizeMode: 'contain'
}}
/>
</TouchableHighlight>
<Text
style={{
paddingTop: 8,
paddingLeft: 5,
fontSize: 15,
fontFamily: 'Helvetica',
fontSize: 13
}}
>LEAGUE SELECT</Text>
<View
style={{
flexDirection:"row",
paddingLeft: 10
}}
>
{this.props.league === null ?'' : this.props.league.map(
(v, i) => {
return(
<View
key={i}
style={{
alignSelf: 'flex-end',
flexDirection:"row",
top: 4,
paddingRight: 10
}}
>
<Check
checked={this.state.checked[i]}
index={i}
value={v.acronym}
changeCheck={this.changeCheck}
style={{
paddingRight: 10
}}
/>
</View>
)
}
)}
</View>
<Text
style={{
paddingLeft: 10,
paddingTop: 12,
fontStyle: 'italic',
color: '#F4AF0D'
}}
>{this.state.checkMessage}</Text>
<TeamSelect />
</View>
</Modal>
<TouchableHighlight
onPress={() => {
this.setModalVisible(true);
}}>
<Icon
style={{
position: 'absolute',
top: -34,
right: 10,
fontSize: 25,
color: 'grey'
}}
name='settings'
/>
</TouchableHighlight>
</View>
);
}
}
function mapStateToProps(state) {
return {
league: state.league.league,
team: state.team.team,
checkedLeagues: state.league.checkedLeagues,
checkedTeams: state.league.checkedTeams,
queryTeams: state.league.queryTeams,
teamObject: state.league.teamObject
}
}
export default connect(mapStateToProps, { loadCards, loadLeagues, loadTeams, changeLeagues })(LeagueSelect)
This is the TeamSelect component where the second red box's selections are made:
class TeamSelect extends Component {
constructor(props) {
super(props)
this.state = {
checked: [],
checkedTeams: [],
teamObject: [],
queryString: [],
accordionStatus: [true, true, true]
}
}
componentDidMount(){
console.log('did mount - checked Teams State', this.state.checkedTeams)
//updates checked teams on load
if(this.state.count === false && this.state.checkedTeams.length === 0 && this.state.checked.length === 0){
this.setState({ count: true})
this.props.team.map(
(v, i) => {
if(this.props.checkedLeagues.includes(v.league.acronym)) {
this.state.checked.push(true)
this.state.checkedTeams.push(v.team_name)
this.state.teamObject.push(v)
} else if (this.state.checkedTeams !== undefined) {
this.state.checked.push(false)
}
}
)
this.forceUpdate()
}
}
componentWillUnmount(){console.log("unmount - count", this.state.count)
console.log('will unmount - checked Teams State', this.state.checkedTeams)
}
componentDidUpdate(){
this.props.changeLeagues(this.props.league, this.props.checkedLeagues, this.state.checkedTeams, this.state.queryString, this.state.teamObject)
}
changeCheck = (index, name, teamObject) => {
//updates checked team state
//prevents all teams being unselected
if(name === this.state.checkedTeams[0]) {
this.setState({ checkMessage: `Don't you want something to look at?` })
} else {
if(!this.state.checkedTeams.includes(name)){
this.state.checkedTeams[this.state.checkedTeams.length] = name
this.setState({ checkedTeams: [...this.state.checkedTeams] })
//sets team object with new team object
this.state.teamObject[this.state.teamObject.length] = teamObject
this.setState({ teamObject: this.state.teamObject })
} else {
newChecked = this.state.checkedTeams.filter(v => { return v !== name})
this.setState({ checkedTeams: newChecked })
//removes team object and sets new state
newObjectChecked = this.state.teamObject.filter(v => { return v.team_name !== teamObject.team_name})
this.setState({ teamObject: newObjectChecked })
}
//updates checkbox for specific space
this.state.checked[index] = !this.state.checked[index]
this.setState({ checked: this.state.checked })
}
}
changeTeamSelect = (index) => {
this.state.accordionStatus[index] = !this.state.accordionStatus[index]
this.setState({ accordionStatus: this.state.accordionStatus})
}
render(){
return(
<View>
<View>
<Text
style={{
fontFamily: 'Helvetica',
fontSize: 13,
paddingLeft: 5,
paddingBottom: 5
}}
onPress={()=> this.changeTeamSelect(0)}
>
NFL TEAM SELECT
</Text>
</View>
{
this.state.accordionStatus[0] === false ? null :
<View
style={{
flexDirection: 'row',
paddingLeft: 10,
flexWrap: 'wrap'
}}
>
{
this.props.team.map(
(v, i) => {
if(v.league.acronym === 'NFL'){
return(
<Check
key={i}
checked={ /*this.props.checkedLeagues.includes(v.league.acronym) ?*/ this.state.checked[i] /*: false*/ }
index={i}
teamObject={v}
value={v.team_name}
changeCheck={this.changeCheck}
/>
)
}
}
)
}
</View>
}
<View>
<Text
style={{
fontFamily: 'Helvetica',
fontSize: 13,
paddingLeft: 5,
paddingBottom: 5
}}
onPress={()=> this.changeTeamSelect(1)}
>
NBA TEAM SELECT
</Text>
</View>
{
this.state.accordionStatus[1] === false ? null :
<View
style={{
flexDirection: 'row',
paddingLeft: 10,
flexWrap: 'wrap'
}}
>
{
this.props.team.map(
(v, i) => {
if(v.league.acronym === 'NBA'){
return(
<Check
key={i}
checked={ /*this.props.checkedLeagues.includes(v.league.acronym) ?*/ this.state.checked[i] /*: false*/ }
index={i}
teamObject={v}
value={v.team_name}
changeCheck={this.changeCheck}
/>
)
}
}
)
}
</View>
}
<View>
<Text
style={{
fontFamily: 'Helvetica',
fontSize: 13,
paddingLeft: 5,
paddingBottom: 5
}}
onPress={()=> this.changeTeamSelect(2)}
>
MLB TEAM SELECT
</Text>
</View>
{
this.state.accordionStatus[2] === false ? null :
<View
style={{
flexDirection: 'row',
paddingLeft: 10,
flexWrap: 'wrap'
}}
>
{
this.props.team.map(
(v, i) => {
if(v.league.acronym === 'MLB'){
return(
<Check
key={i}
checked={ /*this.props.checkedLeagues.includes(v.league.acronym) ?*/ this.state.checked[i] /*: false */}
index={i}
teamObject={v}
value={v.team_name}
changeCheck={this.changeCheck}
/>
)
}
}
)
}
</View>
}
</View>
)
}
}
function mapStateToProps(state) {
return {
league: state.league.league,
team: state.team.team,
checkedLeagues: state.league.checkedLeagues,
checkedTeams: state.league.checkedTeams,
queryTeams: state.league.queryTeams
}
}
export default connect(mapStateToProps, { loadCards, changeLeagues })(TeamSelect)
Something to note, I use redux to update the state, place it into a store, and then use it when the component is mounts again. What is interesting is that this.state.checkedLeagues preserves state as it should in the first component, however, this.state.checkedTeams does not preserve it's state in the second component. Any ideas why?
EDIT:
This is my LeagueReducer:
let defaultState = {
league: null,
checkedLeagues: null,
checkedTeams: null,
queryTeams: null,
teamObject: null
}
export function LeagueReducer(state = defaultState, action){
if(action.type === "CHANGE_LEAGUES") {
return {
...state,
league: action.league,
checkedLeagues: action.checkedLeagues,
checkedTeams: action.checkedTeams,
queryTeams: action.queryTeams,
teamObject: action.teamObject
}
} else {
return state
}
}
Looks like it's possible you're not updating the redux store correctly. Remember do not use array functions that mutate the array like push. You need to use functions like concat that return a new array.

How to create two columns with space beetwen in react native - flatList

Hi i'm new in React Native.
I am trying to create two columns layout with space beetween using react native component called flatList.
Here is my view Code:
<View style={styles.container}>
<FlatList
data={db}
keyExtractor={ (item, index) => item.id }
numColumns={2}
renderItem={
({item}) => (
<TouchableWithoutFeedback onPress ={() => showItemDetails(item.id)}>
<View style={styles.listItem}>
<Text style={styles.title}>{item.name}</Text>
<Image
style={styles.image}
source={{uri: item.image}}
/>
<Text style={styles.price}>{item.price} zł</Text>
</View>
</TouchableWithoutFeedback>
)
}
/>
</View>
Here is styles:
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
padding: 10,
marginBottom: 40
},
listItem: {
maxWidth: Dimensions.get('window').width /2,
flex:0.5,
backgroundColor: '#fff',
marginBottom: 10,
borderRadius: 4,
},
And result is two columns but without space between.
Could you help me resolve this problem ?
You can give the item itself a width value of 45%. Also, flatlist has a property called columnWrapperStyle that you can give the value justifyContent: 'space-between.
Heres an example:
<FlatList
columnWrapperStyle={{justifyContent: 'space-between'}}
data={ApiData}
numColumns={2}
renderItem={({item}) => {
return (
<item style={{width: '45%'}} />
);
}}
/>
Use ItemSeparatorComponent for render a compontent between items
Docs: Rendered in between each item, but not at the top or bottom.
<FlatList
data={arrayOfData}
horizontal
ItemSeparatorComponent={
() => <View style={{ width: 16, backgroundColor: 'pink' }}/>
}
renderItem={({ item }) => (
<ItemView product={item} />
)}
/>
Preview in horizontal list
If list is vertical and suppose columnCount is 2
You have to give the styles.container to the contentContainerStyle propety of Flatlist, like so:
<FlatList
data={db}
keyExtractor={ (item, index) => item.id }
contentContainerStyle={styles.container}
numColumns={2}
renderItem={
({item}) => (
<TouchableWithoutFeedback onPress ={() => showItemDetails(item.id)}>
<View style={styles.listItem}>
<Text style={styles.title}>{item.name}</Text>
<Image
style={styles.image}
source={{uri: item.image}}
/>
<Text style={styles.price}>{item.price} zł</Text>
</View>
</TouchableWithoutFeedback>
)
}
/>
Just add some margin to the style of the list Item.
listItem: {
margin: 10,
}
How to create two columns with equal spacing between items:
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(item) => item.id}
horizontal={false} // you must include this line when using numColumns [per the documentation][1]
numColumns={2} // creates two columns
key={2} // add key to prevent error from being thrown
columnWrapperStyle={{justifyContent: 'space-between'}} // causes items to be equally spaced
>
Also, this will set each column to 1/2 the screen width:
const styles = StyleSheet.create({
item: {
flex: 1/2,
}})
I haven't used this library, but adding padding: 10 to listItem styles should help.
Based on your example it looks like you can add a margin to your list item styles:
listItem: {
maxWidth: Dimensions.get('window').width /2,
flex:0.5,
backgroundColor: '#fff',
marginBottom: 10,
borderRadius: 4,
margin: 18,
},
Keep in mind that this is equivalent to doing:
listItem: {
maxWidth: Dimensions.get('window').width /2,
flex:0.5,
backgroundColor: '#fff',
marginBottom: 10,
borderRadius: 4,
marginTop: 18,
marginBottom: 18,
marginRight: 18,
marginLeft: 18,
},
Customize to your liking or spec :)
Assuming your items are flex:1 and no width specified. You can wrap your renderItem with another view that adds the padding if needed
function columnWrappedRenderItemFunction<ItemT>(
renderItem: ListRenderItem<ItemT>,
numColumns: number,
space: FlatListProps<ItemT>["space"],
numberOfItems: number
): FlatListProps<ItemT>["renderItem"] {
return function columnWrappedRenderItem({
index,
...props
}: Parameters<ListRenderItem<ItemT>>[0]): ReturnType<ListRenderItem<ItemT>> {
const needsGapOnLeft = index % numColumns !== 0;
let extraItems = 0;
if (index === numberOfItems - 1) {
extraItems = (numColumns - (numberOfItems % numColumns)) % numColumns;
}
if (needsGapOnLeft) {
return (
<>
<View style={{width:space}} />
{renderItem({ index, ...props })}
{Array.from({ length: extraItems }, (_, k) => (
<View key={"extra_" + k} style={{marginLeft:space, flex:1}} />
))}
</>
);
} else {
return (
<>
{renderItem({ index, ...props })}
{Array.from({ length: extraItems }, (_, k) => (
<View key={"extra_" + k} marginLeft={space} style={{flex:1}} />
))}
</>
);
}
};
}
e.g.
function myRenderItem() { ... }
...
return (<FlatList
...
data={data}
renderItem={
numColumns === 1
? renderItem
: columnWrappedRenderItemFunction(
renderItem,
numColumns,
space,
data.length
)
}
numColumns={numColumns}
ItemSeparatorComponent={() => <View style={{height: space}} />}
/>);

Categories