In React JS, I'm facing the issue that all model children are selected when i click the Brand. If I uncheck the Brand, all model children are going to hide. Help me to write a logic that Ex:- If I check Hyundai, then Hyundai car models has to be show and checked only. If I uncheck the any one of the Hyundai model, then the Hyundai has to be uncheck.
Data should like this:
[
{
display: "HYUNDAI",
status: false,
filter: {
key: "make",
value: "hyundai",
},
count: 292,
children: [
{
display: "Grand i10",
status: false,
filter: {
key: "model",
value: "grand i10",
},
count: 81,
},
{
display: "CRETA",
status: false,
filter: {
key: "model",
value: "creta",
},
count: 47,
},
{
display: "Elite i20",
status: false,
filter: {
key: "model",
value: "elite i20",
},
count: 44,
},
],
},
];
import React, { useEffect, useState } from "react";
import "./App.css";
import carData from './data.json';
const App = () => {
const [data, setData] = useState([]);
const [check, setCheck] = useState(false);
useEffect(() => {
fetch(carData)
.then((response) => response.json())
.then((result) => setData(result))
.catch((error) => console.log("error", error));
}, []);
return (
<div>
<h1>Car Brands and it's Models</h1>
{data.map((el) => {
return (
<div className="data">
<table className="table">
<tc>
<th>
<input
type="checkbox"
className="checkbox"
value={check}
onClick={() => {
setCheck(!check);
}}
/>
{el.display}
</th>
</tc>
{check && (
<div className="datas">
{el.children.map((ele, innerIndex) => (
<div key={innerIndex}>
<tc>
<td>
<input type="checkbox" className="checkbox" checked />
{ele.display}
</td>
</tc>
</div>
))}
</div>
)}
</table>
</div>
);
})}
</div>
);
};
export default App;
Update: You can move the display of the brands/models out and make it a smaller component. I'll try to make the least change possible to your code.
App:
Brand:
Models: