Is it possible for a component to have a map that changes the return according to the prop that was passed?

Asked

Viewed 21 times

-1

<tbody>
   {props.item.map((film) => (
     <tr>
       <td>{film.name}</td>
       <td>{film.mass}</td>
       <td>{film.height}</td>
       <td>{film.birth_year}</td>
      </tr>
     ))}
</tbody>

I would like to know if there was any way that part of td would be composed of other information. Like, if I make a request in another URL and return objects with other properties, it would be possible for this td to be dynamically without creating another component to receive this information.

1 answer

0


I don’t know if I understand your question very well. But it would be like this?

<tbody>
   {props.item.map((film) => (
     <tr>
       { Object.keys(film).map((chaveDeObj) => 
          (<td>{film[chaveDeObj]}</td>) }
      </tr>
     ))}
</tbody>

could also create an object <thead> using the chaveDeObj as value. This freeVoce swap the object film to anyone without knowing its contents. Of course this only works with simple objects, more than to modify to deal with more complex objects.

The right and have some kind of filter to not demonstrate values that are not necessary.

You can do something like this:

import React from 'react';

// props: { filtro: string[]; itens: any[] }
const genericTable = (props) => {
  const filtrosDeChaves = props.filtro; // ex.: ['nome', 'data']
  return (
    <>
      <thead>
        <tr>
          {filtrosDeChaves.map((chave) => (
            <td key={chave}>{chave}</td>
          ))}
        </tr>
      </thead>
      <tbody>
        {props.itens.map((
          item, // mudei o nome do obj para itens
          index // estou usando index para key mais o certo seria outro valor
        ) => (
          <tr key={index}>
            {Object.keys(item)
              .filter(
                // filtrar para valores desejados
                (chaveDoItem) => filtrosDeChaves.includes(chaveDoItem)
              )
              .map((chaveDoItem) => (
                <td key={chaveDoItem}>{item[chaveDoItem]}</td>
              ))}
          </tr>
        ))}
      </tbody>
    </>
  );
};
  • Got it, helped me a lot. Thanks a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.