Home > Net >  Suggestion to refactor code into simple way -React
Suggestion to refactor code into simple way -React

Time:06-28

I have multiple with the same class name and method with different parameter i want to refactor the below code to a simpler way any suggestion would be helpful.

<table >
  <tbody>
    <tr>
      <td>AA</td>
      <td className = 'table-container'>{formatDate(someMethod1(param1,a)}</td>
    </tr>
    <tr>
      <td>BB</td>
      <td className = 'table-container'>{formatDate(someMethod1(param1,b)}</td>
    </tr>
    <tr>
      <td>CC</td>
      <td className = 'table-container'>{formatDate(someMethod1(param1,c)}</td>
    </tr>
  </tbody>
</table>

I want to refactor the code with the same component.

CodePudding user response:

Try to use an array instead. Having reusable components in an array is easy to maintain, expand and read. Definitely a good practice.

let tableItems = [{name:"AA",date:new Date()},.....]

return (

<table >
  <tbody>
    {tableItems.map((item,index)=>{
     return(
       <tr>
         <td>{item.date}</td>
         <td className = 'table-container'>{item.date}</td>
       </tr>
     )
    })}
  </tbody>
</table>

)

CodePudding user response:

I hope this would be helpful. thanks

export const TableItems = ({data}) => {
  return (
    <>
      {data.map(d => (
        <tr>
          <td>{d.name}</td>
          <td className ={d.className}>{formatDate(someMethod1(param1,a)}</td>
        </tr>
      ))}
    </>
  )
}


const data = [
  {
    name: AA,
    className: 'table-container',
  },
  {
    name: BB,
    className: 'table-container',
  },
  {
    name: CC,
    className: 'table-container',
  }
]

<table >
  <tbody>
    <TableItems data={data} />
  </tbody>
</table>
  • Related