Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the idiomatic way to use props in component composing in reactjs

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.

Component composing layout

like image 820
Dushan Avatar asked Mar 11 '23 18:03

Dushan


1 Answers

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')
);
like image 176
Dan Prince Avatar answered Mar 17 '23 21:03

Dan Prince