Ali Husham
Ali Husham

Reputation: 936

how to render useState values for only specific div (component)?

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.

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>
  );
}

on Codesandbox

Upvotes: 0

Views: 492

Answers (2)

Ali Husham
Ali Husham

Reputation: 936

SOLVED

  • when focus I check if the cell start with = then I convert innerText to text
  • when blur I check if the cell start with = 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)))
                }

CodeSandBox

Upvotes: 0

szczocik
szczocik

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

Related Questions