Does anyone has any example of List View that leads to another listview so for e.g if I have the listview that has following things:
Single Family Home
Mulitplex
Duplex
4 bedroom Home
if someone selects single 4 Bedroom Home, I want the user to lead to another List view that shows the places where the 4 bedroom home is available. How can I do this:
Circle Road
Orange
River Road
Ring Road
I am using two JSON file to achieve what I am trying o do:
[
{
"id":0,
"House_Type": "2 Bedroom"
},
{
"id":1,
"House_Type": "3 Bedroom"
},
{
"id":2,
"House_Type": "Condo"
},
{
"id":3,
"House_Type": "4 Bedroom"
},
{
"id":4,
"House_Type": "Duplex"
},
{
"id":5,
"House_Type": "Multiplex"
}
]
Second JSON file
[
{
"id": 0,
"PID" : 0,
"Address": "123 Test Drive",
"Location": "Orange",
"Zip": 123456"
},
{
"id": 1,
"PID" : 0,
"Address" : "234 Test Drive2",
"Location": "Ring Road",
"Zip": "226106"
},
{
"id": 2,
"PID" : 0,
"Address" : "111 Test Drive2",
"Location": "Bell Road",
"Zip": "226172"
},
{
"id": 3,
"PID" : 0,
"Address" : "111 Test Drive2",
"Location": "Bell Road",
"Zip": "226172"
},
{
"id": 1,
"PID" : 1,
"Address" : "111 Test Drive2",
"Location": "Bell Road100",
"Zip": "226172"
},
{
"id": 4,
"PID" : 1,
"Address" : "222 Test Drive3",
"Location": "Ring Road",
"Zip": "226173"
},
{
"id": 5,
"PID" : 1,
"Address" : "333 Test Drive3",
"Location": "Ring100 Road",
"Zip": "221112"
},
{
"id": 6,
"PID" : 1,
"Address" : "333 Test Drive3",
"Location": "Ring100 Road",
"Zip": "221113"
},
{
"id": 7,
"PID" : 2,
"Address" : "444 Test Drive3",
"Location": "Shepard Road",
"Zip": "221113"
},
{
"id": 8,
"PID" : 2,
"Address" : "555 Test Drive3",
"Location": "Shepard1000 Road",
"Zip": "221141"
},
I want something like this:
First List View:
2 Bedroom
3 Bedroom
Condo
4 Bedroom
Duplex
Multiplex
when user selects 2 Bedroom then he/she will be redirected to another list View like below:
123 Test Drive
Orange, 123456
____________________
234 Test Drive2
Ring Road, 226106
_____________________
111 Test Drive2
Bell Road, 226172
__________________
All the above has the Parent ID (PID) of 0 that matches the ID of first JSON file.
if user selects 3 Bedroom then he/she will be redirected to another list View like below:
111 Test Drive2
Bell Road100, 226172
_______________________________
222 Test Drive3
Ring Road, 226173
_____________________________
333 Test Drive3
Ring100 Road, 221112
________________________
In the above case the parent(PID) is 1 that matches the ID of first JSON file.
I have around 100 records in my first JSON file and around 300 records in my second JSON file. I gave some sample data above.
Below is the code and the error description. I am getting an error in the code:
import React, { Component } from 'react';
import { Text, View, StyleSheet, ListView, ActivityIndicator, TextInput, TouchableOpacity } from 'react-native';
import initialData from './src/screens/houses';
import houseDetails from './src/screens/houseDetails';
export default class Information extends Component {
constructor(props) {
super(props);
this.state = {
initialDtata: initialData(),
subObjects: [],
selected_topic_id: -1,
}
}
listView(){
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
var tabsData = ds.cloneWithRows(this.state.initialDtata)
return(
<View>
<ListView
style={{marginVertical: 5}}
enableEmptySections={true}
dataSource={tabsData}
renderRow={(rowData, sectionID, rowID) =>
this.displayHome(rowData, rowID)}
/>
</View>
)
}
displayHome(rowData, rowID) {
return(
<View style={{flex:1}}>
<TouchableOpacity onPress={() => this.onHomeSelection(rowID)}>
<View style={{marginVertical: 15, marginHorizontal:30, justifyContent: 'space-between', flexDirection: 'row',alignItems: 'center'}}>
<Text style={{fontSize: 10, fontWeight: 'bold'}}>{rowData.House_Type}</Text>
</View>
</TouchableOpacity>
{this.state.selected_topic_id === Number(rowID) ? this.renderQuestionList(rowData.id) : null}
</View>
);
}
onHomeSelection(rowID) {
let selected_topic_id = this.state.selected_topic_id === Number(rowID) ? -1 : Number(rowID);
this.setState({
subObjects: houseDetails(),
selected_topic_id: selected_topic_id,
})
}
renderQuestionList(rowID) {
let selected_array = [];
this.state.subObjects.map((i) => { if(i.PID === rowID) return selected_array.push(i)})
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
let tabsData = ds.cloneWithRows(selected_array)
return(
<View>
<ListView
style={{marginVertical: 5}}
enableEmptySections={true}
dataSource={tabsData}
renderRow={(rowData, sectionID, rowID) =>
this.renderQuestion(selected_array, rowID)}
/>
</View>
)
}
renderQuestion(rowData, rowID) {
let address = rowData.map((i) => {return i.Address})
return(
<View style={{flex:1}}>
<TouchableOpacity>
<View style={{marginVertical: 5, marginLeft:35, marginRight: 35}}>
<Text style={{color: 'black', fontSize: 20, fontWeight: 'bold'}}>{address}</Text>
</View>
</TouchableOpacity>
</View>
);
}
render() {
return (
<View style={{ flex:1, backgroundColor: 'white' }}>
{this.listView()}
</View>
);
}
}
module.exports = {
initialData: function() {
return (
initialDtata = [
{
"id":0,
"House_Type": "2 Bedroom"
},
{
"id":1,
"House_Type": "3 Bedroom"
},
{
"id":2,
"House_Type": "Condo"
},
{
"id":3,
"House_Type": "4 Bedroom"
},
{
"id":4,
"House_Type": "Duplex"
},
{
"id":5,
"House_Type": "Multiplex"
}
]
);
}
}
module.exports = {
houseDetails: function() {
return(
subObjects = [
{
"id": 1,
"PID" : 0,
"Address" : "234 Test Drive2",
"Location": "Ring Road",
"Zip": "226106"
},
{
"id": 2,
"PID" : 0,
"Address" : "111 Test Drive2",
"Location": "Bell Road",
"Zip": "226172"
},
{
"id": 3,
"PID" : 0,
"Address" : "111 Test Drive2",
"Location": "Bell Road",
"Zip": "226172"
},
{
"id": 1,
"PID" : 1,
"Address" : "111 Test Drive2",
"Location": "Bell Road100",
"Zip": "226172"
},
{
"id": 4,
"PID" : 1,
"Address" : "222 Test Drive3",
"Location": "Ring Road",
"Zip": "226173"
}]
);
}
}
Below is the error description:
Invariant Violation: Element type is invalid:
expected a string (for built-in components)
or a class/function(for composite components) but got: object.
This error is located at:
in RCTView (At View.js:60)
in View(at appContainer.js:102)
in RCTView (at View.js:60)
in View (at Appcontainer.js:122)
in AppContainer (at renderApplication.js:32)
any help will be appreciated.
you can try this:
import { initialData } from 'src/screens/houses';
import { houseDetails } from 'src/screens/housesDetails';
export default class Information extends Component {
constructor(props: Object) {
super(props);
this.state = {
initialDtata: initialData(),
subObjects: [],
selected_topic_id: -1,
}
}
listView(){
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
var tabsData = ds.cloneWithRows(this.state.initialDtata)
return(
<View>
<ListView
style={{marginVertical: 5}}
enableEmptySections={true}
dataSource={tabsData}
renderRow={(rowData, sectionID, rowID) =>
this.displayHome(rowData, rowID)}
/>
</View>
)
}
displayHome(rowData: Object, rowID: number) {
return(
<View style={{flex:1}}>
<TouchableOpacity onPress={() => this.onHomeSelection(rowID)}>
<View style={{marginVertical: 15, marginHorizontal:30, justifyContent: 'space-between', flexDirection: 'row',alignItems: 'center'}}>
<Text style={{fontSize: 10, fontWeight: 'bold'}}>{rowData.House_Type}</Text>
</View>
</TouchableOpacity>
{this.state.selected_topic_id === Number(rowID) ? this.renderQuestionList(rowData.id) : null}
</View>
);
}
onHomeSelection(rowID) {
let selected_topic_id = this.state.selected_topic_id === Number(rowID) ? -1 : Number(rowID);
this.setState({
subObjects: houseDetails(),
selected_topic_id: selected_topic_id,
})
}
renderQuestionList(rowID) {
let selected_array = [];
this.state.subObjects.map((i) => { if(i.PID === rowID) return selected_array.push(i)})
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
let tabsData = ds.cloneWithRows(selected_array)
return(
<View>
<ListView
style={{marginVertical: 5}}
enableEmptySections={true}
dataSource={tabsData}
renderRow={(rowData, sectionID, rowID) =>
this.renderQuestion(selected_array, rowID)}
/>
</View>
)
}
renderQuestion(rowData: Object, rowID: number) {
let address = rowData.map((i) => {return i.Address})
return(
<View style={{flex:1}}>
<TouchableOpacity>
<View style={{marginVertical: 5, marginLeft:35, marginRight: 35}}>
<Text style={{color: 'black', fontSize: 20, fontWeight: 'bold'}}>{address}</Text>
</View>
</TouchableOpacity>
</View>
);
}
render() {
return (
<View style={{ flex:1, backgroundColor: 'white' }}>
{this.listView()}
</View>
);
}
}
you can do import { initialData } from 'src/screens/houses';
module.exports = {
initialData: function() {
return (
initialDtata = [
{
"id":0,
"House_Type": "2 Bedroom"
},
{
"id":1,
"House_Type": "3 Bedroom"
},
{
"id":2,
"House_Type": "Condo"
},
{
"id":3,
"House_Type": "4 Bedroom"
},
{
"id":4,
"House_Type": "Duplex"
},
{
"id":5,
"House_Type": "Multiplex"
}
]
);
}
}
and import { houseDetails } from 'src/screens/housesDetails';
module.exports = {
houseDetails: function() {
return(
subObjects = [
{
"id": 1,
"PID" : 0,
"Address" : "234 Test Drive2",
"Location": "Ring Road",
"Zip": "226106"
},
{
"id": 2,
"PID" : 0,
"Address" : "111 Test Drive2",
"Location": "Bell Road",
"Zip": "226172"
},
{
"id": 3,
"PID" : 0,
"Address" : "111 Test Drive2",
"Location": "Bell Road",
"Zip": "226172"
},
{
"id": 1,
"PID" : 1,
"Address" : "111 Test Drive2",
"Location": "Bell Road100",
"Zip": "226172"
},
{
"id": 4,
"PID" : 1,
"Address" : "222 Test Drive3",
"Location": "Ring Road",
"Zip": "226173"
}]
);
}
}
hey #user54967 sorry for the delay
Related
I have read all similar questions in stack overflow on this topic. Yet my info is not being displayed.
I am fetching locations from tomtom api. I have limit the result up to one location for simplicity. My data:
items: Array [
Object {
"address": Object {
"country": "United States",
"countryCode": "US",
"countryCodeISO3": "USA",
"countrySecondarySubdivision": "Hidalgo",
"countrySubdivision": "TX",
"countrySubdivisionName": "Texas",
"extendedPostalCode": "78542-7214",
"freeformAddress": "1718 South 28th Avenue, Edinburg, TX 78542",
"localName": "Edinburg",
"municipality": "Edinburg",
"postalCode": "78542",
"streetName": "South 28th Avenue",
"streetNumber": "1718",
},
"dist": 7911851.058335642,
"entryPoints": Array [
Object {
"position": Object {
"lat": 26.28239,
"lon": -98.14742,
},
"type": "main",
},
],
"id": "840489007442969",
"info": "search:ta:840489007442969-US",
"poi": Object {
"categories": Array [
"company",
"equipment rental",
],
"categorySet": Array [
Object {
"id": 9352038,
},
],
"classifications": Array [
Object {
"code": "COMPANY",
"names": Array [
Object {
"name": "equipment rental",
"nameLocale": "en-US",
},
Object {
"name": "company",
"nameLocale": "en-US",
},
],
},
],
"name": "Wylie Implement Edinbu",
"phone": "+1 956-550-8822",
},
"position": Object {
"lat": 26.28223,
"lon": -98.1464,
},
"score": 1.9846990108,
"type": "POI",
"viewport": Object {
"btmRightPoint": Object {
"lat": 26.2813,
"lon": -98.14536,
},
"topLeftPoint": Object {
"lat": 26.28316,
"lon": -98.14744,
},
},
},
]
My component:
const AutocompleteResults = (props) => {
const [locations, setLocations] = useState(props.items);
console.log("items: ", locations);
useEffect(() => {
setLocations(props.items);
}, [props.items]);
return (
<View style={{ flex: 1, marginBottom: 20 }}>
<Text>Result</Text>
{locations.length>0 ? (
<>
<Text>Items</Text>
<FlatList
style={{ flex: 1, borderColor: "red", borderWidth: 1 }}
horizontal={false}
data={locations}
keyExtractor={(item, index) => index.toString()}
renderItem={({location}) => {
console.log("single location ", location);
return <Text>Location</Text>;
}}
/>
</>
) : null}
</View>
);
};
const style = StyleSheet.create({
viewStyle: {
flex: 1,
justifyContent: "center",
},
});
export default AutocompleteResults;
What I see on the console is: single location undefined
I tried all the suggestions which I found in stack overflow. In my opinion the problem is in extractKey method but I dont know how to fix it.
On the screen I just see the words "Result" "Items" followed by red dash (coming from my styling for flatlist)
EDIT:
I edited my render function in the following way:
renderItem={({ item }) => {
console.log("single location ", item);
return (
<View style={{ flex: 1, height: 30 }}>
<Text>Location</Text>
</View>
);
}}
But the "Location" text still does not display
You are destructuring location in the renderItem function of the FlatList. This fails, because there is no such parameter. The parameter is called item.
This is explained in the documentation.
renderItem({ item, index, separators });
item (Object): The item from data being rendered.
The following code should fix the issue.
return (
<View style={{ flex: 1, marginBottom: 20 }}>
<Text>Result</Text>
{locations.length>0 ? (
<>
<Text>Items</Text>
<FlatList
style={{ flex: 1, borderColor: "red", borderWidth: 1 }}
horizontal={false}
data={locations}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) => {
console.log("single location ", item);
return <Text>Location</Text>;
}}
/>
</>
) : null}
</View>
);
};
The extractKey function is fine.
as the title suggests I would like to know how to use the getParam function to access a nested array. This is my json and my code.
Json:
[
{
"name": "Crock Pot Roast",
"ingredients": [
{
"quantity": "1",
"name": " beef roast",
"type": "Meat"
},
{
"quantity": "1 package",
"name": "brown gravy mix",
"type": "Baking"
},
{
"quantity": "1 package",
"name": "dried Italian salad dressing mix",
"type": "Condiments"
},
{
"quantity": "1 package",
"name": "dry ranch dressing mix",
"type": "Condiments"
},
{
"quantity": "1/2 cup",
"name": "water",
"type": "Drinks"
}
],
"steps": [
"Place beef roast in crock pot.",
"Mix the dried mixes together in a bowl and sprinkle over the roast.",
"Pour the water around the roast.",
"Cook on low for 7-9 hours."
],
I capture the data that interest me and print them, accessing the nested array via map (quantity values, name, type) in this screen.
Screen1:
<FlatList
numColumns={2}
data={this.state.breweries}
renderItem={({ item, index }) => (
<View style={styleResult.box}>
<TouchableOpacity onPress={() =>this.props.navigation.navigate('ReviewDetails', item)}>
<Image style={styleResult.logo}
source={{uri: item.imageURL}} />
<Text style={styleResult.titleRecipe}> {item.name}</Text>
{item.ingredients.map((v,i) => (
<Text style={styleResult.titleRecipe}> {v.name}</Text>
))}
</TouchableOpacity>
But when I want to bring every single value to a second page via onpress, in screen 2 if I want to print the name I can with getParam ('name'), but if I wanted to print the names of the ingredients, I don't know how to do it.
Screen2
const link=navigation.getParam('imageURL');
return(
<View style={styleReviewDetails.container}>
<ScrollView>
<Text style={styleReviewDetails.titleRecipe} >{navigation.getParam('name')}</Text>
<Image style={styleReviewDetails.imageRecipe} source={{uri: link}}></Image>
<Text style={styleReviewDetails.titleRecipe} >Ingredients: ???????</Text>
In your details screen you have an object of the json type you posted.
Therefore, if you want to have a string which contains the ingredient names you could obtain it like this:
const ingredients = navigation.getParam('ingredients') // here you have the list
const ingredientNames = ingredients.map((ingredient) => ingredient.name)
// if you want to put there a separator, like "," you can do it like this:
const ingredientNames = ingredients.map((ingredient, index) => `${ingredient.type}` + ( index !== ingredients.length-1 ? " ," : ""))
// in your code it will be used like this
...
<Text>
{ingredientNames}
</Text>
I get an array after console log my state that get data from Firebase. I want to know: can anyone help me to map array and get below details on ui. Thank You.
I tried below way, but app keep getting errors
Array [
Object {
"lists": Array [
Object {
"lists": Array [
Object {
"id": "123",
"imageUrl": "http://www.pngmart.com/files/1/Pizza-Slice-PNG-Transparent-Image.png",
"name": "Chicken Devill pizza",
"price": 700,
"size": "Medium",
},
],
"randomid": "32013408-0f48-4b15-80c4-eba3fc1fe295",
},
Object {
"lists": Array [
Object {
"id": "1234",
"imageUrl": "http://www.pngmart.com/files/1/Cheese-Pizza.png",
"name": "Cheese pork pizza",
"price": 1500,
"size": "Medium",
},
],
"randomid": "12a74805-4932-4397-b838-6773bc7e44b8",
},
],
},
]
In below code it show a error:
TypeError: undefined is not a function (near '...this.state.lists.map...')
{this.state.lists.lists.map((current, i) => (
))}
The first list here is an array not an Object. You can't call lists.lists because of this.
You will need to flatten the list or use nested map operations.
export default function App() {
const state = {
lists: [
{
lists: [
{
id: "123",
imageUrl:
"http://www.pngmart.com/files/1/Pizza-Slice-PNG-Transparent-Image.png",
name: "Chicken Devill pizza",
price: 700,
size: "Medium"
}
],
randomid: "32013408-0f48-4b15-80c4-eba3fc1fe295"
},
{
lists: [
{
id: "1234",
imageUrl: "http://www.pngmart.com/files/1/Cheese-Pizza.png",
name: "Cheese pork pizza",
price: 1500,
size: "Medium"
}
],
randomid: "12a74805-4932-4397-b838-6773bc7e44b8"
}
]
};
return (
<div className="App">
{state.lists.map((list) => {
return list.lists.map((item) => {
return <p>{item.id}</p>;
});
})}
</div>
);
}
You can find this working here: https://codesandbox.io/s/nervous-tu-u2h8v?file=/src/App.js
I also want to add some thing by myself
I done the mapping inside a mapping like this
{this.state.lists.map((current, i) => (
<View>
{current.map((current, i) => (
<Fragment>
<TouchableOpacity style={styles.card} onPress={() => this.details(current.id)}>
<Image style={styles.img} key={i} source={{uri: current.lists[0].imageUrl}}/>
<Text style={styles.txt} key={i}>{current.lists[0].name}</Text>
<Text style={styles.txt} key={i}>{current.lists[0].size}</Text>
<Text style={styles.txt} key={i}>LKR.{current.lists[0].price}</Text>
</TouchableOpacity>
</Fragment>
))}
</View>
))}
I have an array:
[
{
"room": {
"id": "1",
"name": "NameRoom"
},
"users": [
{
"userId": "1",
"userName": "User1",
},
{
"userId": "2",
"userName": "User12",
},
{
"userId": "3",
"userName": "User13",
}
]
},
{
"room": {
"id": "2",
"name": "NameRoom2"
},
"users": [
{
"userId": "4",
"userName": "User14",
},
{
"userId": "5",
"userName": "User15",
},
{
"userId": "6",
"userName": "User16",
}
]
},
]
Here is my rendering code
componentDidMount() {
fetch('https://site.ru/api/rooms')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson,
})
console.log(responseJson[0].users[0].userName) // i get User1
})
.catch((error) => {
console.log(error)
})
}
renderItemRooms = ({ item,index }) => (
<View style = {styles.containerHeader}>
<Text style = {styles.dateTitle}>16.04.2020</Text>
</View>
<TouchableOpacity style = {styles.containerMain}>
<Text style = {styles.nameTitle}>RoomName</Text>
<IconButton
style={styles.menuIcon}
icon="text"
color={'#e7eee6'}
size={40}
onPress={this._toggleBottomNavigationView}
/>
<BottomSheet
visible={this.state.visible}
onBackButtonPress={this._toggleBottomNavigationView}
onBackdropPress={this._toggleBottomNavigationView}
>
<View style={styles.bottomNavigationView}>
<View style={styles.bottomList}>
<FlatList
keyExtractor={item => item.name}
data={this.state.dataSource}
renderItem={this.renderItemUsers}
/>
</View>
<View style={styles.bottomButton}>
<TouchableOpacity style={styles.buttonStyle}>
<Text>Connect</Text>
</TouchableOpacity>
</View>
</View>
</BottomSheet>
</TouchableOpacity>
)
How can I display a list of users in the internal render in my code?
And print the names of rooms.
How to iterate through such an array correctly?
I need to output TouchableOpacity with the name of the room, it has a button on the right, when you click it, a modal menu appears, which contains a list of users in this room, how do I do this correctly?
I've already searched the Internet and didn't find a similar problem.
I notice that you have missed something in FlatList, also there many methods to iterate an array. I will give you an example here and hope this helps.
Example:
<FlatList
keyExtractor={item => item.room.name} {/* item.name is undefined, you need to add room.name */}
data={this.state.dataSource}
renderItem={this.renderItemUsers}
/>
// And renderItemUsers method
renderItemUsers = ({ item }) => {
const Users = () => item.users.map(user => <Text key={user.userId}>{user.userName}</Text>)
return (
<View>
<Text>Room : {item.room.name}</Text>
<Users />
</View>
)
}
I'm currently working on my first react App and I'm having a little trouble with a product list that I'm trying to create.
Essentially I'm trying to create a list (parsed into react from a JSON file) which will enable the user to select the number of products that they want.
However the quantity selector that I have created is updating all of the iterations of the mapped array rather than just the one that the selector is inside of. How can I adjust the code so that only one counter updates at a time?
My Code is as follows
import React, { Component } from "react";
import "./App.css";
import productdata from "./catalog.json";
class App extends Component {
constructor(props) {
super(props);
this.state = {
BundleVal: "",
ProductVal:"",
CounterVal: 0
}
}
updateBundle = (val) => {
this.setState({
BundleVal: val
})
};
updateProduct = (val) => {
this.setState({
ProductVal: val
})
};
counterincrease = (val) => {
this.setState({
CounterVal: this.state.CounterVal + 1
})
};
counterdecrease = (val) => {
this.setState({
CounterVal: this.state.CounterVal - 1
})
};
render() {
const BundleProducts = [].concat(productdata.data.products).map((item, i) =>
<div key={item.id}>
{item.id} <br />
{item.name} <br />
{item.description} <br />
Installation: {item.price.installation} <br />
Monthly: {item.price.recurring} <br />
{this.state.CounterVal}
<button onClick={this.counterincrease}>+</button>
<button onClick={this.counterdecrease}>-</button>
</div>
);
let bname = null;
if (this.state.BundleVal === "1") {
bname = "Bundle 1";
}
else if (this.state.BundleVal === "2") {
bname = "Bundle 2";
}
else if (this.state.BundleVal === "3") {
bname = "Bundle 3";
}
else if (this.state.BundleVal === "4") {
bname = "Bundle 4";
}
else {bname = null;}
return (
<div>
<h2>Order</h2>
Bundle Id: {this.state.BundleVal}
<br/>
Chosen Bundle: {bname}
<br/>
Number of Products: {this.state.ProductVal}
<br/>
<Bundle updateBundle={this.updateBundle} />
{BundleProducts}
</div>
)
}
}
class Bundle extends React.Component {
constructor(props) {
super(props);
this.state = {
BundleVal: ""
}
}
updatebundle = (e) => {
this.props.updateBundle(e.target.value);
this.setState({BundleVal: e.target.value});
};
render() {
return (
<div>
<h4>Bundle</h4>
<input
type="radio"
value="1"
onChange={this.updatebundle}
checked={this.state.BundleVal==='1'}
/> Bundle 1
<input
type="radio"
value="2"
onChange={this.updatebundle}
checked={this.state.BundleVal==='2'}
/> Bundle 2
</div>
)
}
}
export default App;
Some code from my JSON file is included below
{
"timestamp": 1502121471,
"data": {
"adverts": [],
"bundles": [{
"id": "1",
"name": "Bundle 1",
"description": "Bundle 1 Description",
"maximumPeripherals": 32,
"available": true,
"count": 0,
"price": {
"installation": "99.99",
"recurring": "23.99"
},
"image": {
"file": "bundle-one.png",
},
"products": ["1", "2", "3"]
}, {
"id": "2",
"name": "Bundle 2",
"description": "Bundle 2 Description",
"maximumPeripherals": 32,
"available": true,
"count": 0,
"price": {
"installation": "99.99",
"recurring": "23.99"
},
"image": {
"file": "bundle-two.png",
},
"products": ["1", "2", "2", "2", "2"]
}],
"products": [{
"id": "1",
"name": "Product 1",
"description": "Product 1 Description",
"maximumQuantity": 1,
"isPeripheral": false,
"isAvailable": true,
"price": {
"upfront": null,
"installation": "0.00",
"recurring": "0.00"
},
"image": {
"file": "product-one.png",
}
}, {
"id": "2",
"name": "Product 2",
"description": "Product 2 Description",
"maximumQuantity": null,
"isPeripheral": true,
"isAvailable": true,
"count": 0,
"price": {
"upfront": "60.00",
"installation": "9.60",
"recurring": "1.25"
},
"image": {
"file": "product-two.png",
}
}, {
"id": "3",
"name": "Product Three",
"description": "Product Three Description",
"maximumQuantity": null,
"isPeripheral": true,
"isAvailable": true,
"count": 0,
"price": {
"upfront": "132.00",
"installation": "9.60",
"recurring": "2.75"
},
"image": {
"file": "product-three.png",
}
}]
}
}
A friend of mine suggested the following to answer this question. Essentially the array will now loop through the values and add a different id will be applied to each input.
updateQuantity = (e) => {
var pCounter = this.state.ProductCounter;
var el = parseInt(e.target.id.split("_")[1], 10);
pCounter[el] = parseInt(e.target.value, 10);
this.setState({ProductCounter: pCounter});
console.log(this.state.ProductCounter);
};
render() {
const BundleProducts = [].concat(productdata.data.products).map((item, i) =>
<div key={item.id}>
{item.id} <br />
{item.name} <br />
{item.description} <br />
Installation: {item.price.installation} <br />
Monthly: {item.price.recurring} <br />
<input
type="number"
onChange={this.updateQuantity}
value={this.state.ProductCounter[item.id] || 0}
id={"product_"+item.id}
/><br />
{this.state.ProductCounter[item.id] || 0}
<hr />
</div>
);