jammy
jammy

Reputation: 977

passing data from child to parent in react and undefind is not a function

I need to pass an array from child component to my parent component . What i did in parent component is :

handlerfordata=(data)=>{
        console.log('Inside handlerfordata data is');
        console.log(data);
    }
Inide return in render .Note Child is name of my child component

return(
          <View>

           <Child  handlerfordata={this.handlerfordata()}/>
           </View>
      );

Now inside my child component i have done something like this

 handleSave = () => {
           //finalvalue is an array that is computed and i can see it in my console and handlesave is triggeed at onclick in child component inside return 
           console.log('finalValue is ',finalValue);
            this.props.handlerfordata(finalValue);
       }

Another thing is that child component gets rendered on the screen but i just want to access data from child component and not rendering it .

Upvotes: 2

Views: 1313

Answers (5)

Isaac
Isaac

Reputation: 12874

ReactJS is known for one way data flow(Top down) meaning whatever data that is flowing or passing, should be in one direction, from parent to child.

In the case where you need to pass data the other way round, perhaps try to apply redux state management instead.

In the code that you are trying as stated, it's only passing a method down from parent to child.

Upvotes: 0

Harikrishnan
Harikrishnan

Reputation: 1097

Inorder to call the method you need to pass the reference in the child element as

<Child  handlerfordata={this.handlerfordata}/>

You cannot access the data from child without rendering the child component.I prefer you to use redux so that all the states are there in a single store.

Upvotes: 0

SuperSec
SuperSec

Reputation: 140

You have to bind your handler :

<Child handlerfordata={this.handlerfordata.bind(this)} />

Upvotes: 1

Praveen Rao Chavan.G
Praveen Rao Chavan.G

Reputation: 2860

By adding this code

<Child  handlerfordata={this.handlerfordata()}/>

You are not passing the reference, rather you are calling this function.

Change it to

<Child  handlerfordata={this.handlerfordata}/>

which will just pass a reference.

Then you can call that from child component using props.

Upvotes: 1

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Pass the reference for handlerfordata and not this.handlerfordata().

It shuld be

<Child  handlerfordata={this.handlerfordata}/>
                       ^^^^^^^^^^^^^^^^^^^^^^

Upvotes: 1

Related Questions