Reputation: 936
I created a table with formulas and I wanted from each cell to show the results of the formula when onBlur
and to show the formula itself when onFocus
.
25
will be affected as well, despite I want the cell 25
or"=age+3"
to be effected only when clicking it precisely (focus on it
)import React, { useState } from "react";
import "./styles.css";
const table = [
{ id: 1, row: ["name", "age", "email",'formula'] },
{ id: 2, row: ["Ali", 23, "[email protected]", "=age+3"] },
{ id: 3, row: ["alex", 22, "[email protected]",'22'] }
];
export default function App() {
const [focused, setFocused] = useState(false);
const age = table[2].row[1];
return (
<table className="App">
{table.map((item, index) => (
<tr key={index}>
{item.row.map((cell, index) => {
return (
<td
onFocus={(e) => setFocused(true)}
onBlur={(e) => setFocused(false)}
contentEditable
key={index}
>
{cell[0] === "=" & !focused ? eval(cell.slice(1)) : cell}
</td>
);
})}
</tr>
))}
</table>
);
}
Upvotes: 0
Views: 492
Reputation: 936
SOLVED
=
then I convert innerText to text
=
then I convert innterText to eval
onFocus={(e) => cell[0] === "=" && (e.target.innerHTML = cell)}
onBlur={(e) =>
cell[0] === "=" && (e.target.innerHTML = eval(cell.slice(1)))
}
Upvotes: 0
Reputation: 1343
You will have to keep track of the row that has focused and do a comparison. Here is my attempt at this. I have changed the index for the table.map
to be rowIndex
and in your conditional render, I check if focused
is set and if it equals to the rowIndex
.
OnFocus function sets the focus
to the correct row index and onBlur sets it to null
https://codesandbox.io/s/xenodochial-carson-2xy4x?file=/src/App.js
Upvotes: 1