Home > Net >  Passing data between react native components not working
Passing data between react native components not working

Time:12-06

I've been following the instructions in this document, and have tried some answers from other questions on this website, but none of them are printing the props on the page. Not sure if I'm calling it wrong, or not passing the data properly. Have posted my parent, and 3 separate attempts at getting the child to work. Nothing shows on the page. I have imported child component into parent page, and { component } in child page.

parent:

const ToyDetails = () => {
  const [data, setData] = useState('');

  const parentToChild = () => {
    setData(name)
  }

  return (
    <View>
        <CardCard parentToChild={data}
        <TouchableOpacity onPress={()=>parentToChild()}
          <Text>{buttonText}</Text>
    </View>
  )
}

child (CartCard.js) attempt 1: prints data on parent page

export default class CartCard extends Component {
  render() {
    const { data } = this.props;
      return (
        <View>
          <Text>{data}</Text>
        </View>
      )
   }
}

child attempt 2: prints nothing on either page

export default class CartCard extends Component {
  render() {
    const { data } = this.props;
      return (
        <View>
          <Text>{this.props.parentToChild}</Text>
        </View>
      )
   }
}

child attempt 3: prints data on parent page

const CartCard = ({parentToChild}) => {
   
  return (
    <View>
      <View>
        <Text>{parentToChild}</Text>
      </View>
    </View>
  )
}

export default CartCard

CodePudding user response:

add a useState to buttonText

const ToyDetails = () => {
  const [buttonText, setButtonText] = useState()

CodePudding user response:

Here's an example on how to pass data to children component as props, based on your code https://snack.expo.dev/peRi9sELk Its hard to say whats going wrong for you, but in order to see a change being reflected in your components, you have to cause a re-render of the component tree. The easiest way to do that is by changing state.

  • Related