Reputation: 41
I'm building a basic bike list app. I want to hide the bike's details inside an accordion and load them only when the user open the bike's card. It's working for all the element except the first one.
To do so i write the following code:
return data.bikes.map((bike, index) => {
return(
<Card key={index} onClick={(e) => {this.setState({selected: bike.id});}}>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey={index}>
{bike.title}, {index}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={index}>
<Card.Body>
Bike Details:
<BikeDetails bikeId={this.state.selected}/>
</Card.Body>
</Accordion.Collapse>
</Card>
)
});
To make the first element open I change my code like this:
return data.bikes.map((bike, index) => {
return(
<Card key={index+1} onClick={(e) => {this.setState({selected: bike.id});}}>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey={index+1}>
{bike.title}, {index}, {index+1}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={index+1}>
<Card.Body>
Bike Details:
<BikeDetails bikeId={this.state.selected}/>
</Card.Body>
</Accordion.Collapse>
</Card>
)
});
And now the first element open correctly but I'm not quite happy with this solution. I would like to know if there is a better way of doing it.
CodeSandbox Link: https://codesandbox.io/s/keen-pond-v5y2y?fontsize=14&hidenavigation=1&theme=dark
Upvotes: 1
Views: 1137
Reputation: 41
Answer by Chandradeepta Laha :
In your eventKey property, instead of index, provide bike.id. That should work
Upvotes: 1
Reputation: 261
The better solution is to assign bike.id
to eventKey because you already assigning the index
to Card key as unique key for every card. it work perfect this way.
return data.bikes.map((bike, index) => {
return(
<Card key={index} onClick={(e) => {this.setState({selected: bike.id});}}>
<Card.Header>
<Accordion.Toggle as={Button} variant="link" eventKey={bike.id}>
{bike.title}, {index}
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey={bike.id}>
<Card.Body>
Bike Details:
<BikeDetails bikeId={this.state.selected}/>
</Card.Body>
</Accordion.Collapse>
</Card>
)
});
Upvotes: 3