Alex Ironside
Alex Ironside

Reputation: 5039

Passing props in React Native

I have this component:

<View style={{backgroundColor: solved === true ? 'green' : '#ff5b68'}}>
    <Text>{error}</Text>
    <Text>{errorInfo}</Text>
    <Text>{key}</Text>
    <Text>{uid}</Text>
    <MarkedAsSolvedButton key={key}/>
</View>

And I want to pass the key to the MarkedAsSolvedButton component. Code below:

export default class MarkedAsSolvedButton extends React.Component {
    componentWillReceiveProps(nextProps) {
        alert(nextProps.key)
    }

    handlePress = () => {
        alert(this.props.key);
    };

    render() {
        return (
            <Button onPress={this.handlePress} title={'Marked as solved' + this.props.key}/>
        );
    }
}

But when I try to see the key, it says undefined. But it gives me the value in the parent component.

What am I missing?

Upvotes: 1

Views: 285

Answers (3)

Ikhsan Mahendri
Ikhsan Mahendri

Reputation: 143

onPressButton(){}
render() {
    return (
     <ChildrenComponent
      name={"testing to props"}
      onFunction={this.onPressButton.bind(this)}
      key={this.state.key}
    />
    );
}

and in children component

<View>
    <Button onPress={()=>this.props.onFunction(this.props.key)}>
      <Text>{this.props.name}</Text>
    </Button>
</View>

you can use like that with difrent props after render you can call props

Upvotes: 0

Diego Lopez
Diego Lopez

Reputation: 39

Add constructor with props:

constructor(props) {
    super(props)           
}

Upvotes: -1

Nicholas Tower
Nicholas Tower

Reputation: 84982

key is a very special prop in react, and it is deliberately not exposed to the child component. It exists as a way to provide react with additional information that it can use to optimize performance, especially when dealing with lists (see this page). If you need the information to be exposed to the child, you'll need to pass it as a different prop (this could either be in addition to a key prop, or instead of it). For example:

// In the parent component's render:

<MarkAsSolvedButton key={key} identifier={key} />

// in MarkAsSolved:
handlePress = () => {
  alert(this.props.identifier);
}

Upvotes: 6

Related Questions