How To Show Collapsible Content Correctly Inside An Array Map?
So I made an array of object and map the array. I also make a simple collapsible. The thing is, the collapsible didn't work correctly. It should only show the content where the use
Solution 1:
You are using the same single boolean state to toggle all of the collapsible divs. Instead, store some state that uniquely identifies a mapped element, like the data's id
property. Use the id to check if the div should be collapsed or visible.
constApp = () => {
const [showCollapsible, setShowCollapsible] = useState({});
const myDatas = [
{
id: 1,
fullName: "John Doe",
age: 28,
status: "On Duty"
},
{
id: 2,
fullName: "Jane Doe",
age: 27,
status: "Rest"
},
{
id: 3,
fullName: "James Doe",
age: 32,
status: "Take a leave"
}
];
consttoggleCollapsable = (id) => () => {
setShowCollapsible((set) => ({
...set,
[id]: !set[id]
}));
};
return (
<div>
{myDatas.map((data) => {
return (
<div><p>{data.fullName}</p><p>{data.age}</p><buttononClick={toggleCollapsable(data.id)}>Status</button>
{showCollapsible[data.id] && <div>{data.status}</div>}
</div>
);
})}
</div>
);
};
It would be a little more clean to abstract a Collapsible
component that manages that state.
constCollapsibleDiv = ({ children }) => {
const [showCollapsible, setShowCollapsible] = useState(false);
return (
<><buttononClick={() => setShowCollapsible((show) => !show)}>
Status
</button>
{showCollapsible && children}
</>
);
};
constApp = () => {
const myDatas = [
{
id: 1,
fullName: "John Doe",
age: 28,
status: "On Duty"
},
{
id: 2,
fullName: "Jane Doe",
age: 27,
status: "Rest"
},
{
id: 3,
fullName: "James Doe",
age: 32,
status: "Take a leave"
}
];
return (
<div>
{myDatas.map((data) => {
return (
<div><p>{data.fullName}</p><p>{data.age}</p><CollapsibleDiv><div>{data.status}</div></CollapsibleDiv></div>
);
})}
</div>
);
};
Post a Comment for "How To Show Collapsible Content Correctly Inside An Array Map?"