0

In React I have built a re-usable component which manages its own state (open/closed) for brevity. Let's call it Panel.

I have another component which makes use of that panel component lets call it Bob. After calling an API, I would like to trigger Panel (open the panel).

Do I really have to manage state in Bob (the calling component) for whether panel should open and pass it as props? Surely there is a way to manage state ONLY in Panel by exposing a method from Panel.

Here's what I have been doing: Bob manages state: shouldOpen: boolean;

When Bob needs the panel to open: this.setState({shouldOpen: true});

<Panel
  shouldOpen={this.state.shouldOpen}
/>

Panel has a separate state {isOpen: false}

What I would like to do, is expose a method in Panel which can be called from Bob. This would eliminate the need to manage state in both Bob AND in Panel. So that when I call an API, I can call openPanel

public openPanel = () => {
  this.setState({isOpen: true});
}
public closePanel = () => {
  this.setState({isOpen: false});
}

I'm looking for the RIGHT way to do this. If that means I need to structure my code differently, please provide guidance. To me it just makes sense that panel should manage its own open/closed state.

Acts7Seven
  • 417
  • 1
  • 6
  • 14

1 Answers1

1

In React you often find the pattern, that a reusable component offers an interface via props, e.g in your case an isOpen in Panel. However, your Panel component does not have to store anything in its state and should rather use this.props, if it is a component that is 'controlled' by its parent like in your case - this is completely fine and good code so don't worry about it.

To answer the other part of your question: yes it is possible to call methods on your Panel component by using React.createRef, please see How to access component methods from “outside” in ReactJS?.

Ali Nasserzadeh
  • 1,365
  • 7
  • 15