Home > Software design >  How to use state in React Native custom component?
How to use state in React Native custom component?

Time:07-15

I am trying to create a counter app where certain cards either 1 or -1. As each number on the keypad is clicked the counter increments 1 or -1. So far I've created a custom component and trying to use state in order to

export default function App() {

  const cards = [
    { card: "A", count: -1 },
    { card: "K", count: -1 },
    { card: "Q", count: -1 },
    { card: "J", count: -1 },
    { card: 10, count: -1 },
    { card: 9, count: 0 },
    { card: 8, count: 0 },
    { card: 7, count: 0 },
    { card: 6, count: 1 },
    { card: 5, count: 1 },
    { card: 4, count: 1 },
    { card: 3, count: 1 },
    { card: 2, count: 1 },
  ];


  const [currentCount, setCount] = useState(0); //Count <<

  return (
    <View style={styles.app}>
      <CardCount useState={currentCount}/> // Custom component <<
      <View style={styles.cards}>
      {cards.map((index) =>(<Card item={index}/>))}
      </View>
    </View>
  );
}

The custom component 

export const CardCount = ({currentCount}) => {
  return (
    <Text>{currentCount}</Text>
  )
}

I am not seeing any results for this? Unless I am using the state wrong

Thanks a lot

CodePudding user response:

your custom component should be like this to show received props

export const CardCount = ({useState}) => {
  return (
    <Text>{useState}</Text>
  )
}

CodePudding user response:

<CardCount useState={currentCount}/>

This line of code says that your CardCount Component-Props consist of an object with a useState property.

export const CardCount = ({currentCount}) => {

What you actually expect is currentCount -> instead of useState={currentCount} you have to write currentCount={currentCount} ; the first currentCount refers to the property which your CardCount-Component expects as a prop. The second currentCount refers to your state-variable in the parent-component.

This will always display a 0 though, the default value.

To be able to modify the count value, you could wrap your setCount function in a callback, add this function to your Card as a prop and then create an onClick-event on the card which calls the props-callback with some value.

  • Related