world... again.
I'm stumped by something that should be straightforward, but right now I cant see it. I'm trying to map over a simple array and display values. Each card should have a button that opens a bs modal which should show more information on the particular array object. but instead it returns infomation only on the first object in the array.
I think there's a concept here that I'm not getting and it's a shade embarassing. Thaank's in advance for your help.
import "./styles.css";
export default function App() {
const modalInfo = [
{ name: "james", number: "1" },
{ name: "Jackie", number: "2" },
{ name: "Ariane", number: "3" },
{ name: "Mike", number: "4" }
];
return (
<>
<div className="App">
{modalInfo.map((info) => (
<div className="card">
<h1>{info.name}</h1>
<button
type="button"
data-bs-toggle="modal"
data-bs-target="#staticBackdrop"
>
Show more
</button>
<div
id="staticBackdrop"
data-bs-backdrop="static"
data-bs-keyboard="false"
tabindex="-1"
aria-labelledby="staticBackdropLabel"
aria-hidden="true"
>
<div >
<div >
<div >
<h5 id="staticBackdropLabel">
#{info.number}
</h5>
<button
type="button"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div >{info.name}</div>
<div >
<button
type="button"
data-bs-dismiss="modal"
>
Close
</button>
<button type="button" >
Understood
</button>
</div>
</div>
</div>
</div>
</div>
))}
</div>
</>
);
}
CodePudding user response:
id
attributes must be unique in a document. You are re-using staticBackdrop
in each map iteration so they're being duplicated.
When Bootstrap tries to grab the modal target by #staticBackdrop
, it only gets the first one because that's what happens with repeated IDs.
Assuming the number
property in your objects is unique, try incorporating that into the id
and data-bs-target
{modalInfo.map((info) => (
<div className="card" key={info.number}> {/* keys are important too */}
<h1>{info.name}</h1>
<button
type="button"
data-bs-toggle="modal"
data-bs-target={`#staticBackdrop_${info.number}`}
>
Show more
</button>
<div
id={`staticBackdrop_${info.number}`}
data-bs-backdrop="static"
data-bs-keyboard="false"
tabindex="-1"
aria-labelledby="staticBackdropLabel"
aria-hidden="true"
>
{/* etc */}
</div>
</div>
))}
CodePudding user response:
You must be getting some unique key error in your console.
Give a key
to you card that acts a a unique id
for your card.
<....
{modalInfo.map((info, index) => (
<div className="card" key={info.index}>
...>
You can give index
as well as a unique id
but that not correct way just for testing you can. But from what I see is the number
property is incrementing by 1 as well so that's why I have kept index
as the key
.