Search code examples
functionreact-nativebuttonconditional-statementsonpress

How to make a Function with Conditional Statements to determine what a button does when pressed? (React Native)


Here is my current app.js file. I would like for the button to "know" which dropdown menu item is selected, and then pick a random song from a list and write that song name on the screen.

Currently, no matter which "mood" you have selected, it will output only "happy song" names in the console.

I believe my error is somewhere in my If/If Else statements, but after a few hours of debugging/googling, I could not find what the problem was.

Basically, I need a function to call onPress of my button, and in that function, I need it to determine which dropdown is selected, and only output a single, random, song from that "mood" of songs. However, my current function, "macSong" will always output a "happy" song, even if the dropdown menu has something else selected.

If anything about my question is confusing, please write a comment below and let me know what I need to elaborate on, Thanks!

import { StyleSheet, Text, TextInput, View, Button, Alert } from 'react-native';
import SearchableDropdown from 'react-native-searchable-dropdown';

var items =[
    {
      id: 1,
      name: 'Happy Music'
    },
    {
      id: 2,
      name: 'Sad Music'
    },
    {
      id: 3,
      name: 'Chill Music'
    },
    {
      id: 4,
      name: 'Hype Music'
    }
];

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: []
    }
  }

  render() {
    return (
      <View style={ styles.screen }>
      <Fragment>
        {/* Title */}
        <View style={ styles.title }>
          <Text> Which Mac Miller Song Matches Your Mood? </Text>
        </View>
          {/* Single Dropdown Menu */}
          <SearchableDropdown
            onItemSelect={(item) => {
              const items = this.state.selectedItems;
              this.setState({ selectedItems: [...items, item]});
            }}
            containerStyle={{ padding: 25, alignSelf: 'center' }}
            onRemoveItem={(item, index) => {
              const items = this.state.selectedItems.filter((sitem) => sitem.id !== item.id);
              this.setState({ selectedItems: items });
            }}
            itemStyle={{
              padding: 10,
              marginTop: 2,
              backgroundColor: '#ddd',
              borderColor: '#bbb',
              borderWidth: 1,
              borderRadius: 5,
            }}
            itemTextStyle={{ color: '#222' }}
            itemsContainerStyle={{ maxHeight: 140 }}
            items={items}
            defaultIndex={2}
            resetValue={false}
            textInputProps={
              {
                placeholder: "What kind of music do you want to hear?",
                underlineColorAndroid: "transparent",
                style: {
                    padding: 12,
                    borderWidth: 1,
                    borderColor: '#ccc',
                    borderRadius: 5,
                },
              }
            }
            listProps={
              {
                nestedScrollEnabled: true,
              }
            }
        />

      {/* Button */}
      <View style={ styles.button }>
        <Button
          title="Press me for a Mac Miller song!"
          onPress={() => 
            this.macSong()}
        />
      </View>
      </Fragment>
      </View>
    );
  }

  /* Different Mood Function */
  macSong(selectedItems) {
    console.log(this.state.selectedItems)
    if (this.state.selectedItems.includes('Happy Music')) {
      let songs = ['best day ever', 'kool aid & frozen pizza', 'nikes on my feet']
      let song = songs[Math.floor(Math.random() * songs.length)];
      console.log(song);
    } else if (this.state.selectedItems.includes('Sad Music')) {
      let songs = ['self care', 'ROS', 'stay', 'whats the use']
      let song = songs[Math.floor(Math.random() * songs.length)];
      console.log(song);
    } else if (this.state.selectedItems.includes('Chill Music')) {
      let songs = ['good news', 'claymation', 'the star room']
      let song = songs[Math.floor(Math.random() * songs.length)];
      console.log(song);
    } else if (this.state.selectedItems.includes('Hype Music')) {
      let songs = ['donald trump', 'remember', 'weekend']
      let song = songs[Math.floor(Math.random() * songs.length)];
      console.log(song);
    } else {
      console.log("Selected Item is Unknown")
    }
  }
}

{/* StyleSheet */}
const styles = StyleSheet.create({
  screen: {
    backgroundColor: ''
  },
  button: {
    padding: 10,
    alignSelf: 'center'
  },
  title: {
    padding: 30,
    alignSelf: 'center',
    textAlign: 'center'
  }
});

Solution

  • In your onItemSelect={(item) => {} method you are mutating your state by putting reference to this.state.selectedItems to "items" constant and pushing a new value to it, you should make it immutable like this:

    onItemSelect={(item) => {
      const items = this.state.selectedItems;
      this.setState({ selectedItems: [...items, item]});
    }}
    

    And then inside your Difference moods function you are using single "=" which means assign, not compare. Just use

    if (selectedItems === 'Happy Music'){
    

    inside your if statements and i guess it will work as you expect