Jump to specific step - React Js

Viewed 55

I've created my own stepper like functionality, which works fine.

But the problem is this stepper component movement is limited to next & previous steps only.

I need to jump other screen using index.

Below is my code,

const App: React.FC = (props: any) => {
  console.log(props);
  const [step, setStep] = useState(0);
  /** Set up a ref that refers to an array, this will be used to hold
   * a reference to each step
   */
  const refs = useRef<(HTMLDivElement | null)[]>([]);
  /** Whenever the step changes, scroll it into view! useEffect needed to wait
   * until the new component is rendered so that the ref will properly exist
   */
  useEffect(() => {
    scrollToComponent(refs.current[step]);
    // refs.current[step]?.scrollIntoView({ behavior: 'smooth' });
  }, [step]);

  return (
    <div className="App">
      <button>Move to Component A</button>
      <button>Move to Component B</button>
      <button>Move to Component C</button>

      {steps
        .filter((_, index) => index <= step)
        .map((Step, index) => (
          <Step
            key={index}
            /** using `domRef` here to avoid having to set up forwardRef.
             * Same behavior regardless, but with less hassle as it's an
             * ordianry prop.
             */
            domRef={(ref) => (refs.current[index] = ref)}
            /** both prev/next handlers for scrolling into view */
            toPrev={() => {
              console.log(refs);
              scrollToComponent(refs.current[index - 1]);
            }}
            toNext={() => {
              if (step === index + 1) {
                console.log(refs);
                scrollToComponent(refs.current[index + 1]);
                // refs.current[index + 1]?.scrollIntoView({ behavior: 'smooth' });
              }
              /** This mimics behavior in the reference. Clicking next sets the next step
               */
              setStep(index + 1);
            }}
            /** an override to enable reseting the steps as needed in other ways.
             * I.e. changing the initial radio resets to the 0th step
             */
            setStep={setStep}
            step={index}
          />
        ))}
    </div>
  );
};

Working example, stackblitz Link

Please help I stuck and unable to proceed further.

1 Answers
Related