I’m a beginner at React and I’m trying to implement single selection on my cards where in only one card can be selected at a time and the selected card is highlighted. This is my borderCard component
export const BorderCard = styled.div` width: 100%; box-sizing: border-box; background:{(props) => props.selected ? "1.5px solid #2375A4" : "1px solid #d5dde3"} `;
This BorderCard is then used in my PaymentCard component
const PaymentCard = ({ option }) => { return ( <BorderCard style={{ marginTop: "10px"}} selected > <Row> <StatusHead style={{ fontWeight: 500 }}>{option.optionText}</StatusHead> <StatusHead>₹ {formatAmount(option.totalPayable)}</StatusHead> </Row> </BorderCard> ); };
And finally all these payment cards are displayed one after the other using maps.
return ( <ScrollableBox> {paymentOptions.map((option, index) => ( <PaymentCard key={index} option ={option} onChange = {() => setisSelected(index)} /> ))} </ScrollableBox> <Row style={{ marginTop: "15px", alignItems: "flex-start" }}> <BsExclamationCircle style={{ fontSize: "20px", paddingTop: "2px", margin: "0 8px", }} /> <SubText> {paymentOptions.length > 0 ? paymentOptions[0].lateChargeText : ""} </SubText> </Row> };
I have prop called selected in the BorderCard component and on passing it in the PaymentCard component all the cards are selected instead of one. Secondly in the final return statement I have paymentOptions[0] hard coded where it should be based on the on the array element (i.e card) currently selected. For that I understand I can use the findIndex() method to get the index of the card currently selected but I’m not able to write a function to handleSelection and to appropriately use the selected prop in my BorderCard component. Should I use a state to store the selected card instead? Please help me understand this.
const handleSelection = ; const selectedIndex = paymentOptions.findIndex(handleSelection);
Recent Comments