Skip to content

Managing child component state #1

Closed
@kuon

Description

@kuon

I'm trying your library for a new project, and I just hit a small problem.

Let's consider the following structure:

<SplitView id="my-splitview">
  <SplitViewPane>
    something
  </SplitViewPane>

  <SplitViewPane>
    something else
  </SplitViewPane>
</SplitView>

I'd like the SplitView component to manage the state of it's children, and I'd like the children to be able to read props and dispatch actions in the context of the SplitView.

For example, this is what I have to do now:

function render(props) {

  let items = []

  props.children.forEach((child, i) => {
    items.push(React.cloneElement(child, {
      key: i,
      horizontal: props.horizontal,
      collapsed: props.panes[i].collapsed,
      height: props.panes[i].height,
      width: props.panes[i].width,
      toggleCollapsed: props.toggleCollapsed 
    }))

  })

  return (
    <div>
      { items }
    </div>
  )
}



export default
local({
  key: (props) => props.id,
  createStore: (props) => {
    let panes = props.children.map((child) => child.props)
    return createStore(reduce, { panes })
  },
  mapStateToProps: (state, props) => {
    return {
      panes: state.panes
    }
  },
  mapDispatchToProps: (dispatch) =>({
    toggleCollapsed: (index) => dispatch(toggleCollapsed(index))
  })
})(render)

In this example, the toggleCollapsed action is passed to the child, along with the state.

What I'd rather do, is to only pass an index propery to my children panes, and have a local in my children looking like this:

// in child

function render(props)  {  
return (
    <div className="this-is-split-view-pane" onClick={props.toggleCollapsed}>
    { props.children }
    </div>
  )
}

export default
local({
  key:  // parent key, this is inherited somehow
  createStore: // this is inherited somehow
  mapStateToProps: (state, props) => {
    return state.panes[props.index] // here I can access the PARENT state
  },
  mapDispatchToProps: (dispatch) =>({
    // this dispatch to the parent store
    toggleCollapsed: (index) => dispatch(toggleCollapsed(index))
  })
})(render)

This code might have typos, I tried to simplify my real case into an understandable example.

But I hope the paradigm is simple enough.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions