I'm building a React table component with rows and columns. Naturally, I want the rows to be distributed vertically and the numbers within the rows to be distributed horizontally.
Right now, it looks like this:
But when I wrap each number in a simple Cell
component, I end up with this:
React Code:
function Cell({ number }) {
return (
<div>
{number}
</div>
)
}
function Row({ row }) {
// problem when data point is wrapped in Cell
const mapped = row.map((datapoint, index) => {
return <li className="horizontalList" key={index.toString()}><Cell number={datapoint}/></li>
})
// uncomment this and comment out the other one to see how it should look
// const mapped = row.map((datapoint, index) => {
// return <li className="horizontalList" key={index.toString()}>{datapoint}</li>
// })
return (
<div className="row">
<ul>
{mapped}
</ul>
</div>
)
}
function App() {
const data = [
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
]
const mapped = data.map((row, index) => {
return <li className="verticalList" key={index.toString()}><Row row={row}/></li>
})
return (
<div className="App">
<div className="container">
<ul>
{mapped}
</ul>
</div>
</div>
);
}
CSS:
.container {
display: flex;
flex-direction: column;
align-items: center;
}
.horizontalList {
display: inline;
padding: 10px;
}
.verticalList {
padding: 10px;
}
CodePudding user response:
Inline elements (e.g. <span>
) normally display inline beside eaah other. However, when you insert a block element (e.g. <div>
) inside like:
<span>
<div></div>
</span>
That div
keeps taking the full width and ignores the boundaries of its parent span
.
And that's exactly what happens when you wrap the number, which is inline by your styles, inside a <Cell />
, as it's just a div
.
Run this code snippet to check the difference:
<h4>Inline elements</h4>
<span>item</span>
<span>item</span>
<hr />
<h4>Block element inside inline elements</h4>
<span><div>item</div></span>
<span><div>item</div></span>
Solution:
Make the <Cell />
a span
instead of div
.