React has an easy way to access DOM APIs of HTML elements through references. We learn how React exposes HTML elements by scrolling an element into view on the click of a button.

People’s behavior on websites did not change very much since the early days of the internet. But one thing that did change — since 1994 to be more precise — was that we learned to scroll longer pages of content. We are now used to websites where not all information may be visible at first sight.

But how do we grab a user’s attention for something that isn’t visible in the current part of the viewport it’s currently looking at. We can utilize a very handy browser API for that, called Element.scrollIntoView(). Which does exactly what it says it does with a few nice options to modify its behavior.

Scroll to element with plain HTML

Before diving into the React implementation, let’s try out the API on a simple HTML list with vanilla Javascript.

Let’s say we have an article with a long text.

<article>
	<h1 id="title">
		An interesting article for Latin readers
	</h1>
	<p>
		Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit amet luctus neque. Etiam eu quam lacinia, placerat sem ut, interdum risus. Quisque ut feugiat mauris. Aenean euismod fermentum facilisis. Donec ultricies maximus elit, sit amet convallis urna rhoncus vitae. Aliquam bibendum turpis et felis blandit commodo. Donec egestas neque non elit laoreet, faucibus tempor ante gravida.
	</p>
	<p>
		Duis in ante turpis. Phasellus dignissim tellus et nunc lacinia elementum. Sed venenatis tincidunt justo. Praesent sed purus facilisis, porttitor ligula in, mattis velit. Curabitur non pellentesque nunc. Duis elit urna, bibendum et purus nec, maximus imperdiet mauris. Cras euismod, leo id vehicula vulputate, nibh massa tincidunt justo, sit amet fringilla quam orci pellentesque enim.
	</p>
	<p>
		...
	</p>
</article>

Whenever a user reached the end of the article, we would like to provide a button to scroll back to the top of the article. This can be achieved by adding a link with the id of the <h1> heading element on the end of the paragraph.

<article>
	...
	<a href="#title">
		Back to the top
	</a>
</article>

Now when the user clicks the link, the browser will automatically jump back to the title element and the user is back on the top of the article. This is the basic way to scroll an element into view without using any Javascript at all.

#reactjs #javascript #html

Scroll a React Component Into View
4.95 GEEK