React - how to add scrollbar to the component
In this article we would like to show you how to add scrollbar to the component in React.
Below examples describe three situations:
- When we want to add scrollbar in any direction the content overflows our component's block,
- When the content overflows only at the top and bottom edges (horizontal scrollbar),
- When the content overflows only at the left and right edges (vertical scrollbar).
Check below examples
1. Scrollbar in both directions
In this solution we set overflow value to 'scroll' which allows us to scroll both in X and Y axis.
Runnable example:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const myComponent = {
width: '100px',
height: '100px',
overflow: 'scroll'
};
const MyComponent = () => {
return (
<div style={{ height: '200px' }}>
<div style={myComponent}>
<ul>
<li>List_item_1</li>
<li>List_item_2</li>
<li>List_item_3</li>
<li>List_item_4</li>
<li>List_item_5</li>
</ul>
</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<MyComponent />, root );
2. Horizontal scrollbar (overflowX)
In this solution we set overflowX:
value to 'scroll'
which allows us to scroll along the X axis and overflowY:
value to 'hidden'
which hides vertical scrollbar.
Runnable example:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const myComponent = {
width: '100px',
height: '100px',
overflowX: 'scroll',
overflowY: 'hidden'
};
const MyComponent = () => {
return (
<div style={{ height: '200px' }}>
<div style={myComponent}>
<ul>
<li>List_item_1</li>
<li>List_item_2</li>
<li>List_item_3</li>
<li>List_item_4</li>
<li>List_item_5</li>
</ul>
</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<MyComponent />, root );
Note:
When you don't specifyoverflowY:
value, it will be initialized with'auto'
. (Read more here)
3. Vertical scrollbar (overflowY)
In this solution we set overflowY:
value to 'scroll'
which allows us to scroll along the Y axis and overflowX:
value to 'hidden'
which hides horizontal scrollbar.
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const myComponent = {
width: '100px',
height: '100px',
overflowX: 'hidden',
overflowY: 'scroll'
};
const MyComponent = () => {
return (
<div style={{ height: '200px' }}>
<div style={myComponent}>
<ul>
<li>List_item_1</li>
<li>List_item_2</li>
<li>List_item_3</li>
<li>List_item_4</li>
<li>List_item_5</li>
</ul>
</div>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<MyComponent />, root );
Note:
When you don't specifyoverflowX:
value, it will be initialized with'auto'
. (Read more here)