When I click the p tag the modal box shows up, but the title and text of the selected item in sidebarTitle, is not showing. I Have made an array with different titles and text, and I would like them to show up inside the modal, when a press one of their titles. Here is my code:
import React, { useState } from "react";
import "../sidebarStyles.css";
function Modal({ title, text, closeModal }) {
return (
<div className="modal">
<div className="modal-content">
<span className="close" onClick={closeModal}>
X
</span>
<div className="content">
<h2>{title}</h2>
<p>{text}</p>
</div>
</div>
</div>
);
}
const sidebarTitle = [
{
title: "Text",
text: "Modal",
},
{
title: "Scope",
text: "Modal",
},
{
title: "Analysis",
text: "Modal",
},
];
function Sidebar() {
const [selectedItem, setSelectedItem] = useState(false);
const handleTitleClick = () => {
setSelectedItem(true);
};
const closeModal = () => {
setSelectedItem(false);
};
return (
<div className="sidebar">
{sidebarTitle.map((item, index) => (
<div key={index}>
<p onClick={handleTitleClick}>{item.title}</p>
</div>
))}
{selectedItem ? (
<Modal
title={selectedItem.title}
text={selectedItem.text}
closeModal={closeModal}
className="modal"
/>
) : (
!selectedItem
)}
</div>
);
}
export default Sidebar;
2
Answers
In your code,
selectedItem
is a boolean state variable, and so it won’t have any properties such astitle
ortext
, that’s why you aren’t able to view anything on the UI. You can instead change it to an object such as –and then, change your functions in this way –
and –
and change your p tag to look like this –
<p onClick={()=>handleTitleClick(item.title, item.text)}>{item.title}</p>
and to display the modal, instead of using
selectedItem
, useselectedItem.visible
instead.if any other explanation is required, do let me know.
Your
selectedItem
is of typeboolean
, soselectedItem.title
get’s you undefined.Change your handler to :
and your map function to :
And try not to use index as a key value. More on that topic here => error: Do not use Array index in keys