Main logic in 86 idiomatic lines of code
No third party library: I previously worked with React Hook Form, although for this job, I achieved the spec requirements and further without it.
Built on Hooks: controlled navigation progress with state persistence.
Live link ๐ onClick
- Open terminal
- Run
git clone https://github.com/vercetti11/treyway.git
- Run
cd treyway
- Run
npm i
- Run
yarn start
User can only advance until the last unsubmitted page.
To advance further: fill the fields, refill if necessary, hit submit button.
After validation user sees next page, but he can go back to a previous page and change input values(they persist).
Run yarn test
in a new terminal window.
Tests are functional and made from a user point of view, just as the spec:
With the current design, each form page is a component, therefore its a matter of editing the corresponding element.
Mapping over formPages
renders three buttons, one for each element in the array.
User clicks on a button to navigate, and the button sets a new state using the index from mapping over formPages
.
Next, a switch
statement assesses what component to render depending on the initial value (0) or the index passed from the previously clicked button.
Notice how this is a lowly coupled design.
const formPages = ["User", "Privacy", "Done"];
const [activePage, setActivePage] = useState(0);
const [progress, setProgress] = useState(0);
{formPages.map((page, index) => (
<button
key={page}
disabled={progress < index}
onClick={() => setActivePage(index)}
className={page === formPages[activePage] ? "active" : ""}
>
{page}
</button>
))}
// const [activePage, setActivePage] can use the strings inside the formPages array
// instead of their indexes, but then the cases in the switch would also depend on
// strings which are more cumbersome to write. Legibility is traded for extensibility.
{...}
switch (activePage) {
case 0:
return <FormPageUser/>
case n:
return <FormPageN/>
}
In App.js do the following:
- Insert name of the new page in
const formPages = ["User", "New Page", "Privacy", "Done"];
- Wire up a component in the
Switch
statement with the appropriate index andprops
. - Implement mentioned component as needed.
I can improve the app with better validation messages by using react-hook-form.
State can be stored to localstorage
to persist an accidental reload; alternatively, accidental reload can be prevented by setting an observer on beforeunload
event.
React Hook Form praises it's superiority to Redux Form library, but it doesn't mean it is against Redux. The approach I take using react-hook-form with Redux is to dispatch actions on submit instead of <input onChange.
All the manual wiring up of components can be abstracted, but that leads to overengineering in this particular case.
Programing it's like gardening.