-2

How to map attributes array (which is the sub-array of products)into the picker. Here is my JSON data:

{ "products": [ { "productid": "5466", "name": "Cashew", "description": "", "attributes": [ { "product_id": "5466", "attribute_name": "500 grm", "attribute_price": "500" }, { "product_id": "5466", "attribute_name": "250 grm", "attribute_price": "250" } ] } ] }

here is my code:

renderProductsCart = ({ item }) => {
    return (
      <View style={{ width: "46%", marginLeft: 10, marginTop: 10 }}>
        <Card
          elevation={2}>
          <Card.Cover source={{ uri: item.image }} />
          <Text style={{ marginLeft: 5 }}>{item.name}</Text>
          <Text> ₹: {item.attribute_price}/- </Text>
          <Picker
            selectedValue={this.state.PickerValueHolder}

            onValueChange={(itemValue, itemIndex) => this.setState({ PickerValueHolder: itemValue })} >

            {this.state.data.products.attributes.map((item, key) => (
                        <Picker.Item label={item.attribute_name} value={item.attribute_name} key={item} />)
                    )}
            
          </Picker>
          <View style={{ flexDirection: "row" }}>
            <Card.Actions>
              <Button
                theme={{ colors: { primary: 'black' } }}
                onPress={() => console.log("press")}>View More</Button>
              <Button
                theme={{ colors: { primary: 'black' } }}
                onPress={() => console.log("press")}>Cart</Button>
            </Card.Actions>
          </View>
        </Card>
      </View>
    )
  }

       <FlatList
            data={this.state.data.products}
            renderItem={this.renderProductsCart}
            keyExtractor={(item, index) => index.toString()}
            numColumns={2}
          />

please help me thanks in advance

1 Answer 1

1

I have used the Functional component here but you can use the Class-based component and use it that way too: Output:

enter image description here

Full Example Code:

import React, {useState, useEffect} from 'react';
import { Text, View, StyleSheet, Picker, FlatList, Button } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
const dataP = {
  products: [
    {
      productid: '5466',
      name: 'Cashew',
      description: '',
      attributes: [
        {
          product_id: '5466',
          attribute_name: '500 grm',
          attribute_price: '500',
        },
        {
          product_id: '5466',
          attribute_name: '250 grm',
          attribute_price: '250',
        },
      ],
    },
  ],
};

export default function App() {
  const [data, setData] = useState({});

  useEffect(() => {
    setData(dataP);
  }, []);

  const renderProductsCart = ({ item }) => {
    return (
      <View style={{ width: '46%', marginLeft: 10, marginTop: 10 }}>
        <Card elevation={2}>
          <Card.Cover source={{ uri: item.image }} />
          <Text style={{ marginLeft: 5 }}>{item.name}</Text>
          <Text> ₹: {item.attribute_price}/- </Text>
          <Picker
            selectedValue={''}
            onValueChange={(itemValue, itemIndex) => this.setState({})}>
            {item?.attributes.map((item, key) => (
              <Picker.Item
                label={item.attribute_name}
                value={item.attribute_name}
                key={item}
              />
            ))}
          </Picker>
          <View style={{ flexDirection: 'row' }}>
            <Card.Actions>
              <Button
                theme={{ colors: { primary: 'black' } }}
                onPress={() => console.log('press')}>
                View More
              </Button>
              <Button
                theme={{ colors: { primary: 'black' } }}
                onPress={() => console.log('press')}>
                Cart
              </Button>
            </Card.Actions>
          </View>
        </Card>
      </View>
    );
  };
  return (
    <View style={styles.container}>
      <FlatList
        data={dataP?.products}
        renderItem={renderProductsCart}
        keyExtractor={(item, index) => index.toString()}
        numColumns={2}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Working Expo Snack Demo

Sign up to request clarification or add additional context in comments.

4 Comments

But class components does not support hooks, right? And also I'm retriving the JSON data through fetchAPI, so I think hard coding the JSON data is unncessary and If we do so, we need to update the JSON data after every new entry in the database.
Hooks are for functional components, and you can replace that hardcoded data with the one fetched from API.
How can I do that?
in the case of a functional component, use Axios or fetch API to fetch data from the server, assign it to the state, in the case of a class-based component you can follow the same method in componentDidMount, example: stackoverflow.com/a/65080708/5669120

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.