apokryfos
apokryfos

Reputation: 40690

React pose state affects child component poses

I'm trying to create a component in react which collapses and expands when required. For this, I am using react-pose. However, I'm encountering problems when trying to nest multiple of this component.

Here's how I define my component:

const CollapsableDiv = posed.div({
  show: {
    height: 'auto',
    overflow: 'hidden'
  },
  hide: {
    height: '0px',
    overflow: 'hidden'
  }
});

And here's where I use it.

class App extends React.Component {
  state = { 
    showing: false, 
    showingInner: false 
  };

  toggleShow = () => this.setState({
    showing: !this.state.showing
  });

  toggleInner = () => this.setState({
    showingInner: !this.state.showingInner
  });

  render() {
    return (
      <React.Fragment>
        <button onClick={this.toggleShow}>
          {this.state.showing?'Hide':'Show'}
        </button>
        <CollapsableDiv pose={ this.state.showing ? 'show' : 'hide' }>
          <div>
            This is some content
            <button onClick={this.toggleInner}>
              {this.state.showingInner ? 'Hide' : 'Show'}
            </button>
            <CollapsableDiv pose={this.state.showingInner ? 'show' : 'hide'}>
              <div>
                This is some inner content    
              </div>
            </CollapsableDiv>
          </div>
        </CollapsableDiv>
      </React.Fragment>
    );
  }
}

The problem I have is that the outer <CollapsableDiv> "pose" seems to be passed to the inner one meaning that when you expand the outer div the inner one also expands. The inner <CollapsableDiv> does not seem to have the same influence on the outer one.

Here's an example of the issue https://codesandbox.io/s/x7nljvom9z?fontsize=14

Am I doing something wrong here? Is it not possible to re-use the same component?

Upvotes: 0

Views: 147

Answers (1)

Tiago Engel
Tiago Engel

Reputation: 3661

To make it "independent" from its parent set withParent={false} on the second CollapsableDiv. E.g.:

<CollapsableDiv
  pose={this.state.showingInner ? "show" : "hide"}
  withParent={false}
>
  <div key="two">This is some inner content</div>
</CollapsableDiv>

Upvotes: 4

Related Questions