Home > Net >  How to use the key (defined from lists items key) as prop on my Modal
How to use the key (defined from lists items key) as prop on my Modal

Time:10-19

I have defined the Key in my code key={item.id} when mapping through reposit list and I am trying to use it as a prop in my here {openModal && <Modal repo={reposit} my_key={key} setOpenModal={setOpenModal}/> } but it doesn't seems to work. Someone can explain to me how can I access to the key on my Modal by using it as a prop ?

Here is the part of the code :

      <List.Item>
              <List.Content>            
                    
                    {reposit.map((item) => (  
                      <li key={item.id} onClick={() => {setOpenModal(true)}}>
                          <i className="folder icon" /> {item.name}
                      </li>
                      ))}
                    
                  {openModal && <Modal repo={reposit} my_key={key} setOpenModal={setOpenModal}/> } 
              </List.Content>
     </List.Item>   

Thank you for your help.

CodePudding user response:

You have to use state to keep track the key for the clicked list item like below:

import React, { useState } from "react";

const App = () => {
  const [myKey, setMyKey] = useState();

  return (
    <List.Item>
      <List.Content>
        {reposit.map((item) => (
          <li
            key={item.id}
            onClick={() => {
              setMyKey(item.id);
              setOpenModal(true);
            }}
          >
            <i className="folder icon" /> {item.name}
          </li>
        ))}

        {openModal && (
          <Modal repo={reposit} myKey={myKey} setOpenModal={setOpenModal} />
        )}
      </List.Content>
    </List.Item>
  );
};

CodePudding user response:

The li key attribute is only defined within the li element, it is not accessible outside of it. Your modal is not a child of the li element so it can't be accessed in the way you are trying. You have to pass item.id to the modal through the li onClick function. One way would be to create state to keep track of what key should be passed to the modal, and change it within the onclick function.

const [modalKey, setModalKey] = useState()

const openModal = (key) => {
  setModalKey(key)
  setOpenModal(true)
}

...

<List.Item>
        <List.Content>            
                    
                    {reposit.map((item) => (  
                      <li key={item.id} onClick={() => openModal(item.id)}>
                          <i className="folder icon" /> {item.name}
                      </li>
                      ))}
                    
                  {openModal && <Modal repo={reposit} my_key={modalKey} setOpenModal={setOpenModal}/> } 
        </List.Content>
</List.Item>   
  • Related