Issue
I have an array of nested objects like below and constructing a tab.
src="https://i.stack.imgur.com/wMJvF.png" alt="enter image description here" />
- For all the elements key has been given, but even though it is asking key is missing (snapshot provided). Why?
- When I click on parent element all the three parent-child are getting expanded, how to restrict to only clicked parent node?
export const tabData = [
{
id: 1,
name:"Population",
col: [
{ ItemCode: 1001, ItemName: "MalePopulation" },
{ ItemCode: 1002, ItemName: "FemalePopulation" },
{ ItemCode: 1003, ItemName: "TotalPopulation" },
],
},
{
id: 2,
name:"Poverty",
col: [
{ ItemCode: 1004, ItemName: "RuralRationShops" },
{ ItemCode: 1005, ItemName: "UrbanRationShops" },
{ ItemCode: 1006, ItemName: "TotalRationShops" },
],
},
{
id: 3,
name:"Agriculture",
col: [
{ ItemCode: 1007, ItemName: "AgriculturalLand" },
{ ItemCode: 1008, ItemName: "NonAgriculturalLand" },
{ ItemCode: 1009, ItemName: "TotalLand" },
],
},
];
const [open, setOpen] = useState(false);
function clickHandler1(e) {
setOpen(!open);
}
<div className="h-42 overflow-y-auto">
{Object.keys(tabdata).map(function (keyName, keyIndex) {
// console.log(keyName);
// console.log(tabdata[keyName]);
const col1 = tabdata[keyName].col;
return (
<>
<label key={keyIndex} className="flex flex-row">
<button
key={keyIndex}
onClick={(e) => {
clickHandler1(e);
}}
className="flex flex-row"
>
<BiArrowFromTop /> {tabdata[keyName].name}
</button>
</label>
{Object.keys(col1).map(function (keyName1, keyIndex1) {
return (
<>
{open && (
<lable key={col1[keyName1].ItemCode} className="flex flex-row px-6">
<Link key={col1[keyName1].ItemCode}
// href={`gismappage/Year=${yrId}/Chapter=${chpId}/ItemCode=${col1[keyName1].ItemCode}`}> this static goes to ...slug page
href={`gismappage?paths=${yrId}/${chpId}/${col1[keyName1].ItemCode}`}>
<input
name="itm"
key={col1[keyName1].ItemCode}
type="radio"
onClick={() =>
clickhandler2(col1[keyName1].ItemCode)
}
/>
</Link>
{col1[keyName1].ItemName}
</lable>
)}
</>
);
})}
</>
);
})}
</div>
Solution
Check box can be solved like
Kept the state variable empty first onChange event-> taken the radio button value and matched with the value of radio button if true--> radio button will become checked.
const [selected, setSelected] = useState("");
function clickHandler2(e, i) {
alert(e.target.value);
alert(i);
setSelected(e.target.value);
}
<input
type="radio"
value={item[keyName1].ItemName}
checked={item[keyName1].ItemName === selected}
onChange={(e) =>clickHandler2(e, item[keyName1].ItemName)
}
/>
Answered By - Jaya
Answer Checked By - - Pedro (ReactFix Volunteer)