Reputation: 333
I have a component in react which i, iterating in a loop. This component will always be shown three times and I want them to show in one single row (each component a column). The examples I have seen manually adds "flex:1;" and so on for every column, but since im iterating its not possible.
It looks like this:
<div className="styles.grid">
<!-- stuff -->
</div>
Above is going to be shown three times, and want them all in one single row (each going to be a column).
I have tried:
.grid {
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: center;
}
Does not work. Any help?
Upvotes: 3
Views: 1898
Reputation: 1050
This is what you're probably trying to achieve:
.grid {
display: flex;
flex-wrap: wrap;
align-items: space-between;
}
.grid-item {
width: 30%;
}
<div class="grid">
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
<div class="grid-item">Item content</div>
</div>
Flex container will wrap every item, once it goes outside of its bounds with flex-wrap: wrap;
property.
And every item inside the flex should then be set to width: 30%;
. Every 4th item in grid will be wrapped to the next row.
Upvotes: 0
Reputation: 112777
You can remove the flex-wrap
to let all the flex items be on the same row, and give each flex item a third of the width.
Example
function App() {
return (
<div className="grid">
<div className="grid-item item-1">Foo</div>
<div className="grid-item item-2">Bar</div>
<div className="grid-item item-3">Baz</div>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
.grid {
display: flex;
}
.grid-item {
width: 33.33333%;
height: 200px;
}
.item-1 {
background-color: red;
}
.item-2 {
background-color: green;
}
.item-3 {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1
Reputation: 404
Try using flex-grow: 1
on the children columns. This tells the children to grow equally to fill their parents width.
For more info on flexbox: https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Below is a simple 3 column example, where each column expands equally.
.parent {
width: 100%;
height: 200px;
display: flex;
flex-direction: row;
justify-content: space-between;
}
.col {
flex-grow: 1;
height: 200px;
border: 1px solid black;
}
<div class="parent">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
</div>
Upvotes: 1