Home > Software design >  How to Show/Hide a component depending on items selected in DropDownPicker in React Native?
How to Show/Hide a component depending on items selected in DropDownPicker in React Native?

Time:07-27

I am trying to use 'react-native-dropdown-picker' to select and keep items selected from a DropDownPicker tree.

For the 'Date' item in the list, I want to show the Text "YOU CHOOSE DATE" if and only if Date was selected, and hide the Text if the selection is canceled by the user. How can I add a conditional statement in React Native so my plan works?

Here is my Code:


import { Component } from 'react';

import { React, useEffect } from 'react';

import { useState } from 'react';

import { StatusBar } from 'expo-status-bar';

import { StyleSheet, Text, View } from 'react-native';

import DropDownPicker from 'react-native-dropdown-picker';

export default function App() {

  const [open, setOpen] = useState(false);

  const [value, setValue] = useState(['date', 'fruits', 'banana', 'apple', 'dairy', 'milk', 'cheese']);

  const [items, setItems] = useState([
    {label: 'Date', value: 'date'},

{label: 'Fruits', value: 'fruits'},
{label: 'Article', value: 'article', parent: 'fruits'},
{label: 'Banana', value: 'banana', parent: 'fruits'},
{label: 'Apple', value: 'apple', parent: 'fruits'},

{label: 'Dairy Products', value: 'dairy products'},
{label: 'Milk', value: 'milk', parent: 'dairy products'},
{label: 'Cheese', value: 'cheese', parent: 'dairy products'},

  ]);


  return (
    <View style={styles.container}>
      <View style={styles.boxes}>
        <DropDownPicker
        open={open}
        value={value}
        items={items}
        setOpen={setOpen}
        setValue={setValue}
        setItems={setItems}

    theme="LIGHT"
    multiple={true}
    mode="BADGE"
    badgeDotColors={["blue", "#00b4d8", "#e9c46a", "#e76f51", "#8ac926", "#00b4d8", "#e9c46a", "green"]}
  />
  </View>

  <View> 
    <Text style={styles.text}> YOU CHOOSE DATE</Text>
  </View>
  <StatusBar style="auto" />
</View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
  },
  boxes: {
    flexDirection: 'row',
    marginTop: '40%',
  },
  text: {
    fontSize: 20,
    fontStyle: 'bold',
    marginTop: '60%',
  }
});

The app should look like this: Date is selected Date in deselected

CodePudding user response:

value returns array so must be check like this

const isDateOnly = () => {
    return (
      Object.values(value).length === 1 &&
      Object.values(value).indexOf('date') > -1
    );
  };

then you can check condition in render like this

<View>
        {isDateOnly() ? (
          <Text style={styles.text}> YOU CHOOSE DATE</Text>
        ) : null}
      </View>

  • Related