skip to Main Content

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


  1. Use useState hook to keep track of an item index.

    const [itemIndex, setItemIndex] = useState(null)
    
    {items.map((item, index) => {
      <div key={index}>
        {item.something}
        {itemIndex === index && <input />}
        <button onclick={()=> setItemIndex(index)}>
          Rename
        </button>
      </div>
    })}
    

    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.

    Login or Signup to reply.
  2. 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.

    const [activeInputIndex, setActiveInputIndex] = useState(null);
    

    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.

     const handleRenameClick = (index) => {
        setActiveInputIndex(index);
      };
    

    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.

    <div>
          {stuffforlist.map((stuff, index) => (
            <div key={index}>
              {activeInputIndex === index ? (
                <input
                  type="text"
                  value={stuff.something}
                  onChange={(e) => {
                    // Handle changes in the input field if needed
                  }}
                />
              ) : (
                <div>
                  {stuff.something}
                  <button onClick={() => handleRenameClick(index)}>Rename</button>
                </div>
              )}
            </div>
          ))}
        </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search