More NBA Ideas

Tonight is another game of the 2019 NBA finals. It is still a do or die game for the Golden State Warriors and one game away from winning for the Toronto Raptors. Without bias I think that the…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




How to create a masonry layout component using React.

Masonry layout

The component we’re going to create is going to be a functional component.

Our component will have some props — columns (number of columns in the masonry layout), gap(space between items) and children. We shall have to do some computations with column and gap, so their types will be number.

Let’s define the propTypes for the component and their default values as shown below.

The children prop will be an array of elements that will be defined between the start (<MasonryLayout>)and end (</MasonryLayout>) tag of our component. We are going to use this prop to access the items that our layout component will render.

We need to dynamically create arrays that will contain items in each column. Inside the MasonryLayout function, let’s create and declare some variables.

The columnWrapper object will enable us to dynamically create arrays that we can use as “buckets” for holding items in each column. The result array will contain column (jsx) elements. This is what shall be returned by the component.

Create the columns as shown below.

Divide the children into columns as shown below.

In the code above, were wrapping the child element with a div before pushing in the column. This enables us to add space between items in the column using bottom margin.

The next step will be wrapping the items in each column with a div and pushing it into the result array as shown below.

We need space between the columns, so adding a left margin on all columns other than the first does the trick. The columns will be rendered in a flex container hence the flex: 1.

Let’s wrap the result in a flex container and return it.

Let’s render 12 div elements each with a random height between 200px and 500px.

Congrats, we’re done creating a reusable masonry layout component. If you have any questions, engage me in the comments.

Add a comment

Related posts:

NBA Final 2019 Toronto Raptors vs Golden State Warriors Data Visualized

The Toronto Raptors are in the the NBA playoffs for the first time. Clinching their spot after a Game 6 win over the Milwaukee Bucks in the Eastern Conference finals. Meanwhile, the Golden State…

Love is the Only Law

The church bells are ringing a tune I can’t place but the one I was singing is rudely replaced by their clangorous noise I start to enjoy it only when I hum a drone underneath that ties it together…

Voice of a Depressed. Voice of a Self Medicating Jerk. Voice of Struggle. Voice of hope.

A clean wound would be best. Down by the stream, when I fall most if not all of my mess will be washed away. Only an entry and possibly an exit wound, despite my training I am unsure if a hollow…