Writing super reusable components

const initial = {
firstName: '',
lastName: '',
info: ''
};
function exampleReducer(state, action) {
switch (action.type) {
case 'update_firstName':
return {
...state,
firstName: action.value,
};
case 'update_lastName':
return {
...state,
lastName: action.value,
};
case 'update_info':
return {
...state,
info: action.value,
};
default:
return {
...state,
};
}
}

export function ComponentOne() {
const [state, reactDispatch] = useReducer(exampleReducer, initial);
return (
<>
<div id="inputcontainer">
<label>First Name</label>
<input
label="firstName"
onChange={(e) => { reactDispatch({ type: 'update_firstName', value: e.target.value }); }}
/>
</div>
<div id="inputcontainer">
<label>Last Name</label>
<input
label="lastName"
onChange={(e) => { reactDispatch({ type: 'update_lastName', value: e.target.value }); }}
/>
</div>
<div id="inputcontainer">
<label>Info</label>
<input
label="info"
onChange={(e) => { reactDispatch({ type: 'update_info', value: e.target.value }); }}
/>
</div>
</>
);
}
const initial = [
{
label: 'First Name',
key: 'firstName',
value: '',

},
{
label: 'Last Name',
key: 'lastName',
value: '',

},
{
label: 'First Name',
key: 'lastName',
value: '',
},
];

function exampleReducer(state, action) {
switch (action.type) {
case 'UPDATE':
return {
...state,
[action.key]: {
...state[action.key],
value: action.value,
},
};
default:
return {
...state,
};
}
}

export function component() {
const [state, dispatch] = useReducer(exampleReducer, initial);
return (
<>
{
state.map((field) => (
<ReusableComponent field={field} dispatch={dispatch} />
))
}
</>
);
}

export function ReusableComponent({ field, dispatch }) {
return (
<div id="inputcontainer">
<label>{field.label}</label>
<input
label={field.key}
onChange={(e) => { dispatch({ type: 'UPDATE', key: field.key, value: e.target.value }); }}
/>
</div>
);
}

Why is this so good for dev teams?

At Templar Payments, we’ve just hired 3 new NorthCoders (a coding bootcamp), and so leveraging the simplicity of reusable components allows us to quickly introduce the codebase to new starters in a modular format, preventing a new developer from being bewildered when looking over your codebase.

Storybook

Utilising Storybook for showcasing components to new developers allows you to provide an easy-to-use format for developers to pick and choose what they need from an already created, already tested codebase, allowing them to see all configurable props to make integrating simpler.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nathan Leadill

Nathan Leadill

CTO at Templar Payments, but really I'm just a glorified Javascript developer.