Pass a variable between the screens React-Native when using RadioButton - parameter-passing

I have created a sort of form and I want to pass a variable to the next screen when press submit.
var states = [
{label: "happy", value: 1},
{label: "sad", value: 2},
{label: "angry", value: 3},
{label: "relaxed", value: 4}
];
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Paragraph style={styles.textStyle}>How are you feeling today ?</Paragraph>
<RadioForm
radio_props={states}
initial={2}
onPress={(value) => {ToastAndroid.show(value.toString(), ToastAndroid.SHORT)}}
buttonSize={30}
buttonOuterSize={40}
selectedButtonColor={'blue'}
selectedLabelColor={'blue'}
labelStyle={{ fontSize: 15, }}
disabled={false}
formHorizontal={false}
/>
<Button title="Submit" onPress={() => this.props.navigation.navigate('ButtonsScreen')}/>
</View>
);
}
}
So, I want to pass variable "value" ( which the user selects ) to the 'ButtonsScreen'.
Anyone has any idea ?

Try this way
export default class App extends Component<Props> {
state = { val: "" }; // set state here
render() {
return (
<View style={styles.container}>
....
<RadioForm
....
onPress={(value) => {
this.setState({ val: value });
}}
....
/>
<Button
title="Submit"
onPress={() =>
this.props.navigation.navigate("ButtonsScreen", {
value: this.state.val,
})
}
/>
</View>
);
}
}

Related

how to add icon in a datagrid in reactjs

I want to add icons inside a datagrid in a specific column.
But I don't even know if it's possible. If so, I want to use inside 'Role' column. I don't know how the implement it inside a datagrid. I searched in the web, but didn't get anything that helps me. So kindly help me figure this out.
this is my code
function DataGridExample() {
const [platform, setPlatform] = useState([]);
const [searchText, setSearchText] = useState('');
const [rows, setRows] = useState([]);
useEffect(() => {
let platformList = [
{ id: 1, role: 'Sender', counter_party: "Bharath", token: "1.000", date:"16-03-2022 06:20 AM", comments:'Test First Transfer' },
{ id: 2, role: "Sender", counter_party: "Harish", token: "1.000" , date:"14-03-2022 08:59 AM", comments:'Testing from hosted'},
{ id: 3, role: "Receiver", counter_party: "Vijay", token: "1.000", date:"14-03-2022 08:53 AM", comments:'Test First Transfer'},
];
setPlatform(platformList);
setRows(platformList);
}, []);
const columns = [
{ field: 'role', headerName: 'Role', width: 150,},
{ field: 'counter_party', headerName: 'Counter Party', width: 200 },
{ field: 'token', headerName: 'Token', width: 150 },
{ field: 'date', headerName: 'Date', width: 200 },
{ field: 'comments', headerName: 'Comments', width: 200 }
];
function escapeRegExp(value) {
return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
const requestSearch = (searchValue) => {
const searchRegex = new RegExp(escapeRegExp(searchValue), 'i');
const filteredRows = platform.filter((row) => {
return Object.keys(row).some((field) => {
return searchRegex.test(row[field].toString());
});
});
setRows(filteredRows);
};
return (
<div>
<div style={{ height: 400, width: '100%' }}>
<Box>
<TextField
variant="outlined"
size='small'
value={searchText}
onChange={(e) => { setSearchText(e.target.value); requestSearch(e.target.value) }}
placeholder="Search..."
InputProps={{
startAdornment: <SearchIcon fontSize="small" color="action" />,
endAdornment: (
<IconButton
title="Clear"
aria-label="Clear"
size="small"
style={{ visibility: searchText ? 'visible' : 'hidden', borderRadius: "57%", paddingRight: "1px", margin: "0", fontSize: "1.25rem" }}
onClick={(e) => { setSearchText(''); setRows(platform) }}
>
<ClearIcon fontSize="small" color="action" />
</IconButton>
),
}}
/>
</Box>
<DataGrid
disableColumnMenu
rows={rows}
columns={columns}
pageSize={10}
rowsPerPageOptions={[10]}
/>
</div>
</div >
);
}
export { DataGridExample };
this is how my table currently looks like
and this is how I want my table to be
you should add custom renderCell in column
this is how i do it
enter image description here
Check the following to insert a material-ui icon in your datagrid.
import React, {useState, useEffect} from "react";
import { FormControlLabel, IconButton } from '#material-ui/core';
import { DataGrid } from "#material-ui/data-grid";
import EditIcon from '#material-ui/icons/Edit';
import { blue } from '#material-ui/core/colors';
const MatEdit = ({ index }) => {
const handleEditClick = () => {
// some action
}
return <FormControlLabel
control={
<IconButton color="secondary" aria-label="add an alarm" onClick={handleEditClick} >
<EditIcon style={{ color: blue[500] }} />
</IconButton>
}
/>
};
const MyComponent= () => {
const rows = [{ id: 1, name: "ABC", email: "xyz#gmail.com" }];
const columns=[
{ field: "name", headerName: "Name" },
{ field: "email", headerName: "Email" },
{
field: "actions",
headerName: "Actions",
sortable: false,
width: 140,
disableClickEventBubbling: true,
renderCell: (params) => {
return (
<div className="d-flex justify-content-between align-items-center" style={{ cursor: "pointer" }}>
<MatEdit index={params.row.id} />
</div>
);
}
}
];
return (
<div style={{ height: 500, width: 500 }}>
<DataGrid rows={rows} columns={columns} />
</div>
)
};
export default MyComponent;
Click here for a sandbox demo

Best way for maping html elements from material ui and rendering by map

<FormControlLabel
control={
<Switch
onChange={(e) => changeSwitchState(e.target.name, e.target.checked)}
color='primary'
name='a'
/>
}
label="A"
/>
<FormControlLabel
control={
<Switch
onChange={(e) => changeSwitchState(e.target.name, e.target.checked)}
color='primary'
name='b'
/>
}
label="B"
/>
<FormControlLabel
control={
<Switch
onChange={(e) => changeSwitchState(e.target.name, e.target.checked)}
color='primary'
name='c'
/>
} label="C" />
<span>D</span>
<InputText
className={inputValidation(inputValues.e, inputValues.f, inputValues.d) ? 'err' : 'validated'}
id='d'
keyfilter="num"
value={inputValues.d}
onChange={e => changeInputValue(e.target.id, e.target.value)}
/>
<span>E</span>
<InputText
className={inputValidation(inputValues.f, inputValues.d, inputValues.e) ? 'errE' : 'validateE'}
id='e'
value={inputValues.e}
onChange={e => changeInputValue(e.target.id, e.target.value)}
mode="decimal"
useGrouping={false}
/>
)
};
here is mine code i want make code shorter and render this inputs and switch buttons by map way can someone explain how to do this and what is best practice and how to noth lost data which one im reciving by props way ?
Best way would to be to setup configuration arrays for this. Ideally you would want to keep your inputs in the "Controlled State" in React so your user interface always represents your state.
Lets first configure a constant which holds the initial configuration of your formControlLabels, which holds information I can read from your code which you supplied.
It might look something like this, and can be defined outside of the component which uses it. Arrays holding objects for each input is ideal, since later we want to use map to render these in your return method.
const formControlLabelConfig = [
{
color: "primary",
name: "a",
label: "A",
state: false
},
{
color: "primary",
name: "b",
label: "B",
state: false
},
{
color: "primary",
name: "c",
label: "C",
state: false
}
];
similiarly for your textInput components
const textInputConfig = [
{
keyFilter: "num",
id: "d",
mode: undefined,
className: "err",
errorClassName: "validated",
useGrouping: undefined,
value: ""
},
{
keyFilter: "num",
id: "e",
mode: "decimal",
className: "errE",
errorClassName: "validateE",
useGrouping: false,
value: ""
}
];
We can setup a state variable using this initial configuration. This would be within the functional component you are using to render the FormControlLabel and InputText components
const [formControlLabelState, setFormControlLabelState] = useState(formControlLabelConfig);
const [textInputConfig, setTextInputConfig] = useState(textInputConfig);
we can then use map to render each component according to its config. I have mocked up something of what you will end up with
import React, { useState } from "react";
const formControlLabelConfig = [
{
color: "primary",
name: "a",
label: "A",
state: false
},
{
color: "primary",
name: "b",
label: "B",
state: false
},
{
color: "primary",
name: "c",
label: "C",
state: false
}
];
const textInputConfig = [
{
keyFilter: "num",
id: "d",
mode: undefined,
className: "err",
errorClassName: "validated",
useGrouping: undefined,
value: ""
},
{
keyFilter: "num",
id: "e",
mode: "decimal",
className: "errE",
errorClassName: "validateE",
useGrouping: false,
value: ""
}
];
const SomeComponentName = () => {
const [formControlLabelState, setFormControlLabelState] = useState(
formControlLabelConfig
);
const [textInputState, setTextInputState] = useState(textInputConfig);
const getInputClassName = () => {
let className = "";
//return the className on validation
return className;
};
const changeInputValue = (id, value) => {
setTextInputState((prevState) => {
const newState = [...prevState];
const index = newState.findIndex((config) => config.id === id);
newState[index].value = value;
return newState;
});
};
const changeSwitchState = (name, chackedState) => {
setFormControlLabelState((prevState) => {
const newState = [...prevState];
const index = newState.findIndex((config) => config.name === name);
newState[index].state = chackedState;
return newState;
});
};
return (
<>
{formControlLabelState.map((config) => (
<FormControlLabel
key={config.id}
control={
<Switch
onChange={(e) =>
changeSwitchState(e.target.name, e.target.checked)
}
color={config.color}
name={config.name}
value={config.checked} //would need to check this. Not sure what attribute is used to set the checked state
/>
}
label="B"
/>
))}
<span>D</span>
{textInputState.map((config) => (
<InputText
key={config.id}
className={() => getInputClassName(config.id)}
id={config.id}
value={config.value}
onChange={(e) => changeInputValue(e.target.id, e.target.value)}
mode={config.mode}
useGrouping={config.useGrouping}
/>
))}
</>
);
};

Adding a prefix icon for the Antd Cascader

I am working with antd cascader and want to add a prefix icon in the cascader. Although there is a provision for a suffix icon in the cascader I could not find a way to add a prefix icon.
import { Cascader } from 'antd';
const options = [
{
value: 'zhejiang',
label: 'Zhejiang',
children: [
{
value: 'hangzhou',
label: 'Hangzhou',
children: [
{
value: 'xihu',
label: 'West Lake',
},
],
},
],
},
{
value: 'jiangsu',
label: 'Jiangsu',
children: [
{
value: 'nanjing',
label: 'Nanjing',
children: [
{
value: 'zhonghuamen',
label: 'Zhong Hua Men',
},
],
},
],
},
];
function onChange(value) {
console.log(value);
}
ReactDOM.render(
<Cascader options={options} onChange={onChange} placeholder="Please select" />,
mountNode,
);
Currently, the cascader looks as :
I want it to look something similar to:
where the globe is a prefix icon. How could I add a prefix icon?
You can create a custom cascader with prefix/suffix icons of your choice if you use a wrapper div with relative positioning and have the <Icon/> child with absolute positioning and higher z-index than the Cascader/> (to go on top of it).
Check the example here: https://codesandbox.io/s/antd-cascader-ynqpk
const CustomCascader = ({ options, width = 300 }) => {
const [open, setOpen] = useState(false);
const onChange = value => {
console.log(value);
};
const filter = (inputValue, path) => {
return path.some(
option =>
option.display_name.toLowerCase().indexOf(inputValue.toLowerCase()) > -1
);
};
const onPopupVisibleChange = visible => {
setOpen(visible);
};
return (
<div style={{ position: "relative", width }}>
<Icon
type={open ? "up" : "down"}
style={{ position: "absolute", right: 8, top: 10, zIndex: 5 }}
/>
<Icon
type="global"
style={{ position: "absolute", left: 5, top: 10, zIndex: 5 }}
/>
<Cascader
style={{ paddingLeft: 0, width }}
suffixIcon={<div />}
expandTrigger="hover"
fieldNames={{ label: "name", value: "code", children: "items" }}
options={options}
onChange={onChange}
showSearch={{ filter }}
placeholder="Please select"
onPopupVisibleChange={onPopupVisibleChange}
popupVisible={open}
/>
</div>
);
};
ReactDOM.render(
<div>
<CustomCascader options={options} />
<CustomCascader options={options} />
<CustomCascader options={options} />
</div>,
document.getElementById("container")
);

How to parse json data in react native

hi I am new to React native development, how to parse following data please help me
here is my code
componentDidMount() {
fetch('https://api.myjson.com/bins/96ebw')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.Pharmacy,
},
);
})
.catch((error) => {
console.error(error);
});
}
renderItem(dataSource) {
const { List: list } = this.state.dataSource
const { item } = dataSource;
return (
<View style={styles.itemBlock}>
<View style={styles.itemMeta}>
<Text style={styles.itemName}>{item.RxDrugName}</Text>
<Text style={styles.itemLastMessage}>{item.RxNumber}</Text>
</View>
<View style={styles.footerStyle}>
<View style={{ paddingVertical: 10 }}>
<Text style={styles.status}>{ item.StoreNumber }</Text>
</View>
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Image source={require('../assets/right_arrow_blue.png')} />
</View>
</View>
</View>
);
}
json is
[
{
"Pharmacy": {
"Name": "Hillcrest MOB Pharmacy",
"StoreNumber": "254",
"Address": {
"StreetAddress": "50 Hillcrest Medical Blvd Ste 200-1",
"City": "WACO",
"State": "TX",
"Zip": "76712"
},
"IsDefault": false
},
"ReadyForPickups": [
{
"RxDrugName": "Tizanidine HCL 4mg Caps",
"RxNumber": "6000295",
"StoreNumber": "254",
"PatientPay": "15.59"
}
]
},
{
"Pharmacy": {
"Name": "Waco Pharmacy",
"StoreNumber": "251",
"Address": {
"StreetAddress": "1412 N Valley Mills, Suite 116",
"City": "WACO",
"State": "TX",
"Zip": "76710"
},
"IsDefault": false
},
"ReadyForPickups": [
{
"RxDrugName": "Fluoxetine HCL 40mg Caps",
"RxNumber": "6000233",
"StoreNumber": "251",
"PatientPay": "17.3"
}
]
}
]
The problem is that the json response is an array of objects. You need to select the object from the array.
For example, if you want the first item in the array you could do the following
const first = jsonResponse[0]
{
"Pharmacy":{
"Name":"Hillcrest MOB Pharmacy",
"StoreNumber":"254",
"Address":{
"StreetAddress":"50 Hillcrest Medical Blvd Ste 200-1",
"City":"WACO",
"State":"TX",
"Zip":"76712"
},
"IsDefault":false
},
"ReadyForPickups":[
{
"RxDrugName":"Tizanidine HCL 4mg Caps",
"RxNumber":"6000295",
"StoreNumber":"254",
"PatientPay":"15.59"
}
]
}
Now you can try using first.Pharmacy to capture the data from there.
So console.log(first.Pharmacy.Name) should give you Hillcrest MOB Pharmacy
It also looks like you are trying to create and display a list of these Pharmacies. Depending on the number of items you have there are a couple of ways to do that. However, the most performant and easiest is to use a FlatList. This will take care of the view if for any reason that it extends off of the page.
So let's set up the FlatList.
Firstly, import FlatList from react-native.
Secondly change the setState call in your componentDidMount to be
this.setState({
isLoading: false,
dataSource: responseJson
}
Add the following methods
renderItem = ({item, index}) => {
let { Pharmacy, ReadyForPickups } = item;
if(!ReadyForPickups[0]) return null;
let details = ReadyForPickups[0]
return (
<View style={styles.itemBlock}>
<View style={styles.itemMeta}>
<Text style={styles.itemName}>{details.RxDrugName}</Text>
<Text style={styles.itemLastMessage}>{details.RxNumber}</Text>
</View>
<View style={styles.footerStyle}>
<View style={{ paddingVertical: 10 }}>
<Text style={styles.status}>{ details.StoreNumber }</Text>
</View>
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Image source={require('../assets/right_arrow_blue.png')} />
</View>
</View>
</View>
);
}
keyExtractor = (item, index) => {
return index.toString();
}
Then your render method should look something like this
render () {
return (
<View style={{flex: 1}}>
<FlatList
data={this.state.dataSource}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
</View>
);
}
Then it should look something like this. Obviously the stylings are missing and I used a substitute image. But this should be the idea of what you are looking for.
Hopefully that should be enough to get the data out that you require.
UPDATE
Here is a fully working component that renders a list similar to the one above
import React, { Component } from 'react';
import { View, Text, FlatList, Image } from 'react-native';
import PropTypes from 'prop-types';
// import screens styles
import styles from './styles';
class Pharmacy extends Component {
/**
* Construct component class
* #param {object} props
*/
constructor (props: {}) {
super(props);
this.state = {
isLoading: true,
dataSource: []
};
}
componentDidMount () {
fetch('https://api.myjson.com/bins/96ebw')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
});
});
}
renderItem = ({item, index}) => {
let { Pharmacy, ReadyForPickups } = item;
if (!ReadyForPickups[0]) return null;
let details = ReadyForPickups[0];
return (
<View style={styles.itemBlock}>
<View style={styles.itemMeta}>
<Text style={styles.itemName}>{details.RxDrugName}</Text>
<Text style={styles.itemLastMessage}>{details.RxNumber}</Text>
</View>
<View style={styles.footerStyle}>
<View style={{ paddingVertical: 10 }}>
<Text style={styles.status}>{ details.StoreNumber }</Text>
</View>
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Image source={{uri: 'https://images.pexels.com/photos/949586/pexels-photo-949586.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'}}
style={{height: 50, width: 50}}/>
</View>
</View>
</View>
);
}
keyExtractor = (item, index) => {
return index.toString();
}
render () {
return (
<View style={{flex: 1}}>
<FlatList
data={this.state.dataSource}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
</View>
);
}
}
export default Pharmacy;
UPDATE 2
After a chat with the original question poster it seems that they want they only want to show the ReadyForPickups items as a single list.
This can be done by performing a map and a reduce on the responseJson so the setState call can be updated to the following
this.setState({
isloading: false,
dataSource: responseJson.map(item => item.ReadyForPickups).reduce((acc, currValue) => { return acc.concat(currValue); }, [])
});
This will group the ReadyForPickup items into one long list as follows:
[
{
"RxDrugName":"Tizanidine HCL 4mg Caps",
"RxNumber":"6000295",
"StoreNumber":"254",
"PatientPay":"15.59"
},
{
"RxDrugName":"Hydroxychloroquine Sulfate 200 Tabs",
"RxNumber":"6000339",
"StoreNumber":"201",
"PatientPay":"16.18"
},
{
"RxDrugName":"Naratriptan HCL 2.5mg Tabs",
"RxNumber":"6000300",
"StoreNumber":"111",
"PatientPay":"39.04"
},
{
"RxDrugName":"Tizanidine HCL 4mg Caps",
"RxNumber":"6000457",
"StoreNumber":"08",
"PatientPay":"15.59"
},
{
"RxDrugName":"Lisinopril 20mg Tabs",
"RxNumber":"6000318",
"StoreNumber":"08",
"PatientPay":"13.46"
},
{
"RxDrugName":"Fluoxetine HCL 40mg Caps",
"RxNumber":"6000233",
"StoreNumber":"251",
"PatientPay":"17.3"
},
{
"RxDrugName":"Tizanidine HCL 4mg Caps",
"RxNumber":"6000222",
"StoreNumber":"232",
"PatientPay":"15.59"
},
{
"RxDrugName":"Memantine HCL 5mg Tabs",
"RxNumber":"6000212",
"StoreNumber":"231",
"PatientPay":"17.99"
},
{
"RxDrugName":"Clonidine HCL 0.1mg Tabs",
"RxNumber":"6000339",
"StoreNumber":"07",
"PatientPay":"12.71"
},
{
"RxDrugName":"Benazepril HCL 5mg Tabs",
"RxNumber":"6000261",
"StoreNumber":"06",
"PatientPay":"13.45"
},
{
"RxDrugName":"Clonidine HCL 0.1mg Tabs",
"RxNumber":"6000524",
"StoreNumber":"02",
"PatientPay":"12.73"
},
{
"RxDrugName":"Timolol Maleate 20mg Tabs",
"RxNumber":"6000771",
"StoreNumber":"02",
"PatientPay":"15.33"
},
{
"RxDrugName":"Benazepril HCL 5mg Tabs",
"RxNumber":"6002370",
"StoreNumber":"01",
"PatientPay":"13.45"
},
{
"RxDrugName":"Eliquis 5mg Tabs",
"RxNumber":"6002609",
"StoreNumber":"01",
"PatientPay":"20.88"
},
{
"RxDrugName":"Atorvastatin Calcium 20mg Tabs",
"RxNumber":"6002602",
"StoreNumber":"01",
"PatientPay":"17.69"
},
{
"RxDrugName ":"Astagraf Xl 0.5mg Cp24",
"RxNumber":"6000232",
"StoreNumber":"278",
"PatientPay":"15.33"
},
{
"RxDrugName":"Ropinirole HCL 0.5mg Tabs",
"RxNumber":"6000067",
"StoreNumber":"112",
"PatientPay":"14.75"
},
{
"RxDrugName":"Ciprofloxacin HCL 0.3% Soln",
"RxNumber":"6000217",
"StoreNumber":"275",
"PatientPay":"55.06"
},
{
"RxDrugName":"Sotalol HCL 240mg Tabs",
"RxNumber":"6000575",
"StoreNumber":"09",
"PatientPay":"17.5"
}
]
To match the new dataSource the renderItem function should be updated so that it will display the list.
renderItem = ({item, index}) => {
return (
<View style={styles.itemBlock}>
<View style={styles.itemMeta}>
<Text style={styles.itemName}>{item.RxDrugName}</Text>
<Text style={styles.itemLastMessage}>{item.RxNumber}</Text>
</View>
<View style={styles.footerStyle}>
<View style={{ paddingVertical: 10 }}>
<Text style={styles.status}>{item.StoreNumber }</Text>
</View>
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Image source={require('../assets/right_arrow_blue.png')} />
</View>
</View>
</View>
);
}
Your responseJson is array of JSON object with format:
{
"Pharmacy": {
"Name": "Hillcrest MOB Pharmacy",
"StoreNumber": "254",
"Address": {
"StreetAddress": "50 Hillcrest Medical Blvd Ste 200-1",
"City": "WACO",
"State": "TX",
"Zip": "76712"
},
"IsDefault": false
},
"ReadyForPickups": [
{
"RxDrugName": "Tizanidine HCL 4mg Caps",
"RxNumber": "6000295",
"StoreNumber": "254",
"PatientPay": "15.59"
}
]
}
So you should
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}
);
In render(), you can map() each item in dataSource and call renderItem() as your code:
render() {
return (
<View>
{this.state.dataSource.map(item => this.renderItem(item))}
</View>
)
}
And in renderItem(item), item now is a JSON object with above format, you can render it easily.
renderItem(obj) {
const item = (obj.ReadyForPickups || [])[0] || {};
// this will secure your app not crash when item is invalid data.
return (
<View style={styles.itemBlock}>
<View style={styles.itemMeta}>
<Text style={styles.itemName}>{item.RxDrugName}</Text>
<Text style={styles.itemLastMessage}>{item.RxNumber}</Text>
</View>
<View style={styles.footerStyle}>
<View style={{ paddingVertical: 10 }}>
<Text style={styles.status}>{ item.StoreNumber }</Text>
</View>
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Image source={require('../assets/right_arrow_blue.png')} />
</View>
</View>
</View>
);
}

Flatview returns only blank lines

I'm trying to connect a react-native program with some data from our SQL Server. Here is the Json string that our link returns:
[{"Item_ID":2,"first_name":"steve","last_name":"jones","phone":"510-712-1822","email":"sjones#waltersandwolf.com","company":"Glass"},{"Item_ID":4,"first_name":"Tina","last_name":"Wills","phone":"510-222-7788","email":"twills#waltersandwolf.com","company":"Glass","notes":"","json":"{fname: \"Tina\", lname: \"Wills\", phone: \"510-222-7788\", email: \"twills#waltersandwolf.com\", company: \"Glass\", project: \"Portal\"}"},{"Item_ID":5,"first_name":"Sleepy","last_name":"owl","phone":"555-555-5555","email":"owl#forest.com","company":"Forest","notes":"whoooooo","json":"{first_name:sleepy,last_name:owl, phone:55555555,company:Forest, email: owl, notes:whoooo}"}]
Using this code snippet I've found on the web, I'm trying to just get this to show up in a flatview but it is blank:
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform} from 'react-native';
export default class App extends Component {
constructor(props)
{
super(props);
this.state = {
isLoading: true
}
}
componentDidMount() {
return fetch('https://functions-ww.azurewebsites.net/api/SteveListJSON')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#607D8B",
}}
/>
);
}
GetFlatListItem (company) {
Alert.alert(company);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<FlatList
data={ this.state.dataSource }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <Text style={styles.FlatListItemStyle} onPress={this.GetFlatListItem.bind(this, item.company)} > {item.company} </Text>}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
justifyContent: 'center',
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 0,
},
FlatListItemStyle: {
padding: 10,
fontSize: 18,
height: 44,
},
});
I would appreciate any help you could provide. I'm new at this so it may be something simple I'm missing...
Url is returning response as string and the datasource you need is an object so before setting the state of datasource change it to an object.
Add this:--
this.setState({
isLoading: false,
dataSource: JSON.parse(responseJson)
}