Categories
React Answers

How to make a scrollable div to stick to bottom, when outer div changes in size in React?

Spread the love

Sometimes, we want to make a scrollable div to stick to bottom, when outer div changes in size in React.

In this article, we’ll look at how to make a scrollable div to stick to bottom, when outer div changes in size in React.

How to make a scrollable div to stick to bottom, when outer div changes in size in React?

To make a scrollable div to stick to bottom, when outer div changes in size in React, we can use flexbox.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        height: "300px"
      }}
    >
      <div style={{ flexGrow: 0 }}>foo</div>
      <div
        style={{
          flexGrow: 1,
          overflowY: "auto",
          alignItems: "center",
          display: "flex"
        }}
      >
        bar
      </div>
      <div style={{ flexGrow: 0 }}>baz</div>
      <div></div>
    </div>
  );
}

We make a flex container by setting the display CSS property to 'flex', flexDirection to 'column' and a height for the flex container.

Then we add the elements inside the flex container.

We make the bottom div stick to bottom by setting flexGrow of the div above the bottom one to 1 to make it fill the space.

And we set flexGrow of the bottom div to 0 so that it won’t stretch.

Conclusion

To make a scrollable div to stick to bottom, when outer div changes in size in React, we can use flexbox.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *