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.
Related
I want to set the background color of the round/oval TouchableOpacity buttons beneath the headings to blue when they are tapped by the user, and no background color when they are not tapped. I have heard that this can be achieved by managing the states of the component itself.
Here is my code for reference:
import React, {useState} from 'react';
import {
StyleSheet,
Text,
View,
Button,
FlatList,
Dimensions,
TouchableOpacity,
Image,
} from 'react-native';
import Modal from 'react-native-modal';
const {width: screenWidth} = Dimensions.get('screen');
// screen width Multiply by 0.8
const Footer = () => {
return (
<View>
<Text style={{color: '#fff', fontSize: 20}}>Reviews</Text>
<View style={{flexDirection: 'row', alignItems: 'center', marginTop: 20}}>
<Image
source={require('../assets/five-stars.png')}
style={{width: 90, height: 18}}
/>
<Text style={{marginLeft: 10}}>& Up</Text>
</View>
<View style={{flexDirection: 'row', marginTop: 30}}>
<TouchableOpacity
style={{
backgroundColor: '#525252',
width: 200,
paddingTop: 20,
paddingBottom: 20,
alignItems: 'center',
borderTopLeftRadius: 22,
}}>
<Text>Reset</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
backgroundColor: '#00ACED',
width: 200,
alignItems: 'center',
paddingTop: 20,
paddingBottom: 20,
borderTopRightRadius: 23,
}}>
<Text>Apply</Text>
</TouchableOpacity>
</View>
</View>
);
};
const renderItem = ({item: {title, data, key}}) => (
<View>
<Text style={styles.headingText}>{title}</Text>
<View style={styles.item}>
{data.map(el => (
<TouchableOpacity
key={el.key}
style={[
{
backgroundColor: el.isCheck ? '#00ACED' : 'transparent',
padding: 20,
borderColor: '#185268',
borderWidth: 2,
borderRadius: 40,
marginBottom: 10,
marginRight: 10,
},
]}>
<Text style={styles.btnText}>{el.name}</Text>
</TouchableOpacity>
))}
</View>
</View>
);
const SandboxScreen = () => {
const [isModalVisible, setModalVisible] = useState(false);
const [data, setData] = useState([
{
key: 'id-1',
title: 'Workshop Category',
data: [
{name: 'BodyShops', isCheck: false, key: 'id-5'},
{name: 'Electric Cars', isCheck: true, key: 'id-6'},
{name: 'Performance Shops', isCheck: false, key: 'id-7'},
],
},
{
key: 'id-2',
title: 'Vehicle Category',
data: [
{name: 'Cars', isCheck: false, key: 'id-8'},
{name: 'Trucks', isCheck: true, key: 'id-9'},
{name: 'Motorbikes', isCheck: false, key: 'id-10'},
],
},
{
key: 'id-3',
title: 'Services',
data: [
{name: 'Accident Repair', isCheck: false, key: 'id-11'},
{name: 'AC System Diagnosis', isCheck: false, key: 'id-12'},
{name: 'Car Polishing / Detailing', isCheck: false, key: 'id-13'},
{name: 'Electric / Hybrid System Repair', isCheck: true, key: 'id-14'},
{name: 'General Mechanical Work', isCheck: true, key: 'id-15'},
],
},
{
key: 'id-4',
title: 'Brands',
data: [
{name: 'FORD', isCheck: false, key: 'id-16'},
{name: 'BMW', isCheck: false, key: 'id-17'},
{name: 'BMW', isCheck: false, key: 'id-18'},
{name: 'AUDI', isCheck: false, key: 'id-19'},
{name: 'JAGUAR', isCheck: false, key: 'id-20'},
{name: 'FERRARI', isCheck: true, key: 'id-21'},
{name: 'LAMBORGHINI', isCheck: false, key: 'id-22'},
],
},
]);
const toggleModal = () => {
setModalVisible(prevState => !prevState);
};
return (
<View
style={[
{
flex: 1,
backgroundColor: '#252525',
},
]}>
<View style={styles.container}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item.key}
ListFooterComponent={Footer}
/>
</View>
{/* <Button title="Show modal" onPress={toggleModal} />
<Modal
isVisible={isModalVisible}
animationIn="slideInRight"
animationOut="slideOutRight"
animationInTiming={500}
animationOutTiming={500}
hasBackdrop={true}
backdropColor="#252525"
backdropOpacity={0.8}
backdropTransitionInTiming={500}
backdropTransitionOutTiming={500}
onBackdropPress={() => setModalVisible(false)}
style={{alignItems: 'flex-end', margin: 0}}>
<View
style={{
backgroundColor: 'white',
flex: 1,
paddingTop: 50,
width: screenWidth * 0.7,
}}>
<View style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</View>
</View>
</Modal> */}
</View>
);
};
export default SandboxScreen;
const styles = StyleSheet.create({
container: {},
button: {
backgroundColor: 'green',
padding: 13,
},
headingText: {
color: '#fff',
fontSize: 20,
marginBottom: 20,
},
item: {
flexDirection: 'row',
flexWrap: 'wrap',
marginBottom: 40,
},
});
Please anyone guide me on how this can be achieve by providing code example related to my above code.
Here is your original solution: Snack
import React, { useState, useEffect } from 'react';
import {
StyleSheet,
Text,
View,
Button,
FlatList,
Dimensions,
TouchableOpacity,
SectionList,
Image,
} from 'react-native';
// import Modal from 'react-native-modal';
const { width: screenWidth } = Dimensions.get('screen');
// screen width Multiply by 0.8
const SandboxScreen = () => {
const [isModalVisible, setModalVisible] = useState(false);
const [data, setData] = useState([
{
key: 'id-1',
title: 'Workshop Category',
data: [
{ name: 'BodyShops', isCheck: false, key: 'id-5' },
{ name: 'Electric Cars', isCheck: true, key: 'id-6' },
{ name: 'Performance Shops', isCheck: false, key: 'id-7' },
],
},
{
key: 'id-2',
title: 'Vehicle Category',
data: [
{ name: 'Cars', isCheck: false, key: 'id-8' },
{ name: 'Trucks', isCheck: true, key: 'id-9' },
{ name: 'Motorbikes', isCheck: false, key: 'id-10' },
],
},
{
key: 'id-3',
title: 'Services',
data: [
{ name: 'Accident Repair', isCheck: false, key: 'id-11' },
{ name: 'AC System Diagnosis', isCheck: false, key: 'id-12' },
{ name: 'Car Polishing / Detailing', isCheck: false, key: 'id-13' },
{
name: 'Electric / Hybrid System Repair',
isCheck: true,
key: 'id-14',
},
{ name: 'General Mechanical Work', isCheck: true, key: 'id-15' },
],
},
{
key: 'id-4',
title: 'Brands',
data: [
{ name: 'FORD', isCheck: false, key: 'id-16' },
{ name: 'BMW', isCheck: false, key: 'id-17' },
{ name: 'BMW', isCheck: false, key: 'id-18' },
{ name: 'AUDI', isCheck: false, key: 'id-19' },
{ name: 'JAGUAR', isCheck: false, key: 'id-20' },
{ name: 'FERRARI', isCheck: true, key: 'id-21' },
{ name: 'LAMBORGHINI', isCheck: false, key: 'id-22' },
],
},
]);
const Footer = () => {
return (
<View>
<Text style={{ color: '#fff', fontSize: 20 }}>Reviews</Text>
<View
style={{ flexDirection: 'row', alignItems: 'center', marginTop: 20 }}>
<Text style={{ marginLeft: 10 }}>& Up</Text>
</View>
<View style={{ flexDirection: 'row', marginTop: 30 }}>
<TouchableOpacity
onPress={() => {
setData((prev) => {
//Here I have update your all isCheck prop to false;
let dat = prev.map((item, index) =>
item.data.map((v) => (v.isCheck = false))
);
return [...prev];
});
}}
style={{
backgroundColor: '#525252',
width: 200,
paddingTop: 20,
paddingBottom: 20,
alignItems: 'center',
borderTopLeftRadius: 22,
}}>
<Text>Reset</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
//You can call an API to store your results or directly save the results in your Storage.
alert('Results has been applied!');
}}
style={{
backgroundColor: '#00ACED',
width: 200,
alignItems: 'center',
paddingTop: 20,
paddingBottom: 20,
borderTopRightRadius: 23,
}}>
<Text>Apply</Text>
</TouchableOpacity>
</View>
</View>
);
};
const renderItem = ({ item: { title, data, key }, index }) => (
<View>
<Text style={styles.headingText}>{title}</Text>
<View style={styles.item}>
{data.map((el) => (
<TouchableOpacity
onPress={() => {
setData((prev) => {
el.isCheck = !el.isCheck; // `!` means if a value is true then make it false else make it true;
let dat = [el, ...prev[index].data];
// Here I'm spreading the both objects and merging the data;
return [...prev];
// Retruned the updated values by spreading it.
});
}}
key={el.key}
style={[
{
backgroundColor: el.isCheck ? '#00ACED' : 'transparent',
padding: 20,
borderColor: '#185268',
borderWidth: 2,
borderRadius: 40,
marginBottom: 10,
marginRight: 10,
},
]}>
<Text style={styles.btnText}>{el.name}</Text>
</TouchableOpacity>
))}
</View>
</View>
);
const toggleModal = () => {
setModalVisible((prevState) => !prevState);
};
return (
<View
style={[
{
flex: 1,
backgroundColor: '#252525',
},
]}>
<View style={styles.container}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={(item) => item.key}
ListFooterComponent={Footer}
/>
</View>
{/* <Button title="Show modal" onPress={toggleModal} />
<Modal
isVisible={isModalVisible}
animationIn="slideInRight"
animationOut="slideOutRight"
animationInTiming={500}
animationOutTiming={500}
hasBackdrop={true}
backdropColor="#252525"
backdropOpacity={0.8}
backdropTransitionInTiming={500}
backdropTransitionOutTiming={500}
onBackdropPress={() => setModalVisible(false)}
style={{alignItems: 'flex-end', margin: 0}}>
<View
style={{
backgroundColor: 'white',
flex: 1,
paddingTop: 50,
width: screenWidth * 0.7,
}}>
<View style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</View>
</View>
</Modal> */}
</View>
);
};
export default SandboxScreen;
const styles = StyleSheet.create({
container: {},
button: {
backgroundColor: 'green',
padding: 13,
},
headingText: {
color: '#fff',
fontSize: 20,
marginBottom: 20,
},
item: {
display: 'flex',
flexDirection: 'row',
marginBottom: 40,
},
});
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 have a table in pxp-ui and have this column:
subsystemId: {
type: 'AutoComplete',
isSearchable: true,
label: 'Subsystem Id',
variant: 'outlined',
grid: true,
form: true,
store: {
dataReader,
method: 'GET',
url: `pxp/Subsystem/list`,
idDD: 'subsystemId',
descDD: 'name',
parFilters: 'name',
params: {
sort: 'name',
start: '0',
limit: '50',
dir: 'DESC',
sort: 'subsystemId',
},
renderOption: (option) => (<span>
<b>{option.name}</b> <br />
</span>)
}
validate: {
shape: Yup.string().required(' es requerido'),
},
At this moment it is only showing the id and not the name of the subsystem
How can I do to show the name instead of the id?
you need to use renderColumn for render the data that you want to render
renderColumn: (row) => {
return (
<div>
<Typography variant="body2" color="inherit">
<b>data1:</b>
{row.someDataInRow1}
</Typography>
<Label color="success">
<b>data2:</b>
{row.someDataInRow2}
</Label>
</div>
);
},
with your example will be this
subsystemId: {
type: 'AutoComplete',
isSearchable: true,
label: 'Subsystem Id',
variant: 'outlined',
grid: true,
form: true,
store: {
dataReader,
method: 'GET',
url: `pxp/Subsystem/list`,
idDD: 'subsystemId',
descDD: 'name',
parFilters: 'name',
params: {
start: '0',
limit: '50',
dir: 'DESC',
sort: 'subsystemId', // only you need 1 sort,
},
renderOption: (option) => (
<span>
<b>{option.name}</b> <br />
</span>
),
},
validate: {
shape: Yup.string().required(' es requerido'),
},
renderColumn: (row) => {
return (
<div>
<Typography variant="body2" color="inherit">
<b>data1:</b>
{row.someDataInRow1}
</Typography>
<Label color="success">
<b>data2:</b>
{row.someDataInRow2}
</Label>
</div>
);
},
},
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>