On first click the focus should come on the cell on the second click , focus should come on the input box…
import React, { useState } from 'react';
function App() {
const [currentIndex, setCurrentIndex] = useState(null);
// const [currentColor, setCurrentColor] = useState("");
const [array, setArray] = useState(Array.from({ length: 4 }, () =>
Array.from({ length: 4 }, () => ({
color: "",
text: "",
})
))
)
function selectCell(row,col){
console.log("Selected Cell ==>",row,col);
console.log("CurrentIndex ==>",currentIndex);
setCurrentIndex({row:row,col:col})
}
function handleText(text,row,col){
console.log("Text =>",text)
let newArray=[...array];
newArray[row][col].text=text;
setArray(newArray);
console.log("Array =>",array)
}
function changeColor(color){
if (currentIndex) {
const newArray = [...array];
newArray[currentIndex.row][currentIndex.col].color = color;
setArray(newArray);
}
}
return (
<div className="App" style={{ display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
<div style={{ marginTop: "100px" }}>
<button onClick={() => changeColor("red")}>Red</button>
<button onClick={() => changeColor("blue")}>Blue</button>
<button onClick={() => changeColor("green")}>Green</button>
</div>
<div style={{ marginTop: "100px" }}>
{array.map((arr, rowIndex) => (
<div key={rowIndex} style={{ display: "flex" }}>
{arr.map((item, colIndex) => (
<div
onClick={()=>selectCell(rowIndex,colIndex)}
key={colIndex}
style={{ width: 100, height:50, margin:2, display:'flex',alignItems:"center",justifyContent:"center",
backgroundColor: item.color,
border: currentIndex && currentIndex.row === rowIndex && currentIndex.col === colIndex ? "2px solid black" : "1px solid black"
}}
>
{currentIndex && currentIndex.row==rowIndex && currentIndex.col == colIndex ?
<input
type="text"
style={{width: 90, height:40, backgroundColor:item.color }}
value={item.text}
readOnly={!( currentIndex && currentIndex.row === rowIndex && currentIndex.col === colIndex)}
onChange={(e)=>handleText(e.target.value,rowIndex,colIndex)}
/>
: `${item.text}`}
</div>
))}
</div>
))}
</div>
</div>
);
}
export default App;
This is my code and want to know what I am doing wrong
…am I setting the currentIndex state wrongly…
Currently when clicking on the cell , on the second or third time , then the input box become editable but , it should become editable on second click….
I have doubts that I have done some issue in setting currentIndex but unable to figure out what is wrong.
avinash sirohi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.