Estou com problemas em manter as imagens na posição correta. Tenho uma lista de imagens, mas quando eu clico no filtro para inverter a ordem, algumas imagens mantém a sua posição.
Para melhor entendimento eu fiz um exemplo bem limpo e fácil de compreender que simula um problema parecido:
const api = [
{
name: "Elephant",
url:
"https://i.pinimg.com/originals/1e/06/e1/1e06e107f0ca520aed316957b685ef5c.jpg"
},
{
name: "Wallpaper Windoes",
url: "https://img.ibxk.com.br/2015/07/23/23170425700729.jpg?w=328"
},
{ name: "No image", url: "" },
{ name: "Tiger", url: "https://www.htmlecsspro.com/exemple/img/imagem.jpg" },
{
name: "Lion",
url:
"https://blogmedia.evbstatic.com/wp-content/uploads/wpmulti/sites/18/2014/07/24025147/6BaVde_t20_VKbpQ7-e1527130375674.jpg"
},
{ name: "No image 2", url: "" },
{
name: "Google",
url:
"https://tecnoblog.net/wp-content/uploads/2020/03/google-imagens-700x394.jpg"
}
];
function App() {
const [itemsList, setItemsList] = React.useState([]);
const [isInverted, setIsInverted] = React.useState(false);
function reverseAction() {
setIsInverted(isInverted ? false : true);
setItemsList(api.reverse());
}
React.useEffect(() => {
setItemsList(api);
}, []);
return (
<div>
<button onClick={reverseAction}>Reverse</button>
<p>{isInverted ? "true" : "false"}</p>
{itemsList.map((item, index) => (
<Cards key={index} item={item} />
))}
</div>
);
}
const IMG_DEFAULT = 'https://www.luzeoliveira.com.br/index/wp-content/uploads/2017/07/default.png';
function Cards({ item }) {
const [img, setImg] = React.useState(IMG_DEFAULT);
//Os itens tem uma imagem padrão, mas a imagem é alterada se o item tiver sua propria imagem
React.useEffect(() => {
if (item.url.length > 1) {
setImg(item.url);
}
}, []);
//se ocorrer erro ao carregar a imagem do item, então volta para a imagem padrão
function onErrorImg() {
setImg(IMG_DEFAULT);
}
return (
<div>
<p>{item.name}</p>
<img style={{height: 200 }} src={img} alt="img" onError={onErrorImg} />
</div>
);
}
ReactDOM.render(<App /> , document.querySelector("#app"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="app"></div>