Redirecting to a specific page based on conditions (Ionic + React)

711 Views Asked by At

I have made a questionnaire using ionic slides and I am able to create an array called Answers which stores the selected value from each question.

I wanted to enquire how I can now use an if-statement with this array and then navigate to a specific page when I click "Finish" on the last question?

const answers = [selected1, selected2, selected3, selected4, selected5];

const s1 = [1,2,1,1,1];

function suggestion(answers: number[] | undefined): void {
        if (answers == s1) {
            **not sure what to do here to navigate**
        }
    }

This is the IonButton code:

<IonButton class = "finishbttn" size="small" onClick = {()=> suggestion(answers)}> Finish </IonButton>
1

There are 1 best solutions below

2
On

If you want a link to a page, you should use routerLink instead of onClick(). onClick() is for doing processing (submitting a form, toggling a value, etc.), while routerLink is to link to another page in the router.

Although it is possible to do a redirect in onClick(), IonRouter can get confused, so it is better to use routerLink.

So, first change your <IonButton> to use routerLink.

<IonButton routerLink={doRedirect(answerValue)}>Finish</IonButton>

This uses a redirect function, so you redirect based on the answer values:

const doRedirect = (answers: number[] | undefined) => {
  if (answers === s1) {
    return 'routeForS1';
  }
}

You will of course need to create the routes in your router so that the redirects will work.