React Native Pass data to another component

10,397

Solution 1

I am late to answer but I did in different way using props.

I have two components.

  1. Splash.js
  2. Home.js

I am passing the data (Let's take String) from Splash.js to Home.js.

First component (Sender)

this.props.navigation.navigate('Home', {user_name: userName})

Second component (Receiver)

this.props.navigation.state.params.user_name

Hope this would help you.

Solution 2

OK, so based on your infos, I think the issue is that you don't get the singerName in the Messenger component.

First, I'd change your getArtistName method to this :

getArtistName: function () {
    var artist = [];
    var query = new Parse.Query(Parse.User);
    query.equalTo('userId', this.state.artistUserId);
    return query.first({
        success: (result) => {
            this.setState({artistName: result.get('name')});
            // Removed the this.props.singerName = ... 
            this.setState({imagePath: result.get('image').url()});
        },
        error: (data, error) => {
            console.log('Error occured : ' + error.message())
        }
    });
}

then in your render method :

<Messenger singerName={this.state.artistName} />

Inside a component you need to use setState and not change props : that is to say that this.props.singerName = 'singer' is a wrong way of doing things, you should do this.setState({singerName: 'singer'}); then access it with this.state.singerName

Inside your messenger component, you access it with this.props.singerName

Share:
10,397

Related videos on Youtube

Green
Author by

Green

Updated on June 05, 2022

Comments

  • Green
    Green almost 2 years

    I am new to React Native and trying to build a Messenger app and I have 2 components Search and Messenger​. I am struggling to pass the data I got from Search to Messenger.

    Search component finds user (receiver) and me being sender I want to communicate but after finding user in Search I want to pass that user to Messenger so that I can chat with that specific user that found in <Search> component.

    In addition, Search component has Views that will display user calendar etc.. so ideally I don't want to use <Messenger> in render() method of Search as it will include Messenger component features inside the Search component which destroys the purpose of <Search> component.

    So my code is :

    'use strict';
    
    
    var Search = React.cerateClasss({
    
    getDefaultProps: function () {
        return {
            date: new Date(),
            singerName:''
        };
    },
    getInitialState: function () {
        return {
            date: this.props.date,
            artistName: '',
            artistUserId: 1,
            maxNoArtist: 0,
            imagePath: '../common/images/1.png',
            user: null
        }
    },
    getArtistName: function () {
        var artist = [];
        var query = new Parse.Query(Parse.User);
        query.equalTo('userId', this.state.artistUserId);
        return query.first({
            success: (result) => {
                this.setState({artistName: result.get('name')});
                this.props.singerName= result.get('name');
                this.setState({imagePath: result.get('image').url()});
            },
            error: (data, error) => {
                console.log('Error occured : ' + error.message())
            }
        });
    },
    render: function () {
        if (!this.state.user) {
            return <View style={styles.container}>
                <Text style={styles.label}> Loading.... </Text>
            </View>
        }
        var username = this.state.user.get('username');
    
    
        return (
                <View style={styles.container}>
    
                <ResponsiveImage source={{uri:this.state.imagePath}} initHeight="200" initWidth="400"/>
    
    
                <Text style={styles.label}>
                    {this.state.artistName}
                </Text>
    
                <View style={styles.innerButtonView}>
                    <Button text={'Onki'} onPress={this.getPreviousArtistName}/>
                    <Button text={'Indiki'} onPress={this.getNextArtistName}/>
                </View>
    
                <CalendarPicker
                    selectedDate={this.state.date}
                    onDateChange={this.onDateChange}
                    />
    
                <View style={styles.innerButtonView}>
                    <Button text={'Cyk'} onPress={this.onLogoutPress}/>
                    <Button text={'Habarlas'} onPress={this.onPress}/>
                </View>
    
               <Messenger singerName={this.props.singerName}></Messenger> // BREAKS SEARCH COMPONENT PURPOSE - INCLUDES MESSENGER FEATURES IN TO SEARCH COMPONENT
    
            </View>
        );
    },
    })
    
    
    var Messenger = React.createClass({
        getInitialState: function () {
            return {
                greeting: 'Salam',
                date: new Date(),
                errorMessage: '',
                user: null,
                olderMessageTextFrom: [],
                olderMessageTextTo: [],
                olderMessageDateFrom: [],
                olderMessageDateTo: [],
                earlierMessages: []
            }
        },
        componentWillMount: function () {
            Parse.User.currentAsync().then((user) => {
                    this.setState({user: user})
                }
            )
        },
        getMessages() {
            return [
                {
                    text: this.state.greeting,
                    name: this.props.singerName,
                    image: require('../common/images/1.png'),
                    position: 'left',
                    date: new Date()
                },
    
  • Green
    Green about 8 years
    Thanks for constructive feedback much appreciated. I have tried above mentioned solution but I have 2 issues. 1. When I add <Messenger singerName={this.state.artistName} /> then all features that live in Messenger component appears on Search page 2. I still dont get singerName in Messenger component.
  • Green
    Green about 8 years
    Updated previous comment to mention 2 issues. Here is the repo to my app : github.com/ckurban/toyagel.git
  • G. Hamaide
    G. Hamaide about 8 years
    I edited my answer. Runs fine and I get the artist with this.props.singerName in Messenger component. If you add the component Messenger, it is normal for all features to appear. Maybe add a prop: <Messenger singerName={this.state.singerName} displayFeatures={false} /> and in messenger component check if this.props.displayFeatures is true to display some features.
  • Green
    Green about 8 years
    When you say : you should do this.setState({singerName: 'singer'}); then access it with this.state.singerName Inside your messenger component, you access it with this.props.singerName I thought we do use setState when we are changing state rather than prop, but if I do this.setState({singerName: 'singer'}); then it is changing the singerName prop or do you mean artistName state ?
  • G. Hamaide
    G. Hamaide about 8 years
    Inside the messenger component : you access singerName with this.props.singerName Inside the search component you set it with this.setState({singerName: 'name')} and access it with this.state.singerName
  • Green
    Green about 8 years
    Nope still does not get it. Here is the code where I am trying to display artist name in messenger component - where did you try in search component : getMessages() { return [ { text: this.state.greeting, name: this.props.singerName,
  • Green
    Green about 8 years
    I am keep getting : 2016-02-24 13:19:41.212 [trace][tid:com.facebook.React.JavaScript] Artist name : undefined