Search code examples
react-nativeif-statementpicker

fill a picker usin json according to a condition


I can fill a picker using json stocked in state

  produits: [{
      "code": 11,
      "pu": 50,
      "ps": 50,
      "des": "P 1",
      "promo": "1",
    }, {
      "code": 22,
      "pu": 100,
      "ps": 100,
      "des": "P 2",
      "promo": "1",
    }, {
      "code": 33,
      "pu": 80,
      "ps": 80,
      "des": "P 3",
      "promo": "0",
    },
    {
      "code": 44,
      "pu": 120,
      "ps": 120,
      "des": "P 4",
      "promo": "1",
    },
  ],

what I want is the same thing but if produits.promo === '1' this item will be shown else it will not be shown, this is my approach but it have an empty picker: whene I click nothing changes :

          {<Picker
            style={Styles.picker}
            selectedValue={this.state.pu}
            onValueChange={(itemValue, itemIndex) => this.setState({pu: itemValue, codeProduit: itemIndex+1,})} >
            { this.state.produits.map((item, key)=>
              {if (item.promo === "0") {
                <Picker.Item label={item.des} value={item.pu} key={item.code} />
                }
              }
            )}
          </Picker>}

PS. it works good without If block:

<Picker.Item label={item.des} value={item.pu} key={item.code} />

what's wrong with my approach ?


Solution

  • Just make a new produits array using the filter

    render() {
    const promoProduits = this.state.produits.filter(item => item.promo === '1');
    ....
    

    Then render like

    {<Picker
        style={Styles.picker}
        selectedValue={this.state.pu}
        onValueChange={(itemValue, itemIndex) => this.setState({pu: itemValue, codeProduit: itemIndex+1,})} >
        {
         promoProduits.map((item, key)=> (<Picker.Item label={item.des} value={item.pu} key={item.code} />)
        }
    </Picker>}