skip to Main Content

I have the following code that uses multiple useRef() hooks and a switch statement to scroll to a specific ref based on an index value:

const ref0 = useRef();
const ref1 = useRef();
const ref2 = useRef();
const ref3 = useRef();
const ref4 = useRef();

switch(index) {
  case 0:
    ref0?.current?.scrollIntoView();
    break;
  case 1:
    ref1?.current?.scrollIntoView();
    break;
  case 2:
    ref2?.current?.scrollIntoView();
    break;
  case 3:
    ref3?.current?.scrollIntoView();
    break;
  case 4:
    ref4?.current?.scrollIntoView();
    break;
  default: 
    break;
}

How can I improve this code to make it shorter and more efficient?

4

Answers


  1. Chosen as BEST ANSWER

    Answer from ai

    const refs = [
      useRef(),
      useRef(),
      useRef(),
      useRef(),
      useRef()
    ];
    
    const scrollToRef = (index) => {
      if (index >= 0 && index < refs.length) {
        refs[index]?.current?.scrollIntoView();
      }
    };
    
    scrollToRef(index);
    

  2. You can use something like this:

    const refs = [useRef(), useRef(), useRef(), useRef(), useRef()];
    
    refs.forEach((ref, i) => {
      if (i === index) {
        ref?.current?.scrollIntoView();
      }
    });
    

    Changed your switch-case to foreach loop. It iterates through array and find the one that meets the condition.

    Login or Signup to reply.
  3. const refs = [useRef(), useRef(), useRef(), useRef(), useRef()];
    if (index >= 0 && index < refs.length) {
      refs[index]?.current?.scrollIntoView();
    }
    

    You could use an array of refs instead separate ref variables, then you would have to check if the ‘index’ value is within the valid range. If it is, you’ll access the corresponding ref using ‘refs[index]’ and call ‘scrollIntoView()’ on the ‘current’ property.

    This approach is more concise and eliminates the repetitive code

    Login or Signup to reply.
  4. You can just use an array of refs like this:

    import { createRef, useEffect, useRef } from 'react';
    
    export default function Sample() {
        // create a ref with its content of 10 refs
        const refs = useRef([]);
        refs.current = Array.from({ length: 10 }).map(() => createRef());
    
        useEffect(() => {
            // you can call any dom methods here, call inside any of your listeners' callback or effects
            const indexOfRefIWantToScroll = 5;
            refs.current[indexOfRefIWantToScroll].current?.scrollIntoView();
        }, []);
    
        // bind each ref to your element
        return (<>
            { Array.from({ length: 10 }).map((ele, index) => <div ref={refs.current[index]} key={index} className='scrollElement'></div>) }
        </>)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search