Home > Net >  React native How to get value from Pressable/Text
React native How to get value from Pressable/Text

Time:09-06

Hello i am new to reavt native and i don't understand how csn i get the value from Pressable/Text componente I mean I have a gender select on my app Which has Pressable and inside this a Text When the user click it should updste the state to this value that selected But i cant do it...

const SignUpPageButtons = ({ label }) => {
  const [toggleColor, setToggleColor] = useState(false);

  return (
    <>
    
      <Pressable
    
        style={[{ backgroundColor: toggleColor ? "green" : "white" }, styles.button]}
        onPress={() => {
       
          setToggleColor(!toggleColor);
        }}
      >
        <Text style={[{ color: toggleColor ? "white" : "green" }, styles.button_text]}>{label}</Text>
      </Pressable>
    </>
  );
};

CodePudding user response:

i would make const [toggleColor, setToggleColor] = useState(false); on the parent, then pass it on SignUpPageButtons props like this <SignUpPageButtons label={label} toggleColor={toggleColor} setToggleColor={setToggleColor} />

then in SignupPageButtons use it like this...

const SignUpPageButtons = ({ label, toggleColor, setToggleColor }) => {
  return (
    <>
    
      <Pressable
    
        style={[{ backgroundColor: toggleColor ? "green" : "white" }, styles.button]}
        onPress={() => {
       
          setToggleColor(!toggleColor);
        }}
      >
        <Text style={[{ color: toggleColor ? "white" : "green" }, styles.button_text]}>{label}</Text>
      </Pressable>
    </>
  );
};

CodePudding user response:

You can check this : https://snack.expo.dev/S8wZMuwRH

import {React, useState} from 'react';
import { Text, View, StyleSheet,Pressable } from 'react-native';
import Constants from 'expo-constants';


const SignUpPageButtons = ({ label, toggleColor,setToggleColor }) => { 

  return (
    <>
      <Pressable
    
        style={[{ backgroundColor: toggleColor ? "green" : "white" }, styles.button]}
        onPress={() => {
          setToggleColor(!toggleColor);
        }}
      >
        <Text style={[{ color: toggleColor ? "white" : "green" }, styles.button_text]}>{label}</Text>
      </Pressable>
    </>
  );
};


export default function App() {
const [toggleColor, setToggleColor] = useState(false);



  return (
    <View style={styles.container}>
     <SignUpPageButtons label={toggleColor?"green":"white"} toggleColor={toggleColor} setToggleColor={setToggleColor} />

    </View>
  );
}



const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Hope it helps,

  • Related