Home > Software design >  React Native cant change style onPress
React Native cant change style onPress

Time:09-07

How can i properly change the state of the TapBarItem in TapBar function so that it changes color based on that if active is true or false like in the TapBarItem function below <Icon color={active ? "red" : "gray"} name={icon} /> right now only the else part works and the icon and text is gray. Right now nothing happens onPress

export function TapBar() {

    const [activeItem, setActiveItem] = React.useState("fork");

return (
    <View>
        <TabBarItem
            icon="fork"
            label="label"
            onPress={() => {
                setActiveItem({ active: "fork" });
            }}
            active={activeItem === "fork"}
        />
    </View>
);
}

type TabBarItemProps = {
    label: string;
    icon: IconName<24>;
    onPress: () => void;
    active: boolean;
};

function TabBarItem({ label, icon, onPress, active }: TabBarItemProps) {
    return (
        <Pressable onPress={onPress}>
            <Icon color={active ? "red" : "gray"} name={icon} />
            <Text color={active ? "red" : "gray"}>
                {label}
            </Text>
        </Pressable>
    );
}

CodePudding user response:

You are setting state as an object ,

You should just do this

onPress={() => {
                setActiveItem("fork");
            }}
            active={activeItem === "fork"}

rather than this

 onPress={() => {
                setActiveItem({ active: "fork" }); // here its an object, please check
            }}
            active={activeItem === "fork"}
  • Related