AhmedYahya24 / spzceX

0 stars 1 forks source link

Mapping in React #7

Open NouraldinS opened 2 years ago

NouraldinS commented 2 years ago

Ideally, you should never hard code any options or lists, everything should be used as an object of configuration being passed to a component. A few examples:

<Route path="/" element={<Home />} />
<Route path="/lunches" element={<Lanches />} />
<Route path="/missions" element={<Missions />} />

Should be:


const routes = [
  { path: '/', component: Home },
  { path: '/launches', component: Launches },
  { path: '/missions', component: Missions },
];

.
.
.

{
  routes
    .map(({path, component: Component}) => <Route path={path} element={<Component />})
}

Another example, instead of:

<ul>
  <li>Payload id: {cardDetails.payloads[0].id}</li>
  <li>Payload cutomers:</li>
  <li>Payload mass: {cardDetails.payloads[0].payload_mass_kg}</li>
  <li>Payload type: {cardDetails.payloads[0].payload_type}</li>
  <li>
    Reused: {cardDetails.payloads[0].reused ? "true" : "false"}
  </li>
  <li>Orbit: {cardDetails.payloads[0].orbit}</li>
  <li>Nationality: {cardDetails.payloads[0].nationality}</li>
  <li>Manufacture: {cardDetails.payloads[0].manufacturer}</li>
</ul>

You can do:

const fields = (cardDetails) => {
  const [mission] = cardDetails.payloads;

  return [
    { label: 'Payload id', value: mission.id },
    { label: 'Payload customers' },
    { label: 'Payload mass', value: mission.payload_mass_kg },
    .
    .
    .
  ]
}

const payloadList = useMemo(() => fields(cardDetails), [cardDetails]);

.
.
.
<ul>
  {
    payloadList.map(({label, value}) => (<li>{label}: {value}</li>))
  }
</ul>

There are many instances of this across your application, the benefit of configurable structures is the ease of maintenance and modification. Always imagine that this behavior is used across the application, and one day you needed to make a small modification to every one of these instances, this will take hours if not days when it should've taken seconds.