1

I tried to use ref, but it's not working - scroll only to the bottom of website. I looked everywhere and found no solution, only for list items without map method.

data = [
{id:1, name: "Paul"},
{id:2, name: "Judy"},
{id:3, name: "Thomas"},
]

class NamesList extends Component {

myRef = React.createRef()  
scrollToMyRef = () => window.scrollTo(0, this.myRef.current.offsetTop)

return(
<div>
<ul>
{data.map(user => 
<li key={user.id} onClick={this.scrollToMyRef}>{user.name}</li>
}
</ul>

///CONTENT

<ul>
{data.map(user => 
<li key={user.id} ref={this.myRef}>{user.name}</li>
}
</ul>
</div>
)
}

1 Answers1

0

Try this code. Here I added a blank div inside the ul and gave the reference to it.

///CONTENT

<ul>
{
data.map(user => 
<li key={user.id}>{user.name}</li>
}
<div ref={this.myRef} />
</ul>

And Change the scrollToMyRef() as follows.

const scrollToMyRef() = () => this.myRef.current.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' });