I have three div in a row and three rows, In a row we select only one div at a time, another div is select the before div will unselect. my code like
<div className="row">
<div className="heil select"><button>Click One</button></div>
<div className="heil"><button>Click Two</button></div>
<div className="heil"><button>Click Three</button></div>
</div>
<div className="row">
<div className="heil select"><button>Click One</button></div>
<div className="heil"><button>Click Two</button></div>
<div className="heil"><button>Click Three</button></div>
</div>
<div className="row">
<div className="heil select"><button>Click One</button></div>
<div className="heil"><button>Click Two</button></div>
<div className="heil"><button>Click Three</button></div>
</div>
select class is used to click div will highlight, here statically write how this done in react and in a row we select only one div like radio button I am new in react-js, Please solve this Problem, thanks in advance
CodePudding user response:
I just wrote a working example of what you want.
import { useState } from "react";
export default function Rows() {
const numberOfRows = 3;
const rows = Array(numberOfRows).fill(0);
const cellsEachRow = ["Click One", "Click Two", "Click Three"];
const [selectedCellsIndexes, setSelectedCellsIndexes] = useState(
Array(numberOfRows).fill(0)
);
const handleCellClick = (parentIndex, childIndex) => {
setSelectedCellsIndexes((selectedCellsIndexes) => {
selectedCellsIndexes[parentIndex] = childIndex;
return [...selectedCellsIndexes];
});
};
return (
<div>
{rows.map((row, parentIndex) => {
return (
<div className="row">
{cellsEachRow.map((name, childIndex) => {
return (
<div
className={`heil ${
childIndex ===
selectedCellsIndexes[parentIndex] &&
"selected"
}`}
onClick={() =>
handleCellClick(parentIndex, childIndex)
}
>
<button>{name}</button>
</div>
);
})}
</div>
);
})}
</div>
);
}