intro.js-react using onchange

203 views Asked by At

I am new to intro.js-react and I am currently trying to execute a function at a specific step, however I am having trouble figuring out how to do so. I know there is an onChange prop that can be used with Steps but I am unsure of how implement it here.

import React, { useState } from "react";
import { Box, Tooltip, Button, } from "@chakra-ui/react";
import { Steps } from "intro.js-react";
import "intro.js/introjs.css";

const Tutorial = () => {

  const [enabled, setEnabled] = useState(false);
  const [initialStep, setInitialStep] = useState(0);

  const clickAction = () => {
    setEnabled(true);
  };

  const onExit = () => {
    setEnabled(false);
  };

  // Tutorial steps
  const steps = [
    {
      element: ".s1",
      intro: "Step 1",
    },
    {
      element: ".s2",
      intro: "Step 2",
    },
    {
      element: ".s3",
      intro: "Step 3",
    },
    {
      element: ".s4",
      intro: "Step 4",
    },
  ];

  return (
    <Box>
      <Steps
        enabled={enabled}
        steps={steps}
        initialStep={initialStep}
        onExit={onExit}
      />

      <Tooltip
        ml="1rem"
        hasArrow
        label="Click for tutorial"
        fontSize="md"
        borderRadius="10px"
        aria-label="information"
      >
        <Button colorScheme="facebook" onClick={clickAction} ml="2rem">
          Tutorial
        </Button>
      </Tooltip>
    </Box>
  );
};

export default Tutorial;

How would I be able to implement onchange so that I could execute a function at a certain step (example when step is at .s2)

I have tried examples from other posts however those approaches are related to intro.js, not intro.js-react.

1

There are 1 answers

0
RubenSmn On

As you mentioned you can use the onChange handler for this.

Per documentation the onChange handler receives two arguments

Function (nextStepIndex, nextElement)

We can use the nextStepIndex to check if this index has a element value of ".s2". If it is the desired step we can execute a function. Something like this should work:

<Steps
  enabled={enabled}
  steps={steps}
  initialStep={initialStep}
  onExit={onExit}
  onChange={(nextStepIndex) => {
    const isS2 = steps[nextStepIndex].element === ".s2";
    if (isS2) {
      console.log("it is s2");
      // here your function
    }
  }}
/>