Reputation: 362
I have a scrollbar in a div element with height
and overflow
css, I want the div to start from a bottom. I did that in javascript JSfiddle
var objDiv = document.getElementById("scrolldiv");
objDiv.scrollTop = objDiv.scrollHeight;
#scrolldiv{
width:115px;
height:100px;
overflow:auto;
border: 2px black solid;
}
<div id="scrolldiv">
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
<li>Instagram</li>
</ul>
</div>
How to apply my javascript code in reactjs?
class ShoppingList extends React.Component {
constructor(props){
super(props);
this.state = {
pageNumber: 1
}
}
render() {
return (
<div className="shopping-list" id="scrolldiv">
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
</ul>
</div>
);
}
}
Upvotes: 0
Views: 1716
Reputation: 2664
By using React Refs to get hold of the element:
class ShoppingList extends React.Component {
constructor(props){
super(props);
this.state = {
pageNumber: 1
}
}
componentDidMount() {
let shoppingListContainer = document.getElementById("scrolldiv");
shoppingListContainer.scrollTop = shoppingListContainer.scrollHeight;
}
render() {
return (
<div className="shopping-list" id="scrolldiv">
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
</ul>
</div>
);
}
}
Well, Mui Dialog component doesn't appear to have a hook to run function when dialog is shown, however you can move the scrollposition logic into handleOpen
method, like below:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
}
}
handleOpen = () => {
this.setState({ open: true });
// hack
setTimeout(() => {
let shoppingListContainer = document.getElementById("scrolldiv");
if (shoppingListContainer !== null) {
shoppingListContainer.scrollTop = shoppingListContainer.scrollHeight;
}
}, 100);
};
handleClose = () => {
this.setState({ open: false });
};
render() {
return (
<MuiThemeProvider>
<div>
<RaisedButton label="Alert" onClick={this.handleOpen} />
<Dialog
title="Dialog With Actions"
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}
>
<div className="shopping-list" id="scrolldiv"
style={{
width: 125,
height: 100,
overflow: 'auto',
border: '2px black solid'
}}>
<ul>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
<li>Instagram</li>
<li>WhatsApp</li>
<li>Oculus</li>
</ul>
</div>
</Dialog>
</div>
</MuiThemeProvider>
);
}
}
render(<App />, document.getElementById('root'));
Upvotes: 2