Search code examples
javascriptreactjscomponentsreusability

How to easily add reusable component into a list?


I am using React to build a portfolio website that will list all of my projects and future projects. I was wondering if this was the correct approach to easily adding new project entries to my website. My idea is that I have a reusable component that takes in an object prop

export default function ProjectEntry({projectInformationProp}){
    <div>{projectInformationProp.name}</div>
    <div>{projectInformationProp.stack}</div>
    <div>{projectInformationProp.description}</div>
    <div>{projectInformationProp.github}</div>
}

and each time I wanted to add in a new entry I would put a new "ProjectEntry" into this project list component. This component would take in a list of objects as a prop, each object holding information on a specific project.

export default function ProjectList({projectList}){
    <ul>
        <li>
            <ProjectList projectList[0]={projectInformationProp} />
        </li>
        <li>
            <ProjectList projectList[1]={projectInformationProp} />
        </li>
        <li>
            <ProjectList projectList[2]={projectInformationProp} />
        </li>
    </ul>
}

This would be the list of objects, so in the future if I wanted to add in my latest project I would just have to add in a new object with the new information.

let projectList=[
    {name:project1, stack:javascript, description:good, github:link},
    {name:project2, stack:python, description:bad, github:link},
    {name:project3, stack:C++, description:okay, github:link},
]

I think this would be a decent approach at using React's reusable component correct?


Solution

  • You need to iterate over the array with map to create a new array of components:

    export default function ProjectList({ projectList }){
      <ul>
        {projectList.map(obj => <ProjectEntry data={obj} />)
      </ul>
    }
    

    And then use the object data you pass in on each iteration to create the <ProjectEntry>:

    export default function ProjectEntry({ data }) {
      return (
        <li>
          <div>{data.name}</div>
          <div>{data.stack}</div>
          <div>{data.description}</div>
          <div>{data.github}</div>
        </li>
      );
    }