V R
V R

Reputation: 143

React table row delete does not remove the TextInput

I am getting a book list from database and is stored in a state variable Book list also has book price field

const [books, setBooks]=useState([])
setBooks(data)

I am creating an html in a loop based on the above books data

return ( <div>
{books.map((x,i) => ( <tr>
                         <td>x.bookName</td>
                         <td><MyCustomTextInput value={x.price}></MyCustomTextInput></td>
                      <tr></div>);

MyCustomTextInput looks like as follows

function MyCustomTextInput(props)
     { return (<div>><TextInput></TextInput> </div>) 
     } exports default MyCustomTextInput

I have a button after clicked, it adds a new book entry in the array which also displays a new row in the table

When I remove an item from an array, the table also removes the row which is correct and expected

BUT lets say there are 5 rows in the table. Row ID 4 has Text Input value say $23.32 and Row ID 5 has Text Input Value as $30.00 then after the row 4 is deleted, price from the row 4 which was before delete $23.32 stays as it is even after row 5 is now row 4 and I am expecting to see price $30.00 (row 5 is now moved to row 4 place after delete)

This issue is only with the Text Input and another field book name in the table gets changed properly

Experts any suggestions .....

Upvotes: 0

Views: 619

Answers (2)

Ahmed Nasr
Ahmed Nasr

Reputation: 419

When using lists React expects a "key" prop so that when an a child e.g. a book is deleted it knows which one was deleted

I am having a hard time following your code but your books should like this in the list:

<tr key={book.id}>
    <td>whatever</td>
</tr>

now when the tr with the key of {some id} at index 4 for example is deleted react will update the list correctly

Upvotes: 1

Chuck
Chuck

Reputation: 804

I think you should make clear about your problem. Lots of typo errors make it difficult to understand your real problem.

The only thing I can guess now is that it can be related to map function

books.map((x,i) => ( <tr key={x.id}> ... </tr>)

You should add key attribute to tr element to tell react which one is newly created.

And I am not sure about this one.

function MyCustomTextInput(props)
     { return (<div>><MyCustomTextInput></MyCustomTextInput> </div>) 
     } exports default MyCustomTextInput

You are rendering MyCustomTextInput in a MyCustomTextInput component?

Upvotes: 2

Related Questions