First value in a map function in javascript

Asked

Viewed 116 times

0

I have a function map Javascript where I return all the photos of a certain record. Among these photos, one of them has to receive a text, which in my case is Main photo, which will always be the first element of the array. The question is that the text always goes to all images, and I have no idea how to put the text only in the first photo.

Below is the code in question.

<ul>
  {fotoApi?.fotos?.map((foto, index) => (
    <li key={index} style={{ listStyle: "none" }}>
      <img
        style={cssListImg}
        src={fotoApi.fotos[index]}
        onClick={() => {
          setFile(fotoApi.fotos[index]);
          setImg(null);
          setI(index);
          setImgSel(foto);
        }}
      />
      <br />
      {/* fotoApi.fotos[0] ? <>Foto principal</> : <>""</> */}
      {/* A linha acima é o que eu tentei, mas sem sucesso */}
    </li>
  ))}
</ul>

As requested by @Virgilionovic, my "photos" are created as follows:

const [fotoApi, setFotoApi] = useState({fotos: [], caminhoimagem: ""}];
  • first you have to do outside the map! and then make a slice to skip the first image!

  • has other errors as well, case your example of the object photos?

  • You can put a if (index !== 0) return dentro desse onClick`... but @Virgilionovic’s suggestion is more accurate. Question: all images are clickable?

  • @Sergio, yes, they all are, and should be clickable

  • @Virgilionovic I’ll try what you sent here ;)

1 answer

2


From what I can understand, if you want to print the first item in one way and the others in another way an example of a very simple code is:

function App() {
  const [tarefas, setTarefas] = React.useState([
    {'id': 1, 'desc': 'Tarefa 1'},
    {'id': 2, 'desc': 'Tarefa 2'},
    {'id': 3, 'desc': 'Tarefa 3'},
    {'id': 4, 'desc': 'Tarefa 4'},
    {'id': 5, 'desc': 'Tarefa 5'},
  ]);
  return (
    <ul>
      {tarefas.length && (<li key={tarefas[0].id}>{tarefas[0].desc}</li>)}
      {tarefas.slice(1).map((t, i) => <li key={i}>{t.id}</li>)}
    </ul>
  )
}
ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

where that line:

{tarefas.length && (<li key={tarefas[0].id}>{tarefas[0].desc}</li>)}

picks up the first landing of array and the next:

{tarefas.slice(1).map((t, i) => <li key={i}>{t.id}</li>)}

with slice and map take the rest, I believe that’s your question!

{tarefas.slice(1).map((t, i) => <li key={i}>{t.id}</li>)}

the documentation Slice.

Browser other questions tagged

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