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
Answer from ai
You can use something like this:
Changed your switch-case to foreach loop. It iterates through array and find the one that meets the condition.
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
You can just use an array of refs like this: