I have array of object ImageKist where I would like to show alternate image with different heights using flexbox as shown below:
where images go from left to right. How can I achieve above pattern using flexbox.
Install styled-component: npm install --save styled-components
Code sandbox link: https://codesandbox.io/s/optimistic-curie-jesyz1?file=/src/App.tsx
CodePudding user response:
Update 2 (for glitz
)
It seems that the library mentioned in comments uses a syntax similar to styled-components
, I have made some changes to the code and it seems to work for me.
Forked demo with modifications: codesandbox
Example:
import "./styles.css";
import { styled } from "@glitz/react";
const imageList = [] as any;
for (let i = 1; i < 52; i ) {
imageList.push({
id: `${i}`,
url: `https://picsum.photos/500?random=${i}`
});
}
const Wrapper = styled.div({
display: "grid",
gridTemplateColumns: "repeat(3, 1fr)",
gridAutoRows: "80px",
gap: "30px",
gridAutoFlow: "row dense"
});
const ImageWrapper = styled.div({
overflow: "hidden",
position: "relative",
borderRadius: "20px",
gridRow: "span 2",
gridColumn: "auto",
":nth-of-type(even)": {
gridRow: "span 3"
},
":nth-of-type(6n 5)": {
gridColumn: "2"
}
});
const ImageStyled = styled.img({
width: "100%",
height: "100%",
objectFit: "cover"
});
export default function App() {
return (
<Wrapper>
{imageList.map((image: any) => (
<ImageWrapper key={image.id}>
<ImageStyled src={image.url} alt={image.url} />
<h4 style={{ position: "absolute", top: "16px", color: "white" }}>
{image.id}
</h4>
</ImageWrapper>
))}
</Wrapper>
);
}
Update 1 (for styled-components
)
I updated the answer to omit the use of index
as a prop to create the layout, instead uses :nth-of-type
pseudo-class to alter the styles, so this is now kind of a all CSS solution.
It still uses grid
layout, but hopefully it could help.
Live demo on: stackblitz
Example:
import React from 'react';
import './style.css';
import styled from 'styled-components';
// Test data
const imageList = [];
for (let i = 1; i < 52; i ) {
imageList.push({
id: `${i}`,
url: `https://picsum.photos/500?random=${i}`,
});
}
// Styled components
const Wrapper = styled.div`
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-rows: 80px;
gap: 30px;
grid-auto-flow: row dense;
& > div {
grid-row: span 2;
grid-column: auto;
}
& > div:nth-of-type(even) {
grid-row: span 3;
}
& > div:nth-of-type(6n 5) {
grid-column: 2;
}
`;
const ImageWrapper = styled.div`
overflow: hidden;
position: relative;
border-radius: 20px;
`;
const ImageStyled = styled.img`
width: 100%;
height: 100%;
object-fit: cover;
`;
const H4Styled = styled.h4`
position: absolute;
top: 16px;
color: white;
`;
export default function App() {
return (
<div>
<Wrapper>
{imageList.map((image, index) => (
<ImageWrapper key={image.id} index={index}>
<ImageStyled src={image.url} alt={image.url} />
<H4Styled>{image.id}</H4Styled>
</ImageWrapper>
))}
</Wrapper>
</div>
);
}