Reputation: 294
I'm new to reactjs. I'm good in javascript and jQuery, but dumb in ReactJS. I have this jQuery code and I need to make it work with reactjs. This function is supposed to auto-scroll the list vertically on a loop. But I don't have any idea how to do this in react.
function autoScroll(obj) {
$(obj).find("container").animate({
marginTop: "-28px"
}, 500, function () {
$(this).css({
marginTop: "0px"
}).find("li:first").appendTo(this);
});
}
$(function () {
setInterval('autoScroll(".container")', 3000);
})
Given my component
import React from 'react'
function List(props) {
const lists = props.list
const list_div = lists.map((lists, index) => {
return (
<li key={index}>{lists}</li>
)
})
return(
<ul className="container">{list_div}</ul>
)
}
export default List
Will appreciate any help.
Upvotes: 0
Views: 985
Reputation: 156
Step 1: Add ref
to your components
//Create ref for parent component
const containerRef = React.createRef()
//Set the created Ref to the element
<ul className="container" ref={containerRef}>{list_div}</ul>
Step 2: Create refs to child components
//Create ref to child components
lists.map((list,index) => listsRef[index] = React.createRef())
Step 3: In your event (either click, load, etc), add this code to automatically scroll in one of the child component
this.containerRef.current.scrollTo({
top: listsRef[index].offsetTop,
left: 0,
behavior:'smooth'
})
Upvotes: 1