Gambit2007
Gambit2007

Reputation: 3958

How can I scroll to a component by component key prop?

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

Answers (1)

Inacio Schweller
Inacio Schweller

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

Related Questions