简体   繁体   中英

React create Bootstrap grid of unknown size

I'm building an app in which I need to use React to render a Bootstrap grid. I'm a React newb so please bear with me.

Frontend will receive N objects that need to be displayed in Boostrap columns, each in his own column. The problem is, I don't know how large is N so I don't know how many rows do I need.

Any ideas how to approach this?

Should I have just one component? Or three (Container, Row, Column)? Or something else?

First of all, consider if you even need custom components for Container, Row and Column. You can just use a div with the appropriate css class, I don't see that much value in wrapping this into a custom component. If you do decide to use a custom component, you may want to look at react-bootstrap , they already implemented these.

As for the layout, I believe you can place as many columns as you want in a row in Bootstrap layout and they will wrap as necessary (if there's more than 12), so it might be easiest to just have one row and put all the columns inside it (see Bootstrap docs ).

There are different ways to approach this problem depending on the type of content that you are trying to insert into the grid.

First off, as far as columns go, Bootstrap uses a 12 column grid system. This will make your life a bit easier because you can divide 12 by the number of elements in each row. If your html is set up correctly you can use:

var numOfElements = document.getElementById('objectsWrapper').children.length;

If you're using images you may want to set a strict max-height and max-width (percentages) to restrict the images generated from messing up the grid.

Next, when the column exceeds 12 elements, you'll want to start a new .row if necessary. Create a new div, append it to your current container and set it as the currentDiv you want to add your children to.This step is important because your code needs to know which 'objectsWrapper' it's querying for children.

Wash. Rinse. Repeat.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM