0

I'm trying to write scroll function in React. I'm catching the DOM element by getElementsByName.

handleScroll=(i, e )=>{
    const {errors} = this.props
    const elementsName = Object.keys(errors)
    const elementScroll = document.getElementsByName(elementsName[i])
    elementScroll.scrollIntoView({ blok: "start", behavior: "smooth" });
}

And when I executed this function i recived "scrollIntoView is not a function" error. The element is catched correctly but the scrollIntoView function is making problems.

UPDATE Problem solved i used

document.querySelector(`[name="${elementsName[i]}"]`)
sakuy123
  • 15
  • 5
  • 1
    scrollIntoView only works on an HTML Element. `getElementsByName()` however returns an collection of elements. – Rence Feb 13 '19 at 09:24
  • But when i console log elementScroll i recived a correct HTML nodelist element. – sakuy123 Feb 13 '19 at 09:26
  • 1
    Because you only have one element with the name. It is still a collection though, just with length 1. You will need to either go over the collection with a foreach, or ensure you only return a single element and not the collection. See https://www.w3schools.com/jsref/met_doc_getelementsbyname.asp and https://www.w3schools.com/jsref/met_element_scrollintoview.asp – Rence Feb 13 '19 at 09:27

1 Answers1

1

The problem is that getElementsByName returns an HTMLCollection which is a list of elements. If you only care about the first element you should do:

handleScroll = (i, e) => {
    const { errors } = this.props
    const elementsName = Object.keys(errors)
    const elementScroll = document.querySelector(`[name="${elementsName[i]}"]`);
    if (elementScroll instanceof HTMLElement) {
        elementScroll.scrollIntoView({ blok: "start", behavior: "smooth" });
    }
}

If you want to perform an operation for each item in the collection you should check the following example (though there isn't any point in scrolling to each element, so this is invalid for this case).

handleScroll = (i, e) => {
    const { errors } = this.props
    const elementsName = Object.keys(errors)
    const elementScrollList = document.getElementsByName(elementsName[i]);
    for (let elementScroll of elementScrollList) {
        elementScroll.scrollIntoView({ blok: "start", behavior: "smooth" });
    }
}
nick zoum
  • 7,216
  • 7
  • 36
  • 80