I need a single input to render for items in a mapped list when I press a button.
so if we have a list and you press the button rename,
then an input will show up only for that list item.
im using reactjs
what is the usually methods for this please?
const stuffforlist = {stuff}
return(
{stuffforlist.map(stuff => {
<div>
{stuff.something}
<button onclick={}>
</button>
</div>
})}
)
how can that button onclick render an input field on that same div only for that one map item?
2
Answers
Use useState hook to keep track of an item index.
Based on the
itemIndex === index
check, the input field will be displayed.After submitting the input, set
itemIndex
back to null to hide the input field.Ideally, instead of the index, you would use something like item.id if available. But should be fine to use index for a static list.
You’ll need to use state to keep track of whether the input should be shown or hidden for each item in the list.
The steps according to me are-
1>Create a state variable to store the index of the item for which the input field should be shown. Initially, this state should be set to ‘null’ to indicate that no input field is active inside your component.
2> Handle the "rename" button click. When the "rename" button is clicked, you’ll need to update the state to indicate which item should show the input field.
3> Render the list with input fields conditionally. Inside your
map
function, you can check if the current index matches the your state variable -> activeInputIndex, and if it does, render an input field for that item; otherwise, render the regular content.