0

How can i switch between appearance props with onPress? exampe: Default -> Active -> Background -> Default. in AppearanceButton file i have these three props

appearance?: "default" | "active" | "background"

These props control the color of my AppearnceButton, how can i switch between the appearance props onPress?

 function onPressSwitchAppearance() {
        {
          //How to switch between the appearance props onPress?
        }
    }


<View>
   <AppearnceButton onPress={onPressSwitchAppearance} appearance="default" icon="icon1" />
 </View>

2 Answers2

1

You can use a state variable to maintain the appearance and pass it to your AppearanceButton component.

Here is the code for your reference:

import { useState } from 'react';

const YourComponent = () => {
    const [appearance, setAppearance] = useState<"default" | "active" | "background">('default');

    const onPressSwitchAppearance = () => {
      if(apperance === 'default') {
        setAppearance('active');
      } else if (apperance === 'active') {
        setAppearance('background');
      } else {
        setAppearance('default');
      }
    }

    return (
        <View>
            <AppearnceButton onPress={onPressSwitchAppearance} appearance={appearance} icon="icon1" />
        </View>
    )

}

but I'm not sure how you want to decide the new value for appearance.

Laxman Sharma
  • 130
  • 1
  • 8
  • on appearance={appearance} it shows error - Type 'string' is not assignable to type '"default" | "background" | "active" | undefined'. Why is that so? – CodingProfile Oct 11 '22 at 11:06
  • 2
    Edited the original reference code. The idea is to define the type of state variable. – Laxman Sharma Oct 11 '22 at 11:13
  • thank you, almost perfect. How could i now switch between all three appearances onPress? should i use map inside my onPress function? – CodingProfile Oct 11 '22 at 11:18
  • 2
    Updated the reference again. This will toggle between the values, but if you want to have it random you can use a random function to generate a new value for the appearance ( refer this: https://stackoverflow.com/questions/7350363/select-a-random-string-from-an-array ) – Laxman Sharma Oct 11 '22 at 11:24
1

you should define a state for it

const [appearance ,setApearance] = useState("default")

and in onPressSwitchAppearance you can use setApearance to change the appearance.