Nane
Nane

Reputation: 403

send data through onclick event from child to parent React js?

I am new to React js I am pretty confused that how to send data through onclick event from child to parent component.

Parent Component

...
      onTurn(id){
            console.log(id)//undefined
        }
        renderCardsList(){
              const {cardsList} = this.props

              return cardsList.get('cards').map(({id,front_image}) => {
                  return  <Card
                            image={front_image}
                            onTurn={this.onTurn}
                            />
              })

            }
...

Child Component

const Card = (props) => {
    return(
        <div className="singleCard">
            <div className="imageDiv">
                <img src={props.image} alt="work" />
            </div>
            <div className="bottombar">
                <span onClick={e => props.onTurn(props.id)} className="glyphicon glyphicon-refresh" />
                <span className="glyphicon glyphicon-pencil" />
                <span className="glyphicon glyphicon-pushpin"  />
            </div>
        </div>
    )
};

Upvotes: 0

Views: 2412

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074108

Your onClick expects an id property on props:

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

But you're not providing one:

return  <Card
    image={front_image}
    onTurn={this.onTurn}
    />

So naturally, props.id in the card's render is undefined.

If you want the card to have an id on props, you'll need to specify one, e.g.:

return  <Card
    image={front_image}
    onTurn={this.onTurn}
    id={/*something*/}
    />

Upvotes: 3

Related Questions