KT-mongo
KT-mongo

Reputation: 2212

How to add a scroll bar to a component in React?

I'm using a grid system with 3 columns in my SPA. The left and right list contain components that occupy 100 of the viewport height. The middle column contains a long list and would like to add a scrollbar just to the middle component. I've tried to wraw the middle component with several different scrollbar components but nothing works. I end up always with a main page scroll which leaves me only with the list component when scroll further down and left and right component are remaining remain to the top of the page.

Upvotes: 18

Views: 111503

Answers (2)

KT-mongo
KT-mongo

Reputation: 2212

Found the solution, need to set fixed height to left and right component and overflow:scroll to middle component.

Upvotes: 1

inaumov17
inaumov17

Reputation: 1339

Try adding overflow-y: scroll; on the middle component

const items = [...Array(100)].map((val, i) => `Item ${i}`);

const App = () => (
  <div className="container">
    <div className="left-col">
      Left col
    </div>
    
    <div className="center-col">
      <span>List</span>
      <ul>
        {items.map((item, i) => (<li key={`item_${i}`}>{ item }</li>))}
      </ul>
    </div>
    
    <div className="right-col">
      Right col
    </div>
  </div>
);

ReactDOM.render(<App />, document.getElementById('react'));
.container {
  display: flex;
  flex-direction: row;
  height: 100vh;
}

.left-col {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #ddd;
}

.center-col {
  flex: 1;
  background: #aaa;
  overflow-y: scroll;
}

.right-col {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #e7e7e7;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="react"></div>

Upvotes: 43

Related Questions