- Ariana ease passing components callbacks down to their children in a react application.
npm install --save ariana
import Ariana from 'ariana';
- Create a 'callbacks object' (an object that contains all component's callbacks) :
//In Main.jsx
const mainCallbacks = {
handleFiltering: filterInput => this.setState(filterInput),
log: s => alert(s)
};
- Instantiate a new root wrapper with the callbacks object by calling Ariana :
//In Main.jsx
const wrapper = Ariana(mainCallbacks);
- Pass the 'wrapper' to children components using 'props' :
//In Main.jsx
<Filters
text={this.state.filterText}
stockOnly={this.state.inStockOnly}
ariana={wrapper}
/>
- Use any callback in a child component using the 'wrapper' passed via 'props' :
//In Filters.jsx
const { ariana } = this.props;
ariana.handleFiltering({
filterText: "Ariana"
});
- Overload parent callbacks behaviour by adding new callbacks functions at each stage of the react-app's components tree:
//In Table/index.jsx
const { ariana } = this.props;
const tableCallbacks = {
handleSorting: newSort => this.setState(newSort),
log: () =>
ariana.log(
"Wow... Table/index.jsx component's 'log' callback has been called."
) //overload parent's 'log' callback
};
//add a child wrapper to handle callbacks of this child component
const lisa = ariana.child(tableCallbacks);
//pass lisa(ariana's child) via props to this component's child (Header.jsx)
<Header lisa={lisa} />
- Access a grandparent's callbacks by using the wrapper's 'parent' property :
//In Header.jsx
<button
onClick={() => {
/*use the the parent component's callback*/
lisa.handleSorting({
sort: {
by: column,
asc: !true
}
});
/*use the the grandparent component's callback*/
lisa.parent.log(
"Jeez... Main.jsx component's 'log' callback has been called."
); //it could be possible to do lisa.parent.parent.[...].log()
}}
>
- At any time you can create a copy of the callbacks object contained in the wrapper :
const mainCallbacksCopy = ariana.eject();
- You can use any key name in callback objects except the words reserved by Ariana :
'child'
,'parent'
,'val'
and'eject'
which are functions names of the wrapper.