@tpacks/react-mixins v0.0.5
React mixins
This package implements all common-use mixins, designed to work with react v16 and up.
What is mixin and how does it work?
Mixins is a mechanism allows your class to use properties and methods from multiple objects. A mixin is just an object which contains common-use properties and methods. A mix function is required to combine all those mixins (ingredients) to produce a final object which contains all properties and methods from ingredients.
Let's look at this diagram:
We have two mixins: Mixin A with property A1, A2 and mixin B with property B1, B2.
We have a Mix function, which return a function MixConstructor
as result. Inside this function, we use Object.assign
to assign A1, A2, B1, B2 from A and B to MixConstructor.prototype
.
Then we can use this MixConstructor
to create an instance directly, or we can create a class C extends MixConstructor
then make instance from C. Both instances have MixConstructor.prototype
in their prototype chains, then they can use A1, A2, B1, B2 properties.
If A1, A2, B1, B2 are methods, things work the same.
How to use this package?
This is an example shows us how to use the MixinWithFilter
:
import React from 'react';
import {ReactMix, MixinWithFilter} from '@tpacks/react-mixins';
export default class MyComponent extends ReactMix(MixinWithFilter) {
constructor(props) {
super(props);
this.state = {
...this.state,
mixFilter_filter: {search: ''},
};
}
componentDidUpdate(_prevProps, prevState) {
const filterFieldsChanged = this.mixFilter_whichFilterFieldsChanged(prevState, this.state);
if (filterFieldsChanged.search) {
// Call search API here
}
}
render() {
const {search} = this.state.mixFilter_filter;
return (
<input
value={search}
onChange={(e) => {this.mixFilter_handleFilterChange('search', e.target.value)}}
/>
);
}
}
MyComponent
is inherited from ReactMix(MixinWithFilter)
. MixinWithFilter
will automatically inject mixFilter_filter
to MyComponent
state - which is a reserved state property, but it's value is {}
- an empty object. We need to override it's value with {search: ''}
:
this.state = {...this.state, mixFilter_filter: {search: ''}};
MixinWithFilter
also injects two utility functions to MyComponent
: mixFilter_handleFilterChange
and mixFilter_whichFilterFieldsChanged
.
mixFilter_handleFilterChange
function changes value of specific filter field with usage of this.setState
in it's core.
mixFilter_whichFilterFieldsChanged
finds out which filter fields have changed value in comparison with previous state. componentDidUpdate
hook is a perfect place to put the mixFilter_whichFilterFieldsChanged
function.
One thing to remember: if you use mixins in this package, you have to respect the reserved state properties of those mixins. In the example above, you have to use the mixFilter_filter
property in MyComponent
state to hold all filter values. If you use other state property, mixin's utility functions will not work.
To be continued...