react native list view design - css

I have tried to design the screen in react native but its hard divide a screen column and row like ionic and angular
Output of that below code
<View style={styles.listItemContainer}>
<View style={{flex:1}}>
<View style={{flexDirection:"column"}}>
<Text>1003234</Text>
<Text>Info Test........</Text>
</View>
</View>
<View style={{flexDirection:"column"}}>
<Text style={{backgroundColor:"red",borderRadius:10,padding:2,
marginRight:10,marginTop:5,fontSize:12}}>Inprogress</Text>
</View>
</View>`
exactly what i need

You can use Flatlist
Use below code to apply styles to your List
<FlatList style={Styles.container}
data={this.props.listData}
extraData={this.state.selectedItem}
keyExtractor={(item, index) => item.id}
renderItem={({ item, index }) => (
this.renderRow(item, index)
)}
ListEmptyComponent={this.showEmptyListView()}
/>
Your row render can look like this.
renderRow = (item, index) => {
return (
<TouchableHighlight key={index} onPress={() => this.onPressAction(item)} >
<View style={Styles.listItemContainer}>
<View style={Styles.listDesign}>
<View style={Styles.imageLength}>
{
item.imageUrl == '' ?
<Image
source={require("./../../assets/images/default-display.png")}
style={{ resizeMode: "cover", width: '100%', height: 100 }} /> :
<Image
source={{ uri: item.thumbnailImageUrl }}
style={{ resizeMode: "cover", width: '100%', height: 100 }} />
}
</View>
<View style={[Styles.columnAlign, Styles.contentWidth]}>
<View style={[Styles.justifyEnd, Styles.imageContainer]}>
<View style={Styles.justifySpaceAround}>
<Image
source={require("./../../assets/images/anyImage.png")}
style={{ resizeMode: "cover", width: 25, height: 25 }} />
</View>
</View>
<View style={Styles.buttonContainer}>
<Text style={Styles.vehicleDesc}>{"test"}</Text>
</View>
<View style={Styles.buttonContainer}>
<Text style={Styles.text}>{item.mileage}{translate("Test 1")}</Text>
</View>
<View style={Styles.buttonContainer}>
<Text style={Styles.text}>{"Test2"}</Text>
</View>
<View style={Styles.buttonContainer}>
<Text style={Styles.watchListtext}>{"Test 3"}</Text>
</View>
</View>
</View>
</View>
</TouchableHighlight>
);
}
Your Style
listItemContainer: {
marginTop: 7,
// marginBottom: 7,
flexDirection: 'row',
alignItems: 'flex-start',
},
listDesign: {
backgroundColor: Colors.white,
flexDirection: 'row',
alignItems: 'center',
padding: 6,
width: '100%'
},
vehicleDesc: {
marginLeft: 12,
fontSize: 16,
color: '#AA2328',
fontWeight: 'bold'
},
text: {
marginLeft: 12,
fontSize: 14,
color: Colors.black,
},
watchListtext: {
marginLeft: 12,
fontSize: 14,
color: Colors.brandPrimary,
},
imageLength: {
width: '35%'
},
contentLength: {
width: '65%'
},
container: {
flex: 1,
backgroundColor: Colors.creamyWhite,
},
buttonContainer: {
flexDirection: 'row',
padding: 2
}, imageContainer: {
flexDirection: 'row',
},
justifySpaceAround:
{
justifyContent:'space-around'
}
justifyEnd:
{
justifyContent:'flex-end'
},
coulmnAlign:
{
flexDirection:'coumn'
}
You show empty data
showEmptyListView = () => {
return (
<View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 10 }}>
<Text style={{ color: Colors.white }}>{"No Data to Display"}</Text>
</View>
)
}

You have to handle a lot in style.
You only need 3 common tag:
HorizontalContainer,
VerticalContainer,
ItemContainer,
export const VerticalContainer = styled.View({
flex: 1,
flexDirection: "column",
backgroundColor: (props) => props.backgroundColor || "#000"
});
export const HorizontalContainer = styled.View({
flex: 1,
flexDirection: "row",
backgroundColor: (props) => props.backgroundColor || "#000"
});
export const ItemContainer = styled.View({
flex: (props) => props.flex || 1
});
Inside handle as you like:
<HorizontalContainer backgroundColor="#fff">
<ItemContainer/>
<ItemContainer flex=2></ItemContainer>
<ItemContainer />
</HorizontalContainer >
Hope to help you!

I have done it with My Own code(FlatList view with design and search bar data from api) In that code i have removed my api call services you can try your own
Output Here(Check Before You Try)
import React, { Component } from 'react';
import { View, Text, StyleSheet,FlatList,ScrollView,ActivityIndicator} from 'react-native';
import { Picker } from 'react-native-picker-dropdown';
import Icon5 from 'react-native-vector-icons/FontAwesome5';
import { SearchBar, Avatar } from 'react-native-elements';
// create a component
class Home extends Component {
constructor(props){
super(props);
this.state={
data:[],
text: '',
language:'self',
ready: false,
searchText: "",
filteredData: [],
backupData:[]
}
this.onValueChange = this.handleValueChange.bind(this)
this.arrayholder=[];
}
search (searchText) {
this.setState({searchText: searchText});
console.log(searchText)
let text = searchText.toLowerCase();
let trucks = this.state.data;
// search by food truck name
let filteredName = trucks.filter((truck) => {
return truck.title.toLowerCase().match(text);
});
// if no match and text is empty
if( text == '') {
console.log('change state');
this.setState({
data: this.state.backupData
});
}
else if(!text ){
console.log("myname")
this.setState({data:[]})
}
// if no name matches to text output
else if(!Array.isArray(filteredName) && !filteredName.length) {
console.log("not name");
this.setState({
data: [],
});
}
// if name matches then display
else if(Array.isArray(filteredName)) {
console.log('Name');
this.setState({
data: filteredName,
});
}
};
showEmptyListView = () => {
return (
<View style={{ flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 10 }}>
<Text style={{ color: "black" }}>{"No Data to Display"}</Text>
</View>
)
}
handleValueChange(language) {
this.setState({ language })
}
renderRow = (item, index) => {
return (
<View style={styles.listItemContainer}>
<View style={{flex:1}}>
<View style={{flexDirection:"column",alignItems:"flex-start"}}>
<View style={{flexDirection:"row"}}>
<Text style={{marginLeft:12,marginTop:5,marginBottom:5,fontWeight:"bold",color:"black"}}>{item.number}</Text>
<Icon5 name="arrow-circle-up" size={15} style={{ marginTop:8,marginLeft:8, color: '#af2a5b', }}/>
<Text style={{marginLeft:5,marginTop:5,marginBottom:5,fontWeight:"bold",color:"#af2a5b"}}>{item.priority}</Text>
</View>
<Text style={{marginLeft:12,marginBottom:5,fontWeight:"bold",color:"black"}}>{item.title}</Text>
<View style={{flexDirection:"row"}}>
<Icon5 name="calendar-alt" size={15} style={{ marginLeft:12,marginBottom:5 }}/>
<Text style={{marginLeft:8,marginBottom:5}}>{item.assignedDate}</Text>
</View>
<View style={{flexDirection:"row"}}>
<Icon5 name="user-alt" size={15} style={{ marginLeft:12,marginBottom:5 }}/>
<Text style={{marginLeft:8,marginBottom:5}}>{item.createdBy}</Text>
</View>
</View>
</View>
<View style={{flexDirection:"column"}}>
<Text style={{color:"#f6b073",backgroundColor:"#fcd8b8",borderRadius: 10,padding:3,marginRight:10,marginTop:5,fontSize:12}}>{item.state}</Text>
</View>
</View>
);
}
renderHeader = () => {
return(
<View style={{ flex: 1, flexDirection: 'column' }}>
<View style={styles.listItemContainer}>
<View style={{flexDirection: 'row',backgroundColor: '#fff',color: '#fff',
width: '100%',height: 43,}}>
<View style={{ flex: 1, flexDirection: 'row' }}>
<View style={{ width: '45%', justifyContent: 'center', paddingTop: 7, paddingBottom: 7, color: '#fff', }} >
<Picker mode="dropdown" style={{width:150}}
selectedValue={this.state.language}
onValueChange={this.onValueChange} >
<Picker.Item label="My Task" value="self" />
<Picker.Item label="My Group" value="group" />
</Picker>
</View>
<View style={{ width: '55%', justifyContent: 'center', paddingTop: 7, paddingBottom: 7, color: '#fff', }} >
<SearchBar
inputStyle={{ backgroundColor: 'white', borderRadius: 55, borderWidth: 0, borderTopWidth: 0, borderBottomWidth: 0, height: 25 }}
containerStyle={{ backgroundColor: 'white', borderColor: '#g5g5g5', borderWidth: 0, borderRadius: 55, borderTopWidth: 0, borderBottomWidth: 0, width: '100%', marginLeft: 0, marginRight: 0, marginTop: 10, marginBottom: 10, height: 40 }}
placeholder="Search Here..."
inputContainerStyle={{ backgroundColor: 'white', borderWidth: 0, borderRadius: 55, height: 25 }}
onChangeText={searchText => this.search(searchText)}
value={this.state.searchText}
/>
</View>
</View>
</View>
</View>
</View>
)
}
renderFooter = () => {
return(
<View>
<Text>Footer</Text>
</View>
)
}
render() {
if (this.state.ready) {
return (
<FlatList style={{flex: 1,}}
data={this.state.filteredData && this.state.filteredData.length > 0 ? this.state.filteredData : this.state.data}
renderItem={({ item, index }) => (
this.renderRow(item, index)
)}
keyExtractor={(item, index) => index}
ListHeaderComponent={this.renderHeader}
ListEmptyComponent={this.showEmptyListView()}
enableEmptySections={true}
style={{flexWrap: 'wrap'}}
/>
);
}
else{
return (
<ActivityIndicator
animating={true}
style={{flex: 1,
alignItems: 'center',
justifyContent: 'center',
height: 80}}
color="#2F80ED"
size="large"
/>
);
}
}
}
const styles = StyleSheet.create({
listItemContainer: {
flex: 1,
marginBottom:10,
// paddingBottom: 15,
flexDirection: 'row',
backgroundColor: '#fff',
alignItems: 'flex-start',
},
})
export default Home;

Related

React native checkbox paper not checking individually

I am currently building a todo list productivity application and using the checkboxes from https://callstack.github.io/react-native-paper/checkbox-item.html
Im looping through my users todos through firebase and added a checkbox for each. However, when they check it, all of the todos get checked, not the invididual one. What would be the solution?
Code:
import React, { useEffect } from 'react';
import {useState} from "react"
import { SafeAreaView, Text, View, Button, TouchableOpacity, Modal, StyleSheet,Pressable, TextInput,ImageBackground, Image, ScrollView, } from 'react-native';
import { collection, doc, setDoc, query, getDocs, onSnapshot, addDoc, orderBy, limit, Timestamp, where} from "firebase/firestore";
import {db} from "../firebase"
import { auth } from '../firebase';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { AntDesign } from '#expo/vector-icons';
import { Feather } from '#expo/vector-icons';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import { Checkbox } from 'react-native-paper';
import {signPlsOut} from "../firebase"
export const Dashboard = () => {
const image = { uri: "https://cdn.discordapp.com/attachments/901614276748402820/946157600041476176/Screen_Shot_2022-02-23_at_4.32.16_PM.png" };
const {uid, photoURL, displayName} = auth.currentUser;
const projectsref = collection(db, "projects");
const [modalVisible, setModalVisible] = useState(false);
const [projects, setProjects] = useState([])
const [desc, setDesc] = useState("");
const [title, setTitle] = useState("");
const [checked, setChecked] = React.useState(false);
useEffect(() => {
const getData = async () => {
const q = await query(projectsref, where('uid', '==', uid), orderBy("createdAt"))
onSnapshot(q, (snapshot) => {
let todos = []
snapshot.forEach((doc) => {todos.push(doc.data())})
setProjects(todos)
})
}
getData()
}, [])
async function handleAddTask () {
try {
await addDoc(projectsref, {
title: title,
desc: desc,
createdAt: Timestamp.fromDate(new Date()),
uid: uid,
})
setTitle("")
setDesc("")
setModalVisible(false)
}
catch(error) {
console.log('There has been a problem with your fetch operation: ' + error.message);
// ADD THIS THROW error
throw error;
}
}
return (
<SafeAreaView style={{
flex: 1,
display: "flex",
justifyContent: 'space-between',
margin: 20,
flexDirection: "column",
}}>
<View style={{
flex: 1,
marginTop: 20
}}>
<View style={{marginBottom: 20, display: "flex", flexDirection: "row", justifyContent: "space-between"}}>
<View style={{display: "flex", flexDirection: "row"}}>
<Image source={{uri: "https://cdn.discordapp.com/attachments/856542608171073616/947245168191496212/Screen_Shot_2022-02-26_at_4.33.30_PM.png"}} style={{width: 50, height: 50}}></Image>
<View style={{marginLeft: 20, display: "flex", justifyContent: "space-between"}}>
<Text style={{fontSize: 17, fontWeight: "700"}}>{auth.currentUser.email}</Text>
<Text style={{color: "grey", fontSize: 15}}>Good Morning 👋🏼</Text>
</View>
</View>
<View style={{display: "flex", flexDirection: "row", alignItems: "center"}}>
<AntDesign name="search1" size={24} color="black" />
<Feather name="bell" size={24} color="black" style={{marginLeft: 10}}/>
</View>
</View>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Add task:</Text>
<View style={{marginBottom: 20}}>
<TextInput placeholder='title' value={title} onChangeText={(text) => setTitle(text)} ></TextInput>
<TextInput placeholder='description' value={desc} onChangeText={(text) => setDesc(text)}></TextInput>
</View>
<Button title='submit todo' onPress={handleAddTask}></Button>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Cancel</Text>
</Pressable>
</View>
</View>
</Modal>
<ScrollView style={{backgroundColor: "#EEE6DF", flex: 1, padding: 10, borderRadius: 20, marginBottom: 20, }}>
<Text style={{
fontSize: 30,
fontWeight: "700"
}}>Create Daily Tasks 🙌</Text>
<View style={{display: "flex", flexDirection: "row", flexWrap: "wrap", alignItems: "center"}}>
{projects.map((doc, key) => (
<View key={key} style={{
backgroundColor: "#fff",
borderRadius: "20px",
padding: 10,
marginTop: 20,
width: 130,
marginLeft: 20
}}>
<Checkbox
status={checked ? 'checked' : 'unchecked'}
onPress={() => {
setChecked(!checked);
}}
/>
<Text style={{
color: "#000",
fontSize: 30,
fontWeight: "700"
}}>{doc.title}</Text>
<Text style={{
color: "#000",
fontSize: 20
}}>{doc.desc}</Text>
</View>
))}
<Button title='Sign Out' onPress={signPlsOut} style={{marginLeft: 100}}></Button>
</View>
</ScrollView>
</View>
<View style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "row",
}}>
<TouchableOpacity >
<Pressable
onPress={() => setModalVisible(true)}>
<AntDesign name="pluscircle" size={50} color="#8BF45B" />
</Pressable>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
You must have a state for each ToDo separately.
For this, you can create an array state to store the id's wich ToDo are checked
const [checked, setChecked] = React.useState([]);
{projects.map((doc, key) => (
<View key={key} style={{
backgroundColor: "#fff",
borderRadius: "20px",
padding: 10,
marginTop: 20,
width: 130,
marginLeft: 20
}}>
<Checkbox
status={checked.find((item) => item === doc.id) ? 'checked' : 'unchecked'}
onPress={() => {
if(checked.find((item) => item === doc.id)) { //Verify if the ToDo id exist on checked state
setChecked(checked.filter((item) => item !== doc.id)); //Sets the checked state to an array without the current doc.id
} else {
setChecked([...checked, doc.id)] // add the current ToDo doc.id to the checked state
}
}}
/>
<Text style={{
color: "#000",
fontSize: 30,
fontWeight: "700"
}}>{doc.title}</Text>
<Text style={{
color: "#000",
fontSize: 20
}}>{doc.desc}</Text>
</View>
))}
This logic was the one I could think of now, I don't know if it is the best way but I hope it helps

Issue with Flexbox content in Row, for React Native

I'm having some issues with FlexBox of an Item in React Native my wish is to have a table using a row with this look:
(Sorry for my poor Paint Skills but all the text Name and numbers should be center vertical and Horizontally)
How it Currently looks:
Now the issue is that as you can see the image gets out of the Card Look and also it is not complete from the Sides.
Also there are other team Data which the images are bigger or the names are bigger and therefore the images is even further to the left :S
Example:
Finally here is the Code of the Item where I create the Row:
import React from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import Card from '../UI/Card';
import Colors from '../../constants/Colors';
const TablaItem = props => {
return (
<Card style={styles.product}>
<View style={styles.touchable}>
<View style={styles.container}>
<View style={styles.flexItem}>
<View style={styles.imageContainer}>
<Image style={styles.image} source={{ uri: props.image}} />
</View>
</View>
<View style={styles.flexItem}>
<Text>{props.name}</Text>
</View>
<View style={styles.flexItem}>
<Text>{props.games}</Text>
</View>
<View style={styles.flexItem}>
<Text>{props.win}</Text>
</View>
<View style={styles.flexItem}>
<Text>{props.draw}</Text>
</View>
<View style={styles.flexItem}>
<Text>{props.loose}</Text>
</View>
<View style={styles.flexItem}>
<Text>{props.infavor}</Text>
</View>
<View style={styles.flexItem}>
<Text>{props.against}</Text>
</View>
<View style={styles.flexItem}>
<Text>{props.points}</Text>
</View>
</View>
</View>
</Card>
);
};
const styles = StyleSheet.create({
product: {
height: 50,
margin: 20,
justifyContent: 'center',
alignItems: 'center'
},
container: {
flex: 5,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
flexWrap: 'nowrap'
},
flexItem: {
flexGrow: 0,
flexShrink: 1,
flexBasis: 'auto',
alignSelf:'auto',
marginHorizontal: 10,
},
imageContainer: {
alignSelf: 'flex-end',
width: '200%',
height: '100%',
borderTopLeftRadius: 10,
borderTopRightRadius: 10,
marginHorizontal: 10,
},
image: {
width: '100%',
height: '100%'
},
});
export default TablaItem;
And Here the code of the page where I render those items in a FlatList:
import React, { useState, useEffect, useCallback } from 'react';
import { FlatList, Button, ActivityIndicator, View, StyleSheet, Text } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import * as tablaActions from '../store/actions/tabla';
import Colors from '../constants/Colors';
import Tabla from '../components/tablas/TablaItem';
import Encabezado from '../components/tablas/TablaEncabecado';
const TablaScreen = props => {
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [error, setError] = useState();
const tabla1 = useSelector(state => state.tabla.tabla1);
const tabla2 = useSelector(state => state.tabla.tabla2);
const dispatch = useDispatch();
//Aqui se llama a Load Tabla para llamar partidos desde el API
const loadTablas = useCallback(async () => {
setError(null);
setIsRefreshing(true);
try {
await dispatch(tablaActions.fetchTabla());
} catch (err) {
setError(err.message);
}
setIsRefreshing(false);
}, [dispatch, setIsLoading, setError]);
//unsuscribe de Tablas
useEffect(() => {
const unsubscribeTablas = props.navigation.addListener('focus', loadTablas);
return () => {
unsubscribeTablas();
};
}, [loadTablas]);
//useEffect (carga inicial) de Tablas
useEffect(() => {
setIsLoading(true);
loadTablas().then(() => {
setIsLoading(false);
});
}, [dispatch, loadTablas]);
if (error) {
return <View style={styles.centered} >
<Text>Ah Ocurrido un Error {error}</Text>
<Button title='Probar de Nuevo' onPress={loadTablas} color={Colors.secondary} />
</View>
}
if (isLoading) {
return <View style={styles.centered} >
<ActivityIndicator size='large' color={Colors.secondary} />
</View>
}
//Checkeo de Partidos no Vacio.
if (!isLoading && tabla1 === 0 || tabla2 === 0) {
return <View style={styles.centered} >
<ActivityIndicator size='large' color={Colors.secondary} />
</View>
}
return(
<>
<Text style={styles.grupo}>Grupo A</Text>
<FlatList
onRefresh={loadTablas}
refreshing={isRefreshing}
data={tabla1}
keyExtractor={item => item.teamId.toString()}
renderItem={
itemData => <Tabla
image={itemData.item.logo}
name={itemData.item.teamName}
games={itemData.item.matchsPlayed}
win={itemData.item.win}
draw={itemData.item.draw}
loose={itemData.item.lose}
infavor={itemData.item.goalsFor}
against={itemData.item.goalsAgainst}
points={itemData.item.points}
/>
}
/>
<Text style={styles.grupo}>Grupo B</Text>
<FlatList
onRefresh={loadTablas}
refreshing={isRefreshing}
data={tabla2}
keyExtractor={item => item.teamId.toString()}
renderItem={
itemData => <Tabla
image={itemData.item.logo}
name={itemData.item.teamName}
games={itemData.item.matchsPlayed}
win={itemData.item.win}
draw={itemData.item.draw}
loose={itemData.item.lose}
infavor={itemData.item.goalsFor}
against={itemData.item.goalsAgainst}
points={itemData.item.points}
/>
}
/>
</>
);
};
export const screenOptions = navData => {
return {
headerTitle: 'Tabla de Clasificacion',
// headerLeft: () => (<HeaderButtons HeaderButtonComponent={HeaderButton}>
// <Item
// title='Menu'
// iconName={Platform.OS === 'android' ? 'md-menu' : 'ios-menu'}
// onPress={() => {
// navData.navigation.toggleDrawer();
// }} />
// </HeaderButtons>),
// headerRight: () => (<HeaderButtons HeaderButtonComponent={HeaderButton}>
// <Item
// title='Carretilla'
// iconName={Platform.OS === 'android' ? 'md-cart' : 'ios-cart'}
// onPress={() => {
// navData.navigation.navigate('Cart');
// }} />
// </HeaderButtons>)
}
};
const styles = StyleSheet.create({
centered: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
grupo: {
alignSelf: 'center',
fontWeight: 'bold',
fontSize: 16,
color: Colors.primary,
marginTop: 10,
}
});
export default TablaScreen;
I will also like to render the lines of the Flatlist one beneath the other with just a minimum gap currently it looks like this:
And will also like to add to the top something like this:
Which is basically a Header with the same style, and it will have the titles:
Equipo (which will be the length of the Image and Name), Juegos, Ganados, Empates, Perdidos, Afavor, Encontra, Puntos.
This Last part is just a wish to know.
Any Ideas?
Give your Image resizeMode of "contain" or "cover"
<Image
resizeMode="contain"
style={{ flex: 1 }}
source={{ uri: 'https://ezgif.com/images/insert-image.png' }}
/>
Working Example: Expo Snack
Sample Output:
Sample App Source Code:
import React from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import { Card } from 'react-native-paper';
export default TablaItem = (props) => {
return (
<View style={{ flex: 1, backgroundColor: '#212121' }}>
<View style={styles.card}>
<View>
<View style={styles.imageCircle}>
<Image
resizeMode="cover"
style={{ flex: 1 }}
source={{ uri: 'https://ezgif.com/images/insert-image.png' }}
/>
</View>
</View>
<View style={{ marginLeft: 10, flex: 2 }}>
<Text style={styles.text}>{'Alianza Alianza'}</Text>
</View>
<View
style={{
flexDirection: 'row',
flex: 7,
justifyContent: 'space-evenly',
}}>
<View>
<Text style={styles.text}>{10}</Text>
</View>
<View>
<Text style={styles.text}>{6}</Text>
</View>
<View>
<Text style={styles.text}>{4}</Text>
</View>
<View>
<Text style={styles.text}>{0}</Text>
</View>
<View>
<Text style={styles.text}>{15}</Text>
</View>
<View>
<Text style={styles.text}>{9}</Text>
</View>
<View>
<Text style={styles.text}>{20}</Text>
</View>
</View>
</View>
</View>
);
};
const styles = StyleSheet.create({
imageCircle: {
width: 50,
height: 50,
backgroundColor: 'white',
borderRadius: 25,
padding: 8,
borderWidth: 2,
borderColor: 'rgba(21,21,21,0.2)',
justifyContent: 'center',
alignContent: 'center',
},
card: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'white',
borderRadius: 10,
margin: 10,
paddingHorizontal: 5,
padding: 2,
marginTop: 30,
},
text: {
fontSize: 14,
fontWeight: '600',
},
});

Multi Column and Rows Flex Box issue in React Native

I'm having and Issue with Flex Box I'm trying to get this type of Grid View:
And I have tried a bunch of positions without any luck, the last one I tried is:
return (
<>
<View style={styles.container}>
<View style={styles.column}>
<View style={styles.row}>
<View style={[styles.box, { backgroundColor: 'yellow' }]} />
</View>
</View>
<View style={styles.column}>
<View style={[styles.box, { backgroundColor: 'green' }]} />
<View style={[styles.box, { backgroundColor: 'lightblue' }]} />
</View>
<View style={styles.space_between_columns} />
<View style={styles.column}>
<View style={[styles.box, { backgroundColor: 'grey' }]} />
<View style={[styles.box, { backgroundColor: 'purple' }]} />
</View>
</View>
</>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection:'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
row: {
flexDirection:'row',
justifyContent:'space-between',
alignItems:'center',
height:200,
width:50
},
column: {
flexDirection:'column',
justifyContent:'space-between',
alignItems:'center',
height:200,
width:50
},
space_between_columns:{
width:100
},
box: {
height:50,
width:50
}
});
But instead of giving me the Top Section where I want it, it puts it like this:
Any Ideas?
Kind Regards
Working App: Expo Snack
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.text}>Header</Text>
</View>
<View style={{ padding: 10, flex: 1 }}>
<View style={styles.topSection}>
<Text style={styles.text}>Top Section</Text>
</View>
<View style={{ flexDirection: 'row', flex: 1 }}>
<View style={styles.leftColumn}>
<Text style={styles.text}>Left Column</Text>
</View>
<View style={styles.rightColumn}>
<Text style={styles.text}>Right Column</Text>
</View>
</View>
<View
style={{
height: 70,
flexDirection: 'row',
}}>
<View style={styles.subLeft}>
<Text style={styles.text}>Sub Left</Text>
</View>
<View style={styles.subRight}>
<Text style={styles.text}>Sub Right</Text>
</View>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'start',
backgroundColor: 'black',
},
header: {
height: 100,
backgroundColor: 'lightblue',
justifyContent: 'center',
},
topSection: {
height: 70,
backgroundColor: 'yellow',
justifyContent: 'center',
},
leftColumn: {
flex: 1,
backgroundColor: 'green',
justifyContent: 'center',
},
rightColumn: {
flex: 1,
backgroundColor: 'lightblue',
justifyContent: 'center',
},
subLeft: {
flex: 1,
backgroundColor: 'grey',
justifyContent: 'center',
},
subRight: {
flex: 1,
backgroundColor: 'purple',
justifyContent: 'center',
},
text: {
alignSelf: 'center',
color: 'black',
fontWeight: '800',
fontSize: 20,
},
});

Adding margins to the right edge of Flex-Start React-Native

import React, { Component } from 'react';
import { StyleSheet, Dimensions } from 'react-native';
import {
CheckBox, Container, Content, Text, View, Button,
} from 'native-base';
import Fonts from '../common/Fonts';
const checkAllMargin = Dimensions.get('window').height / 3.14;
const styles = StyleSheet.create({
wrapper: {
justifyContent: 'flex-end',
flexDirection: 'column',
flex: 1,
},
moveButtonContainer: {
flexDirection: 'row',
alignSelf: 'flex-end',
marginTop: checkAllMargin,
},
prevButton: {
justifyContent: 'center',
flex: 1,
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: '#333333',
height: 55,
},
nextButton: {
justifyContent: 'center',
flex: 1,
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor: '#4FCBFF',
height: 55,
},
moveButtonText: {
textAlign: 'center',
fontFamily: Fonts.NANUMGOTHICBOLD,
fontSize: 18,
},
termsView: {
flexDirection: 'row',
justifyContent: 'flex-start',
marginTop: 21,
},
checkBox: {
marginLeft: 10,
},
termsText: {
alignSelf: 'center',
marginLeft: 17,
height: 16,
fontFamily: Fonts.NANUMGOTHIC,
fontSize: 11,
},
termsTextEnd: {
fontFamily: Fonts.NANUMGOTHIC,
fontSize: 11,
alignSelf: 'center',
},
requiredText: {
color: '#4FCBFF',
},
choiceText: {
color: '#999999',
},
checkAllView: {
flexDirection: 'row',
alignItems: 'flex-end',
justifyContent: 'flex-end',
marginTop: 35,
},
checkAllText: {
alignSelf: 'flex-end',
marginRight: 42,
},
checkAllBox: {
marginRight: 17,
},
openLinkButton: {
borderColor: '#CCCCCC',
borderRadius: 10,
height: 18,
width: 35,
alignSelf: 'flex-end',
borderWidth: 1,
},
openLinkText: {
fontFamily: Fonts.NANUMGOTHIC,
fontSize: 9,
paddingTop: 3,
paddingLeft: 5,
},
});
class TermsAgreeContainer extends Component {
constructor(props) {
super(props);
this.state = {
agreeTermsOfServices: false,
agreeTermsOfPrivacy: false,
agreeTermsOfCopyright: false,
agreeAll: false,
};
}
checkTermsOfServices = (isCheck) => {
this.setState({
agreeTermsOfServices: isCheck,
});
}
checkTermsOfPrivacy = (isCheck) => {
this.setState({
agreeTermsOfPrivacy: isCheck,
});
}
checkTermsOfCopyright = (isCheck) => {
this.setState({
agreeTermsOfCopyright: isCheck,
});
}
checkAll = (isCheck) => {
this.setState({
agreeTermsOfServices: isCheck,
agreeTermsOfPrivacy: isCheck,
agreeTermsOfCopyright: isCheck,
agreeAll: isCheck,
});
}
render() {
const {
agreeTermsOfServices, agreeTermsOfPrivacy, agreeTermsOfCopyright, agreeAll,
} = this.state;
const {
checkTermsOfServices, checkTermsOfPrivacy, checkTermsOfCopyright, checkAll,
} = this;
return (
<Container>
<Content scrollEnabled={false} contentContainerStyle={styles.wrapper}>
<View style={styles.termsView}>
<CheckBox
checked={agreeTermsOfServices}
onPress={() => checkTermsOfServices(!agreeTermsOfServices)}
style={styles.checkBox}
/>
<Text
style={styles.termsText}
onPress={() => checkTermsOfServices(!agreeTermsOfServices)}
suppressHighlighting
>
TermsOfServices
</Text>
<Text style={[styles.termsTextEnd, styles.requiredText]}> (required)</Text>
<Text style={[styles.openLinkButton, styles.openLinkText]}>Show</Text>
</View>
<View style={styles.termsView}>
<CheckBox
checked={agreeTermsOfPrivacy}
onPress={() => checkTermsOfPrivacy(!agreeTermsOfPrivacy)}
style={styles.checkBox}
/>
<Text
style={styles.termsText}
onPress={() => checkTermsOfPrivacy(!agreeTermsOfPrivacy)}
suppressHighlighting
>
TermsOfPrivacy
</Text>
<Text style={[styles.termsTextEnd, styles.requiredText]}> (required)</Text>
<Text style={[styles.openLinkButton, styles.openLinkText]}>Show</Text>
</View>
<View style={styles.termsView}>
<CheckBox
checked={agreeTermsOfCopyright}
onPress={() => checkTermsOfCopyright(!agreeTermsOfCopyright)}
style={styles.checkBox}
/>
<Text
style={styles.termsText}
onPress={() => checkTermsOfCopyright(!agreeTermsOfCopyright)}
suppressHighlighting
>
TermsOfCopyright
</Text>
<Text style={[styles.termsTextEnd, styles.choiceText]}> (choice)</Text>
<Text style={[styles.openLinkButton, styles.openLinkText]}>Show</Text>
</View>
<View style={styles.checkAllView}>
<CheckBox
checked={agreeAll}
onPress={() => checkAll(!agreeAll)}
style={styles.checkAllBox}
/>
<Text
style={styles.checkAllText}
onPress={() => checkAll(!agreeAll)}
suppressHighlighting
>
Check All
</Text>
</View>
<View style={styles.moveButtonContainer}>
<Button full style={styles.prevButton}>
<Text style={styles.moveButtonText}>back</Text>
</Button>
<Button full style={styles.nextButton}>
<Text style={styles.moveButtonText}>next</Text>
</Button>
</View>
</Content>
</Container>
);
}
}
export default TermsAgreeContainer;
Currently, the position of the Show button is determined by the Text length on the left.
I would like to move it to the right like the photo.
I want the Show button to be margin 30 based on the right.
However, I do not use margin-right if I use Flex-Start.
How can I place the show button on the right side?
One way could be to divide your current terms row in 2 views, assigning the first one a flex property and just a margin to the second one. Simply wrap the first elements in a <View>, like this:
<View style={styles.termsView}>
<View style={{ flex: 1, flexDirection: 'row' }}>
<CheckBox
checked={agreeTermsOfServices}
onPress={() => checkTermsOfServices(!agreeTermsOfServices)}
style={styles.checkBox}
/>
<Text
style={styles.termsText}
onPress={() => checkTermsOfServices(!agreeTermsOfServices)}
suppressHighlighting>
TermsOfServices
</Text>
<Text style={[styles.termsTextEnd, styles.requiredText]}>
(required)
</Text>
</View>
<Text
style={[
styles.openLinkButton,
styles.openLinkText,
{ marginRight: 10 },
]}>
Show
</Text>
</View>
And repeat this structure for each row.

How to set maxWidth in mobile screen?

I am trying to render few buttons in a row, but having some problem with css style. how can i set maxwidth in mobile screen? this is screen short of my problem
I want to set a css style when maxwidth are over then rest of the button are show in a new row automatically is its possible to render in react-native???
My source code::
import React from 'react';
import { View, Text, StyleSheet, TouchableHighlight } from 'react-native';
import { Header, Icon } from 'react-native-elements';
class Extras extends React.Component {
constructor(props){
super(props);
this.state = { selectFurnish: '', selectVeg: '', selectOtherFecility: '' };
this.onButtonPress = this.onButtonPress.bind(this);
}
leftComponent = () => {
return <Icon name='angle-left' color='#fff' type='font-awesome' onPress={() => {this.props.navigation.navigate('pricing')}} />
}
onButtonPress = (stateName, selected) =>{
const obj = Object.assign({},this.state);
obj[stateName] = selected;
this.setState( obj );
}
render() {
const furnish_button_props = [
{ id: 0, value: 'Full'},
{ id: 1, value: 'Semi'},
{ id: 2, value: 'None'}
];
const veg_button_props = [
{ id: 0, value: 'Yes'},
{ id: 1, value: 'No'}
];
const otherFacilities_button_props = [
{ id: 0, value: 'Parking'},
{ id: 1, value: 'Lift'},
{ id: 2, value: 'Gas Pipeline'},
{ id: 3, value: 'Pool'}
];
return(
<View style={styles.container}>
<Header
leftComponent={this.leftComponent()}
centerComponent={{text: 'NEW LISTING', style: {color: '#FFF', fontSize: 16}}}
outerContainerStyles={{backgroundColor: '#3498db'}}
/>
<View style={styles.block}>
<View>
<Text style={styles.textType}>Furnishing</Text>
<View style={{flexDirection: 'row'}}>
{furnish_button_props.map(i => {
return(
<TouchableHighlight
activeOpacity={1}
onPress={() => this.onButtonPress('selectFurnish',i.value)}
key={i.id}
style={ this.state.selectFurnish === i.value ? styles.buttonOnPress : styles.button }
>
<Text style={ this.state.selectFurnish === i.value ? styles.textOnPress : styles.text }>{i.value}</Text>
</TouchableHighlight>
)
})}
</View>
</View>
<View style={{marginTop: 50}}>
<Text style={styles.textType}>Vegetarian</Text>
<View style={{flexDirection: 'row'}}>
{veg_button_props.map(i => {
return(
<TouchableHighlight
activeOpacity={1}
onPress={() => this.onButtonPress('selectVeg', i.value)}
key={i.id}
style={ this.state.selectVeg === i.value ? styles.buttonOnPress : styles.button }
>
<Text style={ this.state.selectVeg === i.value ? styles.textOnPress : styles.text }>{i.value}</Text>
</TouchableHighlight>
)
})}
</View>
</View>
<View style={{marginTop: 50}}>
<Text style={styles.textType}>Other Facilities</Text>
<View style={{flexDirection: 'row'}}>
{otherFacilities_button_props.map(i => {
return(
<TouchableHighlight
activeOpacity={1}
onPress={() => this.onButtonPress('selectOtherFecility', i.value)}
key={i.id}
style={ this.state.selectOtherFecility === i.value ? styles.buttonOnPress : styles.button }
>
<Text style={ this.state.selectOtherFecility === i.value ? styles.textOnPress : styles.text }>{i.value}</Text>
</TouchableHighlight>
)
})}
</View>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
maxWidth: '100%'
},
block: {
marginTop: 120,
marginLeft: 10
},
textType: {
fontSize: 16,
fontWeight: 'bold',
marginBottom: 5,
marginLeft: 5
},
button: {
borderColor: '#3498db',
borderWidth: 1,
borderRadius: 25,
width: 100,
height: 50,
marginLeft: 5,
marginRight: 5,
display: 'flex',
justifyContent: 'center',
alignItems: 'center'
},
buttonOnPress: {
borderColor: '#3498db',
backgroundColor: '#3498db',
borderWidth: 1,
borderRadius: 25,
width: 100,
height: 35,
marginLeft: 5,
marginRight: 5
},
text: {
fontSize: 14,
color: '#3498db'
},
textOnPress: {
fontSize: 14,
fontWeight: 'bold',
color: '#ffffff'
},
});
export default Extras;
You can add: flexWrap: 'wrap' to your view (<View style={{flexDirection: 'row'}}>)
More about flex

Resources