0

I'm trying to solve kind of simple problem: when component is loaded, i need to scroll it to the bottom. But i've wasted ton of hours trying to solve it. I've tried a lot of different ways (scrollIntoView, scrollTop, scrollBy, etc...) but none of them can't do it. Url below is a link to fiddle where i have a simple component and i need Message to be shown. The problem is that i have to scroll about 10 pixels by myself. I would really appreciate if you help me to solve this problem.

class Hello extends React.Component {
  componentDidMount() {
    const elem = ReactDOM.findDOMNode(this.refs.test);

    if (elem) {
      elem.scrollIntoView(false);
    }
  }

  render() {
    return (
      <div>
        <div className="test" 
             ref="test">
             Hello {this.props.name}
        </div>
        <div>Message</div>
      </div>
    )
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

JSFiddle

3 Answers 3

2

You placed the ref attribute on the wrong place.

Move it one level up in order to catch the whole component, including the "Message" text.

So, basically:

class Hello extends React.Component {
  // ...

  render() {
    return (
      <div ref="test">
        <div className="test">
             Hello {this.props.name}
        </div>
        <div>Message</div>
      </div>
    )
  }
}

Here's a working jsfiddle demo, forked from yours.

Sign up to request clarification or add additional context in comments.

Comments

0
  class Hello extends React.Component {
  // ...

  componentDidUpdate() {
    this.scrollDiv.scrollIntoView(false);
  }

  render() {
    return (
      <div
        ref={(el) => {this.scrollDiv = el}}
      >
        <div className="test">
             Hello {this.props.name}
        </div>
        <div>Message</div>
      </div>
    )
  }
}    

Comments

-1

You should scroll only when the component is loaded into DOM filled with all props.

export default class Hello extends React.Component {
  constructor(props,context){
    super(props,context);
    this.isAlreadyLoaded =  false;
   }

componentWillReceiveProps(nextProps) {
    let scrollToElement = document.getElementById("scroll-element");
    if (scrollToElement && !isAlreadyLoaded){
        this.isAlreadyLoaded = true;
        scrollToElement.scrollIntoView(true);
    }
  }

   render(){
      return {....}
   }
}

1 Comment

That doesn't address the main problem, presented in the question. The question is about why it doesn't scroll down to the "Message" text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.