Rafael GS
Rafael GS

Reputation: 5

How to toggle multiple views with buttons

I'm struggling with this piece of code for a while, I have 5 buttons on the screen and want them to show some view when clicked, but also hide the previous view (showing only ONE view at the time)

I currently have this:

      const [state1, setState1] = useState(false)
      const [state2, setState2] = useState(false)
    //...
    return()
    //Button
    <View/>
    <TouchableOpacity
    onPress={() => setState1(!state1)}
    style={styles.style1}
    >
    <Image
    style={styles.imageButton}
    source={require('./image1')}
    />
    </TouchableOpacity>
    <TouchableOpacity
    onPress={() => setState2(!state2)}
    style={styles.style2}
    >
    <Image
    style={styles.imageButton}
    source={require('./Image2')}
    />
    </TouchableOpacity>
    </View>
//Views
{state1 === true ? (
<View>...</View> ) : null
{state2 === true ? (
<View>...</View> ) : null

This code is working but when I click on button2, the view of button1 is still visible (above in this case) how could I work that out?

Upvotes: 0

Views: 344

Answers (1)

Rajshekhar
Rajshekhar

Reputation: 624

const[state, setButtonStatus]=useState("1")
{return<>
  <View>
        {state == "1" ? (
          <Text>First View</Text>
        ) : state == "2" ? (
          <Text>2nd View</Text>
        ) : state == "3" ? (
          <Text>3rd View</Text>
        ) : (
          <Text>4th View.</Text>
        )}
      </View>
</>
}

You can do like that change value of state on clikck and show view accordingly

Upvotes: 1

Related Questions