Here am able to parse JSON value on my FlatList, because in console.log I can see that, FlatList is also expanding but the value is not displaying on the list . after selecting particular list value data is going on the second screen and displaying data but on first screen blank. Please help
import React, { Component } from 'react';
import { View, Text, TextInput,
FooterTab,Button,TouchableOpacity, ScrollView, StyleSheet,
ActivityIndicator ,Header,icon,FlatList} from 'react-native';
import { createStackNavigator } from 'react-navigation';
import { SearchBar } from 'react-native-elements';
class RenderList extends Component {
static navigationOptions = {
title: 'Selected Item',
header: null,
};
constructor() {
super();
this.state = {
data: null,
loading: true,
search: '',
};
}
componentDidMount() {
this.createViewGroup();
}
createViewGroup = async () => {
try {
const response = await fetch(
'http:///Dsenze/userapi/grouphier/viewgroup',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password: 'admin',
username: 'admin',
viewall: 'false',
id: [4],
startlimit: '0',
valuelimit: '10',
}),
}
);
const responseJson = await response.json();
const { groupData } = responseJson;
this.setState({
data: groupData,
loading: false,
});
} catch (e) {
console.error(e);
}
};
clickedItemText(clickedItem) {
this.props.navigation.navigate('Item', { item: clickedItem });
}
updateSearch = search => {
this.setState({ search });
};
keyExtractor = ({ id }) => id.toString();
keyExtractor = ({ name }) => name.toString();
renderItem = ({ item }) => (
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}>
</TouchableOpacity>
);
render() {
const { loading, data } = this.state;
return (
<ScrollView>
<View style={styles.container1}>
{this.state.loading ? (
<ActivityIndicator size="large" />
) :
(
<FlatList
data={data}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>
)}
</View>
</ScrollView>
);
}
}
class ClickedItem extends Component
{
constructor() {
super();
this.state = {
inputValue: '',
// Default Value of the TextInput
// Default value for the QR Code
};
}
static navigationOptions =
{
title: "Selected Item",
header: null
};
render()
{
return(
<ScrollView>
<View style = { styles.container2 }>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Hospital Id"
editable={false}
placeholderTextColor="#000000"
onChangeText={(hospital_id) => this.setState({hospital_id})}>{ this.props.navigation.state.params.item.name }</TextInput>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Field 2"
secureTextEntry={false}
placeholderTextColor="#000000"
onChangeText={(Field2) => this.setState({Field2})}/>
<TouchableOpacity style={styles.button}onPress={() => {Insert(this.state.hospital_id,this.state.Field2,this.state.Field3,this.state.Field4,this.state.Field5,this.state.Field6);{this.getTextInputValue}}}>
<Text style={styles.buttonText}>Insert</Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
}
export default InvDemoPost = createStackNavigator(
{
List: { screen: RenderList,
header: true},
Item: { screen: ClickedItem,
header: null }
});
const styles = StyleSheet.create(
{
container1:
{
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
ListContainer :{
borderColor: '#48BBEC',
backgroundColor: '#000000',
color:'red',
alignSelf: 'stretch' ,
},
container2:
{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
paddingHorizontal: 15
},
inputBox:{
width:300,
borderColor: '#48BBEC',
backgroundColor: '#F8F8FF',
borderRadius:25,
paddingHorizontal:16,
fontSize:16,
color:'#000000',
marginVertical:10,
},
button:{
width:300,
backgroundColor:'#4169E1',
borderRadius:25,
marginVertical:10,
paddingVertical:16
},
buttonText:{
fontSize:16,
fontWeight:'500',
color:'#ffffff',
textAlign:'center'
},
item:
{
padding: 15
},
text:
{
fontSize: 18
},
separator:
{
height: 2,
backgroundColor: 'rgba(0,0,0,0.5)'
}
});
// Json response is like that
//Json value is below , I have to display Name and Id
{
"groupData": [{
"hierarchy": 1,
"id": 1,
"name": "Karnataka",
"parent": 1,
"type": 1
}, {
"hierarchy": 2,
"id": 2,
"name": "Bangalore",
"parent": 1,
"type": 2
}, {
"hierarchy": 3,
"id": 3,
"name": "North Bangalore",
"parent": 2,
"type": 2
}, {
"hierarchy": 4,
"id": 4,
"name": "St.Mary's Hospitals",
"parent": 3,
"type": 2
}, {
"hierarchy": 4,
"id": 5,
"name": "Mandya Clinic",
"parent": 6,
"type": 2
}, {
"hierarchy": 2,
"id": 6,
"name": "Mandya",
"parent": 1,
"type": 1
}, {
"hierarchy": 4,
"id": 7,
"name": "Blr Clinic3",
"parent": 3,
"type": 1
}, {
"hierarchy": 4,
"id": 8,
"name": "kings hospital",
"parent": 3,
"type": 2
}, {
"hierarchy": 1,
"id": 10,
"name": "Tamil Nadu",
"parent": 10,
"type": 1
}],
"success": "true"
}
// Thanks
Your renderItem function only returns a TouchableOpacity. If you put something inside your TouchableOpacity you should see something on the screen.
In this example I have added a simple Text component with the name that is contained within your item.
renderItem = ({ item }) => (
<TouchableOpacity
style={styles.item}
activeOpacity={0.4}
onPress={() => {
this.clickedItemText(item);
}}
>
<Text>{item.name}/<Text>
</TouchableOpacity>
);
Related
Im trying to create a horizontal flatlist. The code below does work in online editor but not on my emulator. I couldn't figure out if the problem is due to my code or the emulator. I tried remove horizontal property but still it doesn't work vertically. I replaced SafeAreaView with ScrollView but I took same result. Control the styles and removed all styles and tested without styles but again I couldn't scroll it.
export const Stories = () => {
const stories = [
{
id: 1,
name: "Name1",
image: "https://xsgames.co/randomusers/avatar.php?g=male",
},
{
id: 2,
name: "Name2",
image: "https://xsgames.co/randomusers/avatar.php?g=female",
},
{
id: 3,
name: "Name3",
image: "https://xsgames.co/randomusers/avatar.php?g=pixel ",
},
{
id: 4,
name: "Name4",
image: "https://xsgames.co/randomusers/avatar.php?g=pixel ",
},
{
id: 5,
name: "Name5",
image: "https://xsgames.co/randomusers/avatar.php?g=pixel ",
},
{
id: 6,
name: "Name6",
image: "https://xsgames.co/randomusers/avatar.php?g=pixel ",
},
{
id: 7,
name: "Name7",
image: "https://xsgames.co/randomusers/avatar.php?g=pixel ",
},
{
id: 8,
name: "Name8",
image: "https://xsgames.co/randomusers/avatar.php?g=pixel ",
},
{
id: 9,
name: "Name9",
image: "https://xsgames.co/randomusers/avatar.php?g=pixel ",
},
];
const singleStory = ({ item }) => {
return (
<View style={styles.story}>
<View style={styles.avatarContainer}>
<Image source={{ uri: item.image }} style={styles.avatar} />
</View>
<Text>{item.name}</Text>
</View>
);
};
return (
<SafeAreaView style={styles.container}>
<FlatList
horizontal
data={stories}
renderItem={singleStory}
/>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
borderColor: "grey",
borderBottomWidth: 0.9,
borderTopWidth: 0.9,
},
story: {
padding: 10,
alignItems: "center",
},
avatarContainer: {
height: 60,
width: 63,
justifyContent: "center",
alignItems: "center",
},
avatar: {
borderRadius: 50,
height: 50,
width: 50,
},
});
Add flex:1 in container, as you need to fix dimension of the view
container: {
borderColor: "grey",
borderBottomWidth: 0.9,
borderTopWidth: 0.9,
flex:1
},
I'm using antd to create a table which contains chart in cell, just like this html table + chart.js
I tried some tutorials of antd table but failed, here's my codesandbox.
Is there any way or other toolbox to do this ?
You can add couple of packages to achieve the same ( Finished Code sandbox)
"chart.js": "3.4.1",
"react-chartjs-2": "3.0.3",
And then Define the component and use it in the renderer
{
title: "Charts",
render: (chartData) => {
const data = {
labels: ["1", "2", "3", "4", "5", "6"],
datasets: [{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
fill: false,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgba(255, 99, 132, 0.2)"
}]
};
return <LineChart data = {
data
}
/>;
}
You need to use some kind of chart library to display the chart. Ant Design doesn't provide charts. The famous one for react is https://recharts.org/en-US which internally uses react and d3.
I copied your code from the sandbox and added Bar chart rendering code. This is how your code should look like:
import React, { PureComponent } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Table, Input, Button, Space } from "antd";
import Highlighter from "react-highlight-words";
import { SearchOutlined } from "#ant-design/icons";
import {
BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
} from 'recharts';
const data1 = [
{
name: 'Page A', uv: 4000, pv: 2400, amt: 2400,
},
{
name: 'Page B', uv: 3000, pv: 1398, amt: 2210,
},
{
name: 'Page C', uv: 2000, pv: 9800, amt: 2290,
},
{
name: 'Page D', uv: 2780, pv: 3908, amt: 2000,
},
{
name: 'Page E', uv: 1890, pv: 4800, amt: 2181,
},
{
name: 'Page F', uv: 2390, pv: 3800, amt: 2500,
},
{
name: 'Page G', uv: 3490, pv: 4300, amt: 2100,
},
];
class Example extends PureComponent {
render() {
return (
<BarChart
width={500}
height={300}
data={data1}
margin={{
top: 5, right: 30, left: 20, bottom: 5,
}}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="name" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="pv" fill="#8884d8" />
<Bar dataKey="uv" fill="#82ca9d" />
</BarChart>
);
}
}
const data = [
{
key: "1",
name: "John Brown",
age: 32,
address: "New York No. 1 Lake Park"
},
{
key: "2",
name: "Joe Black",
age: 42,
address: "London No. 1 Lake Park"
},
{
key: "3",
name: "Jim Green",
age: 32,
address: "Sidney No. 1 Lake Park"
},
{
key: "4",
name: "Jim Red",
age: 32,
address: "London No. 2 Lake Park"
}
];
const chartData = [
{ year: "1991", value: 3 },
{ year: "1992", value: 4 },
{ year: "1993", value: 3.5 },
{ year: "1994", value: 5 },
{ year: "1995", value: 4.9 },
{ year: "1996", value: 6 },
{ year: "1997", value: 7 },
{ year: "1998", value: 9 },
{ year: "1999", value: 13 }
];
class App extends React.Component {
state = {
searchText: "",
searchedColumn: ""
};
getColumnSearchProps = (dataIndex) => ({
filterDropdown: ({
setSelectedKeys,
selectedKeys,
confirm,
clearFilters
}) => (
<div style={{ padding: 8 }}>
<Input
ref={(node) => {
this.searchInput = node;
}}
placeholder={`Search ${dataIndex}`}
value={selectedKeys[0]}
onChange={(e) =>
setSelectedKeys(e.target.value ? [e.target.value] : [])
}
onPressEnter={() =>
this.handleSearch(selectedKeys, confirm, dataIndex)
}
style={{ marginBottom: 8, display: "block" }}
/>
<Space>
<Button
type="primary"
onClick={() => this.handleSearch(selectedKeys, confirm, dataIndex)}
icon={<SearchOutlined />}
size="small"
style={{ width: 90 }}
>
Search
</Button>
<Button
onClick={() => this.handleReset(clearFilters)}
size="small"
style={{ width: 90 }}
>
Reset
</Button>
<Button
type="link"
size="small"
onClick={() => {
confirm({ closeDropdown: false });
this.setState({
searchText: selectedKeys[0],
searchedColumn: dataIndex
});
}}
>
Filter
</Button>
</Space>
</div>
),
filterIcon: (filtered) => (
<SearchOutlined style={{ color: filtered ? "#1890ff" : undefined }} />
),
onFilter: (value, record) =>
record[dataIndex]
? record[dataIndex]
.toString()
.toLowerCase()
.includes(value.toLowerCase())
: "",
onFilterDropdownVisibleChange: (visible) => {
if (visible) {
setTimeout(() => this.searchInput.select(), 100);
}
},
render: (text) =>
this.state.searchedColumn === dataIndex ? (
<Highlighter
highlightStyle={{ backgroundColor: "#ffc069", padding: 0 }}
searchWords={[this.state.searchText]}
autoEscape
textToHighlight={text ? text.toString() : ""}
/>
) : (
text
)
});
handleSearch = (selectedKeys, confirm, dataIndex) => {
confirm();
this.setState({
searchText: selectedKeys[0],
searchedColumn: dataIndex
});
};
handleReset = (clearFilters) => {
clearFilters();
this.setState({ searchText: "" });
};
render() {
const columns = [
{
title: "Name",
dataIndex: "name",
key: "name",
width: "30%",
...this.getColumnSearchProps("name")
},
{
title: "Age",
dataIndex: "age",
key: "age",
width: "20%",
...this.getColumnSearchProps("age")
},
{
title: "Address",
dataIndex: "address",
key: "address",
...this.getColumnSearchProps("address"),
sorter: (a, b) => a.address.length - b.address.length,
sortDirections: ["descend", "ascend"]
},
{
title: "Charts",
render: () => (
<>
<Example />
</>
)
}
];
return <Table columns={columns} dataSource={data} />;
}
}
ReactDOM.render(<App />, document.getElementById("container"));
I have used recharts library for Charts.
Here is the Github link for your example: https://github.com/siddharth-sunchu/antd-chart-example
I added some pictures in my app that are called from an array. Now I need another array to have text which includes a title and some description for these images.
How can I create this array of text that when an image is clicked, the specific title and description would be shown for that image?
This is the code where pictures are displayed on the Home Screen of the app.
import { StatusBar } from "expo-status-bar";
import Icon from "react-native-vector-icons/FontAwesome";
import {
StyleSheet,
Text,
View,
Image,
FlatList,
Dimensions,
TouchableOpacity,
} from "react-native";
import Header from '../components/Header';
var loadImageCount = 6;
export default class PicFlatlist extends Component {
constructor(props){
super(props);
this.state = {
loadImageCount: 6,
images: [
{ url: require("../assets/pic_1.jpg"), id: 1 },
{ url: require("../assets/pic_2.jpg"), id: 2 },
{ url: require("../assets/pic_3.jpg"), id: 3 },
{ url: require("../assets/pic_4.jpg"), id: 4 },
{ url: require("../assets/pic_5.jpg"), id: 5 },
{ url: require("../assets/pic_6.jpg"), id: 6 },
{ url: require("../assets/pic_7.jpg"), id: 7 },
{ url: require("../assets/pic_8.jpg"), id: 8 },
{ url: require("../assets/pic_9.jpg"), id: 9 },
{ url: require("../assets/pic_10.jpg"), id: 10 },
{ url: require("../assets/pic_11.jpg"), id: 11 },
{ url: require("../assets/pic_12.jpg"), id: 12 },
{ url: require("../assets/pic_13.jpg"), id: 13 },
{ url: require("../assets/pic_14.jpg"), id: 14 },
{ url: require("../assets/pic_15.jpg"), id: 15 },
{ url: require("../assets/pic_16.jpg"), id: 16 },
{ url: require("../assets/pic_17.jpg"), id: 17 },
{ url: require("../assets/pic_18.jpg"), id: 18 },
{ url: require("../assets/pic_19.jpg"), id: 19 },
{ url: require("../assets/pic_20.jpg"), id: 20 },
{ url: require("../assets/pic_21.jpg"), id: 21 },
{ url: require("../assets/pic_22.jpg"), id: 22 },
{ url: require("../assets/pic_23.jpg"), id: 23 },
{ url: require("../assets/pic_24.jpg"), id: 24 },
{ url: require("../assets/pic_25.jpg"), id: 25 },
{ url: require("../assets/pic_26.jpg"), id: 26 },
{ url: require("../assets/pic_27.jpg"), id: 27 },
{ url: require("../assets/pic_28.jpg"), id: 28 },
{ url: require("../assets/pic_29.jpg"), id: 29 },
{ url: require("../assets/pic_30.jpg"), id: 30 },
{ url: require("../assets/pic_31.jpg"), id: 31 },
{ url: require("../assets/pic_32.jpg"), id: 32 },
{ url: require("../assets/pic_33.jpg"), id: 33 },
{ url: require("../assets/pic_34.jpg"), id: 34 },
{ url: require("../assets/pic_35.jpg"), id: 35 },
{ url: require("../assets/pic_36.jpg"), id: 36 },
{ url: require("../assets/pic_37.jpg"), id: 37 },
{ url: require("../assets/pic_38.jpg"), id: 38 },
{ url: require("../assets/pic_39.jpg"), id: 39 },
{ url: require("../assets/pic_40.jpg"), id: 40 },
{ url: require("../assets/pic_41.jpg"), id: 41 },
{ url: require("../assets/pic_42.jpg"), id: 42 },
{ url: require("../assets/pic_43.jpg"), id: 43 },
{ url: require("../assets/pic_44.jpg"), id: 44 },
{ url: require("../assets/pic_45.jpg"), id: 45 },
{ url: require("../assets/pic_46.jpg"), id: 46 },
{ url: require("../assets/pic_47.jpg"), id: 47 },
],
};
}
loadMore = () => {
var ImageCount = this.state.loadImageCount + 12;
this.setState({ loadImageCount: ImageCount });
}
static navigationOptions = () => {
return {
header: (null),
};
}
renderFooter = () => {
if(this.state.loadImageCount < this.state.images.length){
return (
<View style={styles.buttonRow}>
<Icon.Button
name="sort"
backgroundColor="#ffa500"
onPress={() => {this.loadMore()}}
>
<Text style={{ fontSize: 15 }}>View More</Text>
</Icon.Button>
</View>
);
}
else{
return (
null
)
}
}
render(){
return (
<View >
<View style={{width:"100%",height:undefined,paddingTop:StatusBar.currentHeight}}>
<Header />
</View>
<View style={styles.outerContainer}>
<FlatList
data={this.state.images.slice(0, this.state.loadImageCount)}
key={"2"}
numColumns={2}
contentContainerStyle={styles.homescreen}
keyExtractor={(item) => item.id.toString()}
ListFooterComponent={this.renderFooter}
renderItem={({ item }) => (
<TouchableOpacity
activeOpacity={0.8}
onPress={() =>
this.props.navigation.navigate("Image Details", {
SelectedImage: [item],
})
}
>
<Image
source={item.url}
style={{
width: Dimensions.get("window").width * 0.45,
height: Dimensions.get("window").width * 0.55,
borderWidth: 2,
borderColor: "white",
resizeMode: "cover",
marginVertical: Dimensions.get("window").width * 0.02,
marginHorizontal: Dimensions.get("window").width * 0.02,
}}
/>
</TouchableOpacity>
)}
/>
</View>
</View>
);};
}
const styles = StyleSheet.create({
homescreen: {
width: Dimensions.get("window").width,
alignItems: "center",
justifyContent: "center",
height: undefined,
paddingBottom: Dimensions.get("window").height * 0.1,
backgroundColor: 'white'
},
outerContainer: {
position: "relative",
marginTop: Dimensions.get("window").height * 0.05,
},
buttonRow: {
margin: 15,
flexDirection: "row",
alignContent: "center",
alignSelf: "center",
justifyContent: "center",
},
});
This is the code for the page when an image is clicked on:
import React, { Component, useState } from 'react';
import {
StyleSheet,
Text,
View,
Image,
FlatList,
Dimensions
} from 'react-native';
import { NavigationStackProp } from "react-navigation-stack";
import Header from '../components/Header';
import BackHeader from '../components/BackHeader';
var count = 0;
interface Props{
navigation: NavigationStackProp
}
interface State{
images: any
}
export default class ImageDetails extends Component<Props,State> {
constructor(props) {
super(props);
this.state = {
images: this.props.navigation.getParam("SelectedImage")
};
}
render () {
return (
<View>
<View style={{width:"100%",height:undefined}}> //,paddingTop:StatusBar.currentHeight
<BackHeader />
</View>
<FlatList
data={this.state.images}
numColumns={1}
contentContainerStyle={styles.homescreen}
keyExtractor={(item) => item.id.toString()}
renderItem={(item) => this.loadImage(item)}
/>
</View>
);
}
loadImage = (item) => {
return (
<View style={styles.homescreen}>
<Image
source={item.item.url}
style={{
width: Dimensions.get("window").width * 0.99,
height: Dimensions.get("window").height * 0.73,
borderWidth: 2,
borderColor: "white",
resizeMode: "cover",
marginVertical: Dimensions.get("window").width * 0.02,
marginHorizontal: Dimensions.get("window").width * 0.02,
}}
/>
<Text>Miniature Description</Text>
</View>
);
};
}
const styles = StyleSheet.create({
homescreen: {
position: "relative",
width: Dimensions.get("window").width,
alignItems: "center",
alignSelf: 'center',
justifyContent: "center",
},
});
So I find this answer from Expo Community on Discord. For creating an array, you can either create it inside the main file of your project or a better approach is to create an extra file and add your array file in it and then call it inside the main file. For instance, this is an extra file in my code for creating a array.
image1: {
title: "Cool Image # 1",
description: `People setting in a garden`,
},
image2: {
title: "Cool Image # 1",
description: `People setting in a garden`,
},
image3: {
title: "Cool Image # 1",
description: `People setting in a garden`,
},
image4: {
title: "Cool Image # 1",
description: `People setting in a garden`,
},
image5: {
title: "Cool Image # 1",
description: `People setting in a garden`,
},
};
And this is my main file calling the array.
constructor(props) {
super(props);
this.state = {
loadImageCount: 6,
images: [
{
url: require("../assets/pic_1.jpg"),
id: 1,
title: ImageData["image1"].title,
description: ImageData["image1"].description,
},
{
url: require("../assets/pic_2.jpg"),
id: 2,
title: "cool image #2",
description: "Some people sitting in a garden",
},
I would like to create a page like this in react native however I don't know how I could implement the radio buttons with data that looks like the following code. an idea of how I could go about itenter image description here
My data looks like this with an option title first then the radio button to choose. To make it simple I would like to create a section with a title and radio buttons that and the data I get them in a table like this one
const products = [
{
id: 1,
title : 'Boisson',
data : [
{
label: 'Coca Cola',
price: '500 KMF',
},
{
label: 'Fanta',
price: '250 KMF',
},
{
label: 'Sprite',
price: '200 KMF',
},
]
},
{
id: 2,
title : 'Boisson',
data : [
{
label: 'Coca Cola',
price: '500 KMF',
},
{
label: 'Fanta',
price: '250 KMF',
},
{
label: 'Sprite',
price: '200 KMF',
},
]
},
];
Thank's for your help
You can use react-native-paper radio button check my example:
import React, { Component } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import { RadioButton } from 'react-native-paper';
const products = [
{
id: 1,
title: 'Soft Drinks',
data: [
{
label: 'Coca Cola',
price: '500 KMF',
},
{
label: 'Fanta',
price: '250 KMF',
},
{
label: 'Sprite',
price: '200 KMF',
},
]
},
{
id: 2,
title: 'Juices',
data: [
{
label: 'Mango',
price: '500 KMF',
},
{
label: 'Orange',
price: '250 KMF',
},
{
label: 'Strawberry',
price: '200 KMF',
},
]
},
];
export default class DrinkSelector extends Component {
checkDrink(drink, object) {
var i;
for (i = 0; i < object.length; i++) {
if (object[i].isChecked === 'checked') {
object[i].isChecked = 'unchecked';
}
}
drink.isChecked = "checked";
this.setState({ refresh: true });
}
render() {
return (
<View style={{ flex: 1, padding: 20, backgroundColor: "#f2f2f2" }}>
{products.map((object, d) =>
<View key={d} style={{ justifyContent: 'space-between' }}>
<Text style={{ fontSize: 18, marginBottom: 20 }}>{object.title}</Text>
{object.data.map((drink, i) =>
<View key={i} style={styles.drinkCard}>
<RadioButton value={drink.price} status={drink.isChecked} onPress={() => this.checkDrink(drink, object.data)} />
<Text style={{ fontSize: 20, paddingLeft: 10 }}>{drink.label}</Text>
</View>
)}
</View>
)}
</View>
)
}
}
const styles = StyleSheet.create({
drinkCard: {
paddingLeft: 6,
alignItems: 'center',
flexDirection: 'row',
marginBottom: 16,
backgroundColor: 'white',
height: 55,
elevation: 1,
borderRadius: 4,
}
})
I want to custom a screen same:
so I use Flastlist and check if the item is header I will set with item = window.with and if not width item = window.width/3. But its error.
Here is my code:
const { width, height } = Dimensions.get("window")
class App extends React.Component {
constructor() {
super()
this.state = {
data: [
{ name: "Movies", header: true },
{ name: "Interstellar", header: false },
{ name: "Dark Knight", header: false },
{ name: "Pop", header: false },
{ name: "Music", header: true },
{ name: "Adams", header: false },
{ name: "Nirvana", header: false },
{ name: "Amrit Maan", header: false },
{ name: "Oye Hoye", header: false },
{ name: "Eminem", header: false },
{ name: "Places", header: true },
{ name: "Jordan", header: false },
{ name: "Punjab", header: false },
{ name: "Ludhiana", header: false },
{ name: "Jamshedpur", header: false },
{ name: "India", header: false },
{ name: "People", header: true },
{ name: "Jazzy", header: false },
{ name: "Appie", header: false },
{ name: "Baby", header: false },
{ name: "Sunil", header: false },
{ name: "Arrow", header: false },
{ name: "Things", header: true },
{ name: "table", header: false },
{ name: "chair", header: false },
{ name: "fan", header: false },
{ name: "cup", header: false },
{ name: "cube", header: false }
],
stickyHeaderIndices: []
};
}
renderItem(item) {
if (item.header) {
return (
<View style={{ width: width, height: 40, backgroundColor: 'green' }}>
<Text>{item.name}</Text>
</View>
)
} else {
return (
<View style={{
width: width / 3,
height: width / 3,
backgroundColor: 'white',
borderWidth: 1,
borderColor: 'gray'
}}>
<Text>{item.name}</Text>
</View>
)
}
}
render() {
return (
<View style={{ flex: 1, backgroundColor: 'red' }}>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
this.renderItem(item)
)}
keyExtractor={item => item.name}
/>
</View>
);
}
}
export default App;
and my result
I have the error: an item isn't header is a row, but I want to show 3 item in a row.
When added number column = 3 in flastlist with code :
<FlatList
numColumns={3}
data={this.state.data}
renderItem={({ item }) => (this.renderItem(item))}
keyExtractor={item => item.name}
/>
I have result
How can I fix show 3 item in a row?
Thank you very much.
I think you forgot to add numColumns = { 3 } in Flatlist props. Here you get detail solution to your problem.
I've used nested FlatList to solve this:
const renderCategory = category => (
<View>
<Text>{category}</Text>
<FlatList
data={itemsByCategory[category]}
renderItem={({item, index}) => renderItem(item)}
keyExtractor={(item, index) => index.toString()}
numColumns={3}
/>
</View>
);
return (
<FlatList
data={Object.keys(itemsByCategory)}
renderItem={({item, index}) => renderCategory(item)}
keyExtractor={(item, index) => index.toString()}
/>
);
Using flexWrap: 'wrap' and flexDirection: 'row' in your main container should resolve your problem.
<View style={{ flex: 1, backgroundColor: 'red', flexWrap: 'wrap', flexDirection: 'row' }}>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
this.renderItem(item)
)}
keyExtractor={item => item.name}
/>
</View>