Jessie Richardson
Jessie Richardson

Reputation: 958

Pass Data to a Component in React Native?

I'm having trouble with the syntax on props when passing a data structure to a component in React Native. If anyone could help me see how I can reuse the component 'DisplayPerson' below by passing it 'FemaleInfo' and then again 'MaleInfo' would greatly appreciate it.

var FemaleInfo = [
    {name: 'Jane Doe', age: 23, occupation: 'Carpenter'},
    {name: 'Kate Ryan', age: 31, occupation: 'Lawyer'},
    {name: 'Ellen Anderson', age: 42, occupation: 'Doctor'}
];

var MaleInfo = [
    {name: 'John Doe', age: 23, occupation: 'Carpenter'},
    {name: 'Jack Douglas', age: 31, occupation: 'Lawyer'},
    {name: 'Rick Smith', age: 42, occupation: 'Doctor'}
];

var DisplayPerson = React.createClass({
    getInitialState: function() {
        return {
            name: FemaleInfo[0].name,
            age: FemaleInfo[0].age,
            occupation: FemaleInfo[0].occupation
        };
    },
    render() {
        return (
            <Text style={styles.data}>
                {this.state.name}
            </Text>
            <Text style={styles.data}>
                {this.state.age}
            </Text>
            <Text style={styles.data}>
                {this.state.occupation}
            </Text>
})

Upvotes: 2

Views: 1755

Answers (1)

Jagadish Upadhyay
Jagadish Upadhyay

Reputation: 1264

Create a parent component for DisplayPerson. Pass the info from parent to child and use the props in the child component.

Something like:

and use info in DisplayPerson component.

render() {
    let info = this.props.info;
    return (
        <View>
            <Text style={styles.data}>
                {info.name}
            </Text>
            <Text style={styles.data}>
                {info.age}
            </Text>
            <Text style={styles.data}>
                {info.occupation}
            </Text>
        </View>)
}

Upvotes: 2

Related Questions