Recently I am working on a puzzle game with react js. I want to select one cell in each column. but unfortunately, I did not do that. the code sample is here. I would be so grateful If you can help me with it.
CodePudding user response:
With your requirement, you need to save the selected column and row that is related.
You can see my code below, I've store related column and row into check State, after that just tweak a little condition on the List
component to show bg-danger
class. Furthermore, I removed onClick
function on the div
component a parent of the List
component, because I think it's useless to do multiple function call at one time for the same action onClick
App.js
import "./styles.css";
import List from "./List";
import { useState, useRef } from "react";
export default function App() {
const [check, setCheck] = useState({});
const [columnId, setColumnId] = useState(null);
const refColumnId = useRef(columnId)
refColumnId.current = columnId;
const data = [
{ id: 1, listOfNumbers: [1, 2, 3, 4, 5, 6] },
{ id: 2, listOfNumbers: [1, 2, 3, 4, 5, 6] },
{ id: 3, listOfNumbers: [1, 2, 3, 4, 5, 6] }
];
const handleIndex = (column, row) => {
setCheck({...check, [column]: row})
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div className="row">
{data.map((data, index) => {
return (
<div className="col-md-4">
<List
columnId={columnId}
key={data.id}
data={data.listOfNumbers}
getIndex={handleIndex}
check={check}
id={data.id}
/>
;
</div>
);
})}
</div>
</div>
);
}
List.js
const List = ({ data, getIndex, check, id, columnId }) => {
const handleCardClick = (column, row) => {
console.log("columnId : ", columnId);
console.log("id : ", check);
getIndex(column, row);
};
return (
<div className="d-flex flex-column">
{data.map((number, index) => {
return (
<div className="card">
<div
className={`card-body ${
check.hasOwnProperty(id) && index === check[id] ? "bg-danger" : ""
}`}
onClick={() => handleCardClick(id, index)}
>
<h3>{number}</h3>
</div>
</div>
);
})}
</div>
);
};
export default List;