1

I am trying to pass a function down to a child then down another level to that child's child then have that pass it's id back up to the parent but I can't figure out how to pass the id back up. I can get the function to get called without passing parameters back but I can't get it to work with it.

Here is my parent component:

class SideBar extends Component {
constructor(props){
    super(props);
    this.state={
        groups: [
            {name: 'Test', id: 1},
        ],
        open: false,
        selectedIndex: 1
    };
}
handleSelectedIndex = (id) => {
    console.log('selected id: ' + id);
};
render(){
    return(
        <div className={classes.Groups}> 
            <Groups groups={this.state.groups} selected={this.state.selectedIndex} handleSelected={this.handleSelectedIndex}/>
        </div>
    );
}

Here is the first child:

const groups = (props) => (
<List component="nav" className={classes.GroupContainer}>
    {
        props.groups.map(group => 
            <Group 
                name={group.name} 
                key={group.id} 
                id={group.id} 
                selected={props.selected} 
                handleSelected={props.handleSelected}/>
        )
    }
</List>
);

And here is the child's child:

const group = (props) => {
let id = props.id
return(
    <>
    <ListItem
        button
        selected={props.selected === props.id}
        className={classes.Group}
        onClick={props.handleSelected(id)} 
    >
        <ListItemText 
            className={classes.GroupTitle} 
            primary={props.name} 
            key={props.key}/>
    </ListItem>
    <Divider className={classes.Divider}/>
    </>
);
};

Can someone please explain how to pass the id back up?

Ben Cavenagh
  • 608
  • 1
  • 6
  • 22
  • Possible duplicate of https://stackoverflow.com/questions/44754051/passing-data-from-child-to-parent-component-react-via-callback-function – SakoBu Nov 30 '18 at 01:53
  • @SakoBu not a duplicate of that. That only has one child involved. I am trying to go through a middleman child component – Ben Cavenagh Nov 30 '18 at 01:56

1 Answers1

1

You need to invoke the handler in the right way in your child's child component.

This line will invoke the handler while the component is getting rendered and not on onClick.

onClick={props.handleSelected(id)} 

Instead, it should be like this

onClick={(e) => props.handleSelected(id)} 

This will bind the event listener correctly.

Dinesh Pandiyan
  • 5,814
  • 2
  • 30
  • 49