Created
September 13, 2018 07:20
-
-
Save longnt80/bcad4559660213ab77b058e86f95b7ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import { Formik } from 'formik'; | |
import history from '../../../history'; | |
import ProgressBar from './ProgressBar'; | |
class Wizard extends React.Component { | |
static Page = ({ children, parentState }) => { | |
return children(parentState); | |
}; | |
constructor(props) { | |
super(props); | |
this.state = { | |
values: props.initialValues, | |
}; | |
} | |
next = values => { | |
history.push( | |
this.props.routes[ | |
Math.min(this.props.currentStep + 1, this.props.children.length - 1) | |
], | |
); | |
this.setState(() => ({ | |
values, | |
})); | |
}; | |
previous = () => | |
history.push(this.props.routes[Math.max(this.props.currentStep - 1, 0)]); | |
validate = values => { | |
const activePage = React.Children.toArray(this.props.children)[ | |
this.props.currentStep | |
]; | |
return activePage.props.validate ? activePage.props.validate(values) : {}; | |
}; | |
handleSubmit = (values, bag) => { | |
const { children, onSubmit, currentStep } = this.props; | |
const isLastPage = currentStep === React.Children.count(children) - 1; | |
if (isLastPage) { | |
return onSubmit(values, bag); | |
} | |
this.next(values); | |
bag.setSubmitting(false); | |
}; | |
render() { | |
const { children, currentStep } = this.props; | |
const { values } = this.state; | |
const totalStep = React.Children.count(children); | |
const activePage = React.Children.toArray(children)[currentStep]; | |
const isLastPage = currentStep === React.Children.count(children) - 1; | |
return ( | |
<Formik | |
initialValues={values} | |
enableReinitialize={false} | |
validate={this.validate} | |
onSubmit={this.handleSubmit} | |
render={({ values, handleSubmit, isSubmitting, handleReset }) => ( | |
<div> | |
<ProgressBar currentStep={currentStep} totalStep={totalStep} /> | |
<form onSubmit={handleSubmit}> | |
{React.cloneElement(activePage, { name: "new props" })} | |
<div className="buttons"> | |
{currentStep > 0 && ( | |
<button type="button" onClick={this.previous}> | |
« Previous | |
</button> | |
)} | |
{!isLastPage && <button type="submit">Next »</button>} | |
{isLastPage && ( | |
<button type="submit" disabled={isSubmitting}> | |
Submit | |
</button> | |
)} | |
</div> | |
<pre>{JSON.stringify(values, null, 2)}</pre> | |
</form> | |
</div> | |
)} | |
/> | |
); | |
} | |
} | |
export default Wizard; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey sorry I didn't see the github message as it was deleted. Looks like you worked it out though!