Antd table cell render charts - javascript

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

Related

Flatlist scroll doesn't work on android emulator

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
},

adding select options to select acording to another select

I have a formik form that has three field select one for for country and one for city one for country number code i have the the info in a data.js
export const countries = {
en: [
{ value: 'jo', label: 'Jordan',
{ value: 'ae', label: 'United Arab Emirates},
{ value: 'sa', label: 'Saudi Arabia'},
{ value: 'iq', label: 'Iraq', },
{ value: 'kw', label: 'Kuwait'},
{ value: 'qa', label: 'Qatar'},
{ value: 'lb', label: 'Lebanon'}
],
ar: [
{ value: 'jo', label: 'الاردن' },
{ value: 'ae', label: 'الامرات العربيه المتحدة' },
{ value: 'sa', label: 'السعوديه' },
{ value: 'iq', label: 'العراق' },
{ value: 'kw', label: 'الكويت' },
{ value: 'qa', label: 'قطر' },
{ value: 'lb', label: 'لبنان' }
] }
export const cities = {
en: {
ae: [
{ value: 'dubai', label: 'Dubai' },
{ value: 'abudhabi', label: 'Abu Dhabi' }
],
jo: [{ value: 'amman', label: 'Amman' }],
qa: [{ value: 'doha', label: 'Doha' }],
kw: [{ value: 'kuwait', label: 'Kuwait' }],
sa: [
{ value: 'riyadh', label: 'Riyadh' },
{ value: 'jeddah', label: 'Jeddah' },
{ value: 'khobar', label: 'Khobar' },
{ value: 'dhahran', label: 'Dhahran' },
{ value: 'dammam', label: 'Dammam' },
],
lb: [{ value: 'beirut', label: 'Beirut' }],
iq: [{ value: 'baghdad', label: 'Baghdad' }]
},
ar: {
ae: [
{ value: 'dubai', label: 'دبي' },
{ value: 'abudhabi', label: 'ابو ظبي' }
],
jo: [{ value: 'amman', label: 'عمان' }],
qa: [{ value: 'doha', label: 'الدوحه' }],
kw: [{ value: 'kuwait', label: 'الكويت' }],
sa: [
{ value: 'riyadh', label: 'الرياض' },
{ value: 'jeddah', label: 'جدة' },
{ value: 'khobar', label: 'الخبر' },
{ value: 'dhahran', label: 'الظهران' },
{ value: 'dammam', label: 'الدمام' },
],
lb: [{ value: 'beirut', label: 'بيروت' }],
iq: [{ value: 'baghdad', label: 'بغداد' }]
} }
export const countryCodes = [
{ value: '+962', label: '+962', code: 'jo' },
{ value: '+966', label: '+966', code: 'sa' },
{ value: '+965', label: '+965', code: 'kw' },
{ value: '+964', label: '+964', code: 'iq' },
{ value: '+961', label: '+961', code: 'lb' },
{ value: '+974', label: '+974', code: 'qa' },
{ value: '+971', label: '+971', code: 'ae' }
]
I'm mapping over the counters and put every one label in an option tag, when select a country should only return the cites of that country and auto select the first value for the cites and select the correct phone code
here's my form
<Formik
initialValues={initialValues}
validationSchema={props.params !== 'ar' ? FormSchmaEn : FormSchmaAr}
onSubmit={() => {
handleSubmit()
setRenderPreferredContactMethod(() => true)
}}
>
{formikProps => {
const { values, setFieldValue } = formikProps;
return (
<div className='container' style={{ marginTop: '150px' }}>
<Form className="container">
<hr style={{ maxWidth: '480px', width: '100%' }} />
<div className="row justify-content-center">
<div className="col form-input" style={{ marginBottom: '10px', width: '100%', maxWidth: "500px" }}>
<Field as="select" name='country' value={values.country} onChange={e => (setFieldValue('country', e.target.value))}
className="form-control" style={props.params !== 'ar' ? { textAlignLast: 'left' } : { textAlignLast: 'right' }}>
{props.params !== 'ar' ? <option value="Country">Country</option> : <option value="Country" hidden>البلد</option>}
{countries[`${props.params}`].map((country, index) => (
<option key={index} value={countries.en[index].label} onChange={e => setFieldValue('city', countries.en[index].cities)}>{country.label}</option>
))}
</Field>
<ErrorMessage name="country" component="div" style={{ color: 'red' }} />
</div>
</div>
<div className="row justify-content-center">
<div className="col form-input" style={{ marginBottom: '10px', width: '100%', maxWidth: "500px" }}>
<Field value="test" as="select" type="text" name='city' className="form-control" style={props.params !== 'ar' ? { textAlignLast: 'left' } : { textAlignLast: 'right' }}>
{props.params !== 'ar' ? <option hidden></option> : <option value="المدينه" hidden>{country.cities}</option>}
{countries[`${props.params}`].map((city, index) => (
<option key={index} >{city.cities.label}</option>
))}
</Field>
<ErrorMessage name="city" component="div" style={{ color: 'red' }} />
</div>
</div>
<div className={props.params !== 'ar' ? "row justify-content-center" : "row justify-content-center flex-row-reverse"}>
<div className="col-4 form-input" style={{ marginBottom: '10px', width: '100%', maxWidth: "150px" }}>
<Field as="select" type="text" name='numberCode' className="form-control" onClick={(e) => setNumberCode(() => e.target.value)}>
<option value="+1" hidden>+1</option>
{countryCodes.map((countryCode, index) => (
<option key={index}>
{countryCodes[index].label}
</option>
))}
</Field>
</div>
<div className="col-8 form-input" style={{ marginBottom: '10px', width: '100%', maxWidth: "350px" }}>
<Field type="text" name="phoneNumber" className={props.params !== 'ar' ? "form-control" : "form-control ar"} placeholder="111 111" onKeyUp={(e) => setPhoneNumber(() => numberCode + e.target.value)} />
<ErrorMessage name="phoneNumber" component="div" style={{ color: 'red' }} />
</div>
</div>
</Form>
</div>
)
}}
</Formik>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Upon selecting the country, you need to store your selection in some sort of state (useState). Then based on that, you can easily then conditionally render what you want (the cities based on stored value).
Some pseudo code:
on select - set country => jo.
if country => render city selector.
if en => output english cities list.
Edit: I'd also suggest using a more up to date react.

Building a dashboard with fluent-ui in React and the cards and table appear at bottom of screen when they're not supposed to

I am following a tutorial to build a dashboard using fluentui in React, and am going to customise it and change it afterwards. However I have followed the tutorial exactly and got no errors but for some reason the cards and table appear at bottom of screen, not looking like how they are styled and the table has no data in it.
My code is exactly the same as the tutorial found here: https://www.youtube.com/watch?v=P9s6dsdu_9c. I will post a screenshot below of how mine looks atm and all relevant code below that.
code:
App.js
import React from 'react';
import { BrowserRouter as Router} from 'react-router-dom';
import './App.css';
import 'office-ui-fabric-react/dist/css/fabric.css';
import Chart3 from './Components/Chart/Chart3';
import Jumbo from './Components/Jumbotron/Jumbotron';
import Footer from './Components/Footer/Footer';
import Header from './Components/Navbar/Navbar';
import Navigation from './Navigation/Navigation';
import CardsSection from './Components/Cards/Card';
import Table from './Components/Table/Table';
function App() {
return (
<div className="ms-grid" dir="ltr">
<div className="ms-grid-row">
<div className="ms-grid-col ms-sm1 ms-xl1">
<Navigation />
</div>
<div className="ms-Grid-col ms-sm11 ms-xl11 main-element">
<div className="ms-Grid-row">
<CardsSection />
</div>
<div className="ms-Grid-row">
<Table />
</div>
</div>
</div>
</div>
);
}
export default App;
Navigation.js
import React from 'react';
import {Nav, initializeIcons} from '#fluentui/react';
const Links = [
{
links: [
{
name: 'Dashboard',
url: '/',
key: 'key1',
iconProps: {
iconName: 'News',
styles: {
root: {
fontSize: 20,
color: '#106ebe'
}
}
}
},
{
name: 'Settings',
url: '/',
key: 'key2',
iconProps: {
iconName: 'SwitcherStartEnd',
styles: {
root: {
fontSize: 20,
color: '#106ebe'
}
}
}
},
{
name: 'Charts',
url: '/',
key: 'key3',
iconProps: {
iconName: 'StackedLineChart',
styles: {
root: {
fontSize: 20,
color: '#106ebe'
}
}
}
}
]
}
]
//Styling for the navigation
const navigationStyles = {
root: {
height: '100vh',
boxSizing: 'border-box',
border: '1px solid',
overFlowY: 'auto',
paddingTop: '10vh'
}
}
const Navigation = () => {
initializeIcons(); //initalizing so we can see icons when we use them
return (
<Nav
groups={Links}
selectedKey="key1"
styles={navigationStyles}
/>
)
}
export default Navigation;
Card.js
import React from 'react';
import { Card } from '#uifabric/react-cards';
import { Text, initializeIcons} from '#fluentui/react';
import 'office-ui-fabric-react/dist/css/fabric.css';
const container = {
display: 'flex',
justifyContent: 'center',
margin: '10vh 0'
}
const icon = {
fontSize: 24,
padding: 15,
verticalAlign: 'middle',
paddingLeft: 0,
color: '#0078d4'
}
const styles = {
cardStyles: {
root: {
backgroundColor: 'white',
padding: 20,
borderTop: '5px solid #0078d4',
width: '90%',
maxWidth: '90%',
margin: 'auto'
}
},
header: {
root: {
fontSize: 20,
fontWeight: 'bold',
}
},
amount: {
root: {
fontSize: 26,
paddingBottom: 20,
paddingTop: 30,
}
},
amount: {
root: {
fontSize: 16,
fontWeight: 'bold',
color: '#0078d4'
}
}
}
const cards = [
{
title: 'current balance',
amount: '21',
icon: 'Money',
percentage: '2.3',
},
{
title: 'current expenses',
amount: '215',
icon: 'PaymrntCard',
percentage: '2.3',
},
{
title: 'current income',
amount: '21',
icon: 'Savings',
percentage: '2.3',
},
]
const CardsSection= () => {
initializeIcons();//initailizing icons so can be used
return (
<div style={container}>
{cards.map((card) => (
<div className="s-Grid-col ms-sm3 ms-xl3">
<Card styles={styles.cardStyle}>
<Card.Section>
<Card.Item>
<i style={icon} className={`ms-Icon ms-Icon--${card.icon}`} aria-hidden="true"></i>
<Text styles={styles.header}>{card.title}</Text>
</Card.Item>
<Card.Item>
<Text styles={styles.amount}>{card.amount}</Text>
</Card.Item>
<Card.Item>
<Text styles={styles.percentage}>{card.percentage}%</Text>
</Card.Item>
</Card.Section>
</Card>
</div>
))}
</div>
)
}
export default CardsSection;
Table.js
import React from 'react';
import { DetailsList } from '#fluentui/react';
import { mergeStyleSets } from 'office-ui-fabric-react/lib/Styling';
import 'office-ui-fabric-react/dist/css/fabric.css';
const operations = [
{
from: '0000 0284 7529 304304',
to: '0000 9876 9876 5678 4123',
amount: '1.343',
date: '20-05-2020'
},
{
from: '0000 0284 7529 304304',
to: '0000 9876 9876 5678 4123',
amount: '1.343',
date: '20-05-2020'
},
{
from: '0000 0284 7529 304304',
to: '0000 9876 9876 5678 4123',
amount: '1.343',
date: '20-05-2020'
},
{
from: '0000 0284 7529 304304',
to: '0000 9876 9876 5678 4123',
amount: '1.343',
date: '20-05-2020'
},
{
from: '0000 0284 7529 304304',
to: '0000 9876 9876 5678 4123',
amount: '1.343',
date: '20-05-2020'
}
]
const columns = [
{ key: 'column1', name: 'From', fieldName:'From', minWidth: 100, maxWidth: 300, isResizable: true },
{ key: 'column2', name: 'To', fieldName:'To', minWidth: 100, maxWidth: 300, isResizable: true },
{ key: 'column3', name: 'Amount', fieldName:'Amount', minWidth: 100, maxWidth: 300, isResizable: true },
{ key: 'column4', name: 'Date', fieldName:'Date', minWidth: 100, maxWidth: 300, isResizable: true },
]
const classNames = mergeStyleSets({
teble: {
margin: 'auto'
}
});;
const Table = () => {
return (
<div data-is-scrollable={true}>
<div className={`s-Grid-col ms-sm9 ms-xl9 ${classNames.table}`}>
<DetailsList
items={operations}
columns={columns}
selectionMode={0}
/>
</div>
</div>
)
}
export default Table
In Table.js, there is a typo in the className. It has to be ms-Grid-col and not s-Grid-col

how to create a radio button section with a data table in react native?

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,
}
})

React native Flatlist grid and item header

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>

Categories