ms3300
ms3300

Reputation: 296

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

Upvotes: 5

Views: 12789

Answers (2)

Nicholas Tower
Nicholas Tower

Reputation: 85032

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) {
    // ...
  }
}

Upvotes: 10

mpen
mpen

Reputation: 282955

I don't know why createRef doesn't take an initial value, but I wrote a replacement for it:

export function createRef<T>(initialValue: T): {current: T};
export function createRef<T>(): {current: T|null};
export function createRef<T>(initialValue?: T): {current: T|null} {
    return {current: initialValue ?? null}
}

Upvotes: 0

Related Questions