Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set an initial value on React.createRef() method?

I manage scrolling in my component with a ref that is the current scroll value. I cannot use state and setState, because when the user would be scrolling the setState method would make things really choppy and impossible. Hence, I decided to use refs that don't re render the component, but save the value when the component re renders. My problem is that I cannot set an initial value for the ref. As I am using a class component I cannot use the simple useRef react hook that allows the initial value to be set easily... instead I use React.createRef() but when I put the value in the parenthesis () it doesn't seem to register it and is undefined until the user scrolls. How can I fix that? enter image description here

Here when the component updates (for example when a new message is sent), I want to make sure that it scrolls down to the newest message only if the user is not browsing older messages somewhere above. enter image description here

like image 996
ms3300 Avatar asked Sep 07 '26 16:09

ms3300


1 Answers

To set the initial value of a ref created by React.createRef, do something like the following:

constructor(props) {
  super(props):

  this.scrollPosition = React.createRef();
  this.scrollPosition.current = 201;
}

I do want to mention though, that since you're in a class component, you probably don't need a ref. In function components, refs are often used the way you're using them: to have a mutable object which persists from render to render.

But in class components, you already have a mutable object which persists from render to render: this. So you can probably ditch the ref and just do:

constructor(props) {
  super(props);
  this.scrollPosition = 201;
}

componentDidUpdate(prevProps, prevState) {
  if (this.state.message === "" && this.scrollPosition > 200) {
    // ...
  }
}
like image 149
Nicholas Tower Avatar answered Sep 10 '26 07:09

Nicholas Tower



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!