bier hier
bier hier

Reputation: 22520

How can I open the collapsing div through prop?

I have a react-bootstrap Collapse that should open/close when clicking the button. I also want to open it through a redux dispatch but for simplicity I am passing a property with a bool value:

 <App opennow={true} />

This is part of the render method in my Appcomponent:

 render() {
    console.log('opennow', this.props.opennow)

    //this.state.open = this.props.opennow;
    console.log(this.state.open);
    return (
      <div>
        <Button onClick={ 
            ()=> 
      this.setState({ open: !this.state.open })
                        }>
          click
        </Button>
        <Collapse in={this.state.open}>
          <div>

How can I keep the existing show/hide functionality and trigger a show ie open the Collapse through a property in this case this.props.opennow? Here is a Codepen

Upvotes: 3

Views: 181

Answers (1)

mrinalmech
mrinalmech

Reputation: 2155

Add a componentDidMount in your class. It runs code after the DOM has been generated.

 componentDidMount(){
     if(this.props.opennow){
       this.setState({open:true})
     }
  }

If the opennow prop is passed as true it checks the condition and sets the open to true in the state.

Here's the codepen

Upvotes: 2

Related Questions