0

I got the property from the child but how can I pass to the parent?

in parent.js

<Child childId={() => this.getchildId()} />

getchildId = (id) => { 
   // do something 
   console.log(id) // return undefined
}

in child.js

const id = "something";

<Item itemid={this.getId(id)} />

getId = (id) => { 
    console.log(id); // return "something"
    this.props.childId(id)
}

Update! It works with

in parent.js

<Child childId={this.getchildId} />

Now the problem is they are keep being called...

susu watari
  • 177
  • 1
  • 2
  • 11

3 Answers3

0
<Child childId={this.getchildId} />

getchildId = (id) => { 
 // do something 
 console.log(id) // return undefined
 }

In parent.js just pass the function reference.

LuisMendes535
  • 526
  • 7
  • 18
0
// in parent
getchildId = (id) => { 
   // do something 
   console.log(id) // return undefined
}

<FirstChild logChildId={this.getchildId}


// in FirstChild 
<SecondChild logChildId={props.logChildId} />

// in SecondChild
<button onClick={() => props.logChildId("test")}>
click me
</button>

so it's just passing down the function pointer via props

Can you show the code for your <Item /> component? make sure that the function isn't directly invoked and only referenced by arrow function just as I pointed out in second child, or via method if you are writing a class function

// in SecondChild

handleLogChildId = (id) => {
  const { logChildId } = this.props
  logChildId(id)
}

<button onClick={this.handleLogChildId("test")}>
click me
</button>
Lelouch
  • 910
  • 6
  • 19
0

Passing anything from child to parent is very simple via functions.

let assume you have a parent like this

class Parent extends Component {
 constructor(props){
  this._getProps = this._getProps.bind(this);
 }
 _getProps(data) { // Here you will receive the props data from child component.
  console.log(data);
 }
 render(){
  return (
   <Child getProps = {this._getProps}/>
  );
 }
}


class Child extends Component {
 constructor(props){
  this._sendProps = this._sendProps.bind(this);
 }
 _sendProps(data) {
  this.props.getProps(data); // This will send your props data to parent function.
 }
 render(){
  return (
   <div> </div>
  );
 }
}
Amit Chauhan
  • 1,810
  • 3
  • 17
  • 25