Adnan Arif
Adnan Arif

Reputation: 107

How to redirect a page after validation is done in ReactJS

I am using multistep form in react once i click on Next button it's redirect to next step, but now I want to validate the form too, So once validation is done then it's need to redirect to next step. Here's my code:

import React, { useState } from 'react';  
import SimpleReactValidator from 'simple-react-validator';

const UserDetails = ({ setForm, formData, navigation }) => {
     const {
    fullName
    } = formData;
    const useForceUpdate = () => useState()[1];
    const validator = new SimpleReactValidator();

    const forceUpdate = useForceUpdate();
    const submitForm = (e) =>{  
        e.preventDefault()

        if (validator.allValid()) {
          alert('You submitted the form and stuff!');
        } else {

            validator.showMessages();
           forceUpdate();
        }
      }
      {validator.showMessages('fullName', fullName, 'required|alpha')}
      {validator.showMessages('fullName', fullName, 'required|alpha')}
return( 
<>
<input
type="text"
name="fullName"
placeholder='Name'
onChange={setForm}
defaultValue={fullName} />
    <label className="form__label" htmlFor ="fullname">Name</label>         
  {validator.message('fullName', fullName, 'required|alpha')}
 <button className="btn green_btn w250 font22"  onClick={submitForm}>
Next </button>
</>

I want once all data is validate then

    const { next } = navigation;  

this code should be enable and it's goes to next step..

Upvotes: 0

Views: 1923

Answers (1)

Kesav
Kesav

Reputation: 149

Use the useHistory hook from react-router.Add the pathname for the nextpage to it when all the validations are done.

import React, { useState } from 'react';  
import SimpleReactValidator from 'simple-react-validator';
import { useHistory } from 'react-router-dom';

const UserDetails = ({ setForm, formData, navigation }) => {
     const {
    fullName
    } = formData;
    const useForceUpdate = () => useState()[1];
    const validator = new SimpleReactValidator();
    const history=useHistory()
    const forceUpdate = useForceUpdate();
    const submitForm = (e) =>{  
        e.preventDefault()

        if (validator.allValid()) {
          history.push('/pathname for nextpage')
          alert('You submitted the form and stuff!');
        } else {

            validator.showMessages();
           forceUpdate();
        }
      }
      {validator.showMessages('fullName', fullName, 'required|alpha')}
      {validator.showMessages('fullName', fullName, 'required|alpha')}
return( 
<>
<input
type="text"
name="fullName"
placeholder='Name'
onChange={setForm}
defaultValue={fullName} />
    <label className="form__label" htmlFor ="fullname">Name</label>         
  {validator.message('fullName', fullName, 'required|alpha')}
 <button className="btn green_btn w250 font22"  onClick={submitForm}>
Next </button>
</>

Upvotes: 1

Related Questions