Home > OS >  React change logic to avoid repeating code
React change logic to avoid repeating code

Time:09-21

How could i simplify isPressedStyle and isPressedStyle2 so that i dont have to repeat myself? Is it possible to have them both in one logical line? if variant === "white" its container has a white background and if isPressed the background changes to gray. But if variant === "transparent" there should be no background color and the opacity on isPressed should change.

   export function List() {
        return <View>
                    <ListItem variant="transparent"/>
                    <ListItem variant="white" />
             </View>;
}

type ListItemProps = {
    variant: "transparent" | "white";
};

export function ListItem({ variant }: ListItemProps) {
    const [isPressed, setIsPressed] = React.useState(false);
    const isPressedStyle = variant === "white" && isPressed ? { backgroundColor: "gray" } : {};
    const isPressedStyle2 = variant === "transparent" && isPressed ? { opacity: 0.5 } : {};
    function onPressIn() {
        setIsPressed(true);
    }
    function onPressOut() {
        setIsPressed(false);
    }
    return (
        <View style={[ styles.row, variant === "white" && styles.backgroundColorWhite]}>
            <Pressable
                onPressIn={onPressIn}
                onPressOut={onPressOut}
                style={[
                    styles.container,
                    isPressedStyle, //How to have these two isPressed in one line
                    isPressedStyle2,
                ]}
            >
            </Pressable>
        </View>
    );
}
const styles = StyleSheet.create({
    container: {
        flexDirection: "row",
        flex: 1,
        padding: 16,
    },
    backgroundColorWhite: {
        backgroundColor: 'white',
    },
   row: {
    flexDirection: "row",
},

CodePudding user response:

const isPressedStyle = variant === 'white' && isPressed
  ? { backgroundColor: 'gray' }
  : variant === 'transparent' && isPressed
  ? { opacity: 0.5 }
  : {};


const isPressedStyle = isPressed
  ? (variant === 'white' && { backgroundColor: 'gray' }) || (variant === 'transparent' && { opacity: 0.5 })
  : {};
  • Related