Home > Enterprise >  How to toggle between two elements using single React state
How to toggle between two elements using single React state

Time:10-18

How to toggle between two elements using a single React state? Right now both of the elements are toggled via onPress but should toggle only one at a time.

  const [active, setActive] = React.useState(false);
    
  function toggle() {
    setActive((active) => !active);
  }

  return (
    <View style={styles.row}>
      <CustomButton onPress={toggle} active={active} />
      <CustomButton onPress={toggle} active={active} />
    </View>
  );
}

CodePudding user response:

May be something like below ... as Hao said

    const [active, setActive] = React.useState("");

    function toggle(name) {
        setActive(name);
    }

    return (
                <View style={styles.row}>
                    <CustomButton onPress={()=>toggle("one")} active={active === "one"}/>
                    <CustomButton onPress={()=>toggle("two")} active={active === "two"}/>
                </View>
           );
    } 
  • Related