jcmcneal / react-step-wizard

A modern flexible step wizard component built for React.
MIT License
583 stars 126 forks source link

Is there a way to reset the wizard on route change? #78

Closed jvgeee closed 3 years ago

jvgeee commented 3 years ago

I have 6 pages, each of which has a step-wizard on them.

It's something similar to this:


function SectionContent(props) {
const {introduction, tips, config, content} = props;

return <StepWizard isHashEnabled={true}>
        {introduction && (
          <IntroductionContent
            content={content}
            config={config}
            introduction={introduction}
            hashKey={getHashKey(introduction.title)}
          />
        )}

        {tips &&
          tips.map((item, key) => (
            <TipsContent
              content={content}
              config={config}
              item={item}
              key={key}
              hashKey={getHashKey(item.title)}
            />
          ))}
      </StepWizard>
}

function SectionScreen(props) {
  const {sectionName} = useParams()
  let content
  let config

  switch (sectionName) {
    case 'onboarding':
      content = onboarding
      config = onboardingConfig

      break
    case 'key-people':
      content = keyPeople
      config = keyPeopleConfig

      break
  }

  return (
    <SectionContent
      {...props}
      sectionName={sectionName}
      content={content}
      config={config}
    />
  )
}

The introduction and tips objects come from props, based on the current app route and represent an entirely different wizard; they just reuse the same component.

If I'm on step 5 of a wizard, and then I click my nav to go to a different wizard, it opens step 5 of that wizard.

What am I doing wrong here? Is there a way to unmount or reset the wizard on URL change? To add complication, I have conditional steps (based on answers from previous steps) that sometimes show / hide a screen, so I don't want to reset the wizard whenever any children change.

I'm thinking there should be some sorta way to reset the wizard using useEffect(), but I'm a bit lost here.

resolritter commented 3 years ago

You can try using the "key" functionality from React.

https://reactjs.org/docs/lists-and-keys.html#keys

Pseudo-code:

const [currentRoute, setCurrentRoute] = React.useState()

history.listen(() => setCurrentRoute(route))

<WizardComponent key={currentRoute} />

It can be a solution because, when the key changes, React will throw away the previous component instance and recreate another one from scratch. That should effectively reset the Wizard.

jvgeee commented 3 years ago

Perfect! That solves it, sounds like it was more of a React implementation problem than a step-wizard problem. Cheers @resolritter !