Reputation: 3958
I have a parent component that renders the following child components:
Object.values(eventData).map((event) => {
return (
<EventsSection
key={event.id}
eventID={event.id}
eventDate={event.date}
/>
);
})
Assuming there are 10-20 records in eventData
- upon a certain user action, how can i make the browser window to scroll onto an EventSection
records based on its key
prop?
Upvotes: 1
Views: 204
Reputation: 1986
You need to use a ref
from the id. Something like the below would be enough if the user wanted to click on the list and make the browser scroll to that ref
.
function renderEventSection(props) {
const { key, name } = props
const ref = useRef()
const handleClick = () =>
ref.current.scrollIntoView({
behavior: 'smooth',
block: 'start',
});
return (
<div key={key} ref={ref} onClick={handleClick}>
{name}
</div>
)
}
If you need to scroll from outside the list, just move that logic to the parent component or use a React Context (See second example). Also, if you need another event, just change it to any other desired user interaction.
Upvotes: 1