Web development basic and advance tutorial, php basic tutorial, laravel basic tutorial, React Native tutorial

Wednesday, January 18, 2023

How to Scroll to Element in React

0 comments

How to Scroll to Element in React


import React from 'react'
import { useRef, useState } from 'react';
import { flushSync } from 'react-dom';


const TestScroll =() => {

const listRef = useRef(null);
const [people, setPeople] = useState([]);



const handleAddClick = () => {
// 👇 Will wait until the DOM is updated with the new state
//flushSync(() => {
setPeople((people) => [
...people,
{
id: `${Date.now()}`,
name: 'hhhh iiiii uuuuu yyyyyyyy',
},
]);
//});

// 👇 Scroll to the last element in the list
listRef.current?.lastElementChild?.scrollIntoView();
};

return (
<div style={{ height: 500 }}>
<h3>UUUU FFFFKKKKK</h3>

<div style={{ height: 400, borderWidth: 1, borderColor: 'red', overflow: 'scroll' }} ref={listRef}>
{people.map((person, index) => (
<li key={person.id}> {index}. {person.name}</li>
))}
</div>
<div style={{ height: 100 }}>
<button onClick={handleAddClick}>Add new person</button>
</div>
</div>
)
}


export default TestScroll


No comments:

Post a Comment