Dear architects/design experts,
I'm using Alt Js to inject stores and actions to react native components. In this case some stored properties are not using in entire component tree, but only by some components which are in very deeper level.
For example (Please refer to image): I have composed component X
using Y
and Z
components. And injected an alt store called P
to component X
and passing it to component Z
through component Y
as a prop. In this case the P
store is not using by component Y
, but had to pass as a prop to Y
because it needs to component Z
I feel like the prop requirement of component Z
ruins the usage places of component Y
because of that prop is really not using by Y
in it self, just passing to Z
. What is the idiomatic way to inject alt stores and pass props to child components without messing the code. Is there a way to pass props, inject alt stores to one specific place and use in every component without passing through entire component tree.
You can pass down unexpected props by making each component pass down all of its props.
function ComponentX(props) {
const { p } = props;
// use p here
return <ComponentY {...props} />;
}
function ComponentY(props) {
// don't use props.p here
return <ComponentZ {...props} />;
}
function ComponentZ(props) {
const { p } = this.props;
return <span>{p}</span>
}
render(
<ComponentX p={true} />,
document.getElementById('app')
);
However, if you're passing a store down through the components, then you might want to take a leaf from react-redux's book and use the context mechanism instead.
Design a provider component which is initialized with the store (example comes directly from react-redux). In fact, you could almost definitely just use react-redux
to pass your store down.
export default class Provider extends Component {
getChildContext() {
return { store: this.store }
}
constructor(props, context) {
super(props, context)
this.store = props.store
}
render() {
return Children.only(this.props.children)
}
}
Then wrap your top-most component in your provider and all it (and it's children) will be able to access the store through context.
function ComponentX(props, context) {
const { foo } = context.store;
return <div>{foo}</div>;
}
render(
<Provider store={yourStore}>
<ComponentX />
</Provider>,
document.getElementById('app')
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With