A
A
Alexander2021-06-20 15:12:54
React
Alexander, 2021-06-20 15:12:54

How to pass a value from one function to another in a functional component?

You need to delete a row from the table, but before deleting show a modal with a warning. How can the modal itself find out the ID of the table row being deleted?

const Component = ({ rows }) => {
      const [modalIsVisible, setModal] = false;

      const deleteRow = () => {
        // how to get id of row to delete here?
      }

      return (
        <div>
          <table>
            {rows.map(row => (
              <tr>
                <td>
                  <div>row of id {row.id}</div>
                  <button onClick={() => setModal(true)}>Delete row</button>
                </td>
              </tr>
            )}
          </table>
          <Modal isVisible={modalIsVisible}>
            <button onClick={deleteRow}>Delete anyway</button>
            <button onClick={() => setModal(false)}>Close</button>
          </Modal>
        </div>
      )
    }

I thought, of course, to create a separate state variable using useState, but I don’t like this approach, because The ID of the deleted line is purely system information that does not affect the display in any way and should not cause a rerender.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-06-20
@aleksand44

The ID of the deleted line is purely system information that does not affect the display in any way

Why, it can easily influence: Well, in general, useRef will help you :
const [ delId, setDelId ] = useState(null);
<button onClick={() => setDelId(row.id)}>Delete
<Modal isVisible={!!delId}>
<button onClick={() => setDelId(null)}>Close
The useRef() Hook isn't just for DOM refs. The “ref” object is a generic container whose currentproperty is mutable and can hold any value, similar to an instance property on a class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question