0

I'm using Bootstrap to build a basic table and I want to handle the user clicking on a row so that I can mark it as selected.

My list items have nested elements. When I click directly on the list item the onClick handler gets called and 'event.target.value' is set correctly.

When I click on a nested element then the onClick handler still gets called but the 'event.target.value' is undefined.

I've read lots of suggestions based on binding inside the render method but I know this is not a recommended thing to do.

class TeamListItem extends Component {

    constructor(props) {
        super(props);
        this.internalHandleSelectTeam = this.internalHandleSelectTeam.bind(this);
    }

    internalHandleSelectTeam(event) {
        console.log(event.target.value);
    }

    render() {
        const team = this.props.team;   
        return (
            <li className="list-group-item" value={team.teamId} onClick={this.internalHandleSelectTeam}>
                <Row>
                    <Col xs={10} sm={8} md={6}>
                        {team.teamName}
                    </Col>
                    <Col xs={2} sm={4} md={6}>
                        {team.resourceList.length}
                    </Col>
                </Row>      
            </li>
        );
    }
}

export { TeamListItem }
nemesv
  • 138,284
  • 16
  • 416
  • 359
jafwatt
  • 323
  • 4
  • 19

1 Answers1

1

Ok, I've got it working by modifying the 'internalHandleSelectTeam' function:

internalHandleSelectTeam() {
    const teamId = this.props.team.teamId;
    this.props.onSelectTeam(teamId);
}

I'm not sure if this is good practice or not but it works and doesn't require binding inside the render function.

jafwatt
  • 323
  • 4
  • 19
  • 1
    Yes that's the normal pattern. The only thing I would change is just call the function handleSelectTeam without the 'internal'. – brub Dec 22 '17 at 16:04
  • Check this answer on why you were getting an error https://stackoverflow.com/questions/46642018/divs-id-attribute-is-undefined-not-getting-captured-onclick-in-a-react-app/46642915#46642915 also check this answer to know methods to avoid binding inside render https://stackoverflow.com/questions/45053622/how-to-avoid-binding-inside-render-method/45053753#45053753 – Shubham Khatri Dec 22 '17 at 17:51