简体   繁体   中英

How can I match data from an object and pass it as props to another component that displays dynamically?

I am storing my data in JS array. After that I am using map function to display components with specific data. Until then, everything works. After I click component I want to display a PopUp component that display more specific data from the data.js file. How can I pass it as props and match correct data to correct component? At this moment after I click it always shows me the same text.

My data.js file:

export const data = {
  projects: [
    {
      name: "Project1",
      image: require("../assets/img/Project1.PNG"),
      description: "Set number 1",
      technologies: "REACT",
      link: "github.com",
    },
    {
      name: "Project2",
      image: require("../assets/img/Project2.PNG"),
      description: "Project number 2 - description",
      technologies: "C#",
      link: "github.com",
    },

This is my PopUp.js that should display more specific data:

function Popup({ project, description }) {
  return (
    <Wrapper>
      <p>Project name is: {project}</p>
      <p>Description is: {description}</p>
    </Wrapper>
  );
}

And here I map my data and here is the problem. How can I pass it?

function Projects() {
  const [isOpen, setIsOpen] = useState(false);

  const togglePopup = () => {
    setIsOpen(!isOpen);
  };

  return (
    <Wrapper>
      {data.projects.map((proj) => (
        <ProjectContainer background={proj.image} onClick={togglePopup}>
          {isOpen && (
            <Popup project={proj.name} description={proj.description} />
          )}
        </ProjectContainer>
      ))}
    </Wrapper>
  );
}

Really thanks for all of the answers!

You can use index instead of boolean :

function Projects() {
  const [isOpen, setIsOpen] = useState('nothing');

  return (
    <Wrapper>
      {data.projects.map((proj, index) => (
        <ProjectContainer background={proj.image} 
          onClick={()=>setIsOpen(oldIndex => index === isOpen ? 'nothing' : index)}>
          {isOpen === index && (
            <Popup project={proj.name} description={proj.description} />
          )}
        </ProjectContainer>
      ))}
    </Wrapper>
  );
}

The state stores the index of the current opened popup.

ProjectContainer onClick event check if the current index is the same as their and changes accordingly : to 'nothing' if they are currently opened, to their index if they are not.

The condition {isOpen === index && ( is used to show only the current opened popup ie the current index.

This way you can toggle an individual project and not all of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM