Ref in React

Dealing with Ref in React JS

The references on React are utilized to access the instance in a DOM node and able to interact just like you would do it in JavaScript or components created with react. 

import React, { createRef } from 'react';

const MyComponent=() => {
	const myRef = createRef();
	return (
		<section ref={myRef}>
		</section>
	);
};

export default MyComponent;

This is the example in which we added a reference in a DOM element so later we can obtain its offsetTop property and scroll to it. 

In the instance myRef we have the property called current in which you can find that makes reference to the element. 

import React, { createRef } from 'react';

const MyComponent=() => {
	const myRef = createRef();
	const scrollTop = () => {
		const top = myRef.current.offsetTop;
		window.scrollTo({
			top: top,
			behavior: 'smooth'
		});
	}
	return (
		<>
		<section ref={myRef}>
		</section>
		<button onClick={scrollTop}></button>
		</>
	);
};

export default MyComponent;