I am using react-bootstrap
components. I have a table
covered by a div
. The table has six rows. I have added height
to my div, but table
is not sized according to height
.
I need the table to fit inside the div, and the table header should be fixed and table body content should scroll.
UI Looks like this below
It overflows in the div. I tried applying height and scroll. But it's not working.
Here's the Code I tried:
import Table from "react-bootstrap/Table";
import "bootstrap/dist/css/bootstrap.min.css";
export default function App() {
return (
<div style={{ height: "200px", backgroundColor: "aqua" }}>
<Table striped bordered>
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody style={{ overflow:"scroll" }}>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>4</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>5</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>6</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
</tbody>
</Table>
</div>
);
}
I don't know how to make it. Please help me with some solutions.
Code SandBox Link: https://codesandbox.io/s/agitated-hamilton-qh1eh5?file=/src/App.js
Based on the current CSS you have given, it should be fixed by placing an overflow-y: scroll
to your container div
. Since the styling is done as inline javascript, you must write it as overflowY: "scroll"
.
EDIT: Since the actual question was about getting it fixed, you need to add position: sticky
and top:0
to the table header (and background color, otherwise it's transparent), and the previous overflowY: scroll
should be overflowY: auto
instead. Here is the result for that:
import "./styles.css";
import Table from "react-bootstrap/Table";
import "bootstrap/dist/css/bootstrap.min.css";
export default function App() {
return (
<div
style={{
overflowY: "auto",
height: "200px",
backgroundColor: "green"
}}
>
<Table striped bordered>
<thead style={{ position: "sticky", top: 0, background: "green" }}>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody
style={{
overflowY: "scroll",
// height: "200px",
backgroundColor: "aqua"
}}
>
<tr>
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>2</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>3</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>4</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<td>5</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<td>6</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
</tbody>
</Table>
</div>
);
}