Home » Javascript » Toggle react components

Toggle react components

Posted by: admin November 1, 2017 Leave a comment

Questions:

When I open a component I need to close all other components. On click they render a list

class ParentComponent extends Component{ 
  constructor(props){
   super(props)
   this.state= {...}
 } 

   render(){
      return(
         <DropDown />
         <DropDown />
         <DropDown />
        )
   }
}

Each DropDown component has its own state to manage open/close on click event. How can i make sure all components are closed except the one i click on ?

Answers:

Ultimately, you need to keep track of which Dropdown component is “active” in the ParentComponent’s state. I can think of a few ways to toggle the active state of each Dropdown component, but the high level explanation would be to pass a function from the parent component as a prop into the dropdown component that will call this.setState on the parent’s state upon the user opening/closing the dropdown. You can then define another prop on the Dropdown component that “deactivates” it. Finally, in your parent component, conditionally apply the “deactivate” flag to the Dropdown components that you want to be closed based on the state.

Questions:
Answers:

Here is the jsfiddle example to manage to show single drop down

`http://jsfiddle.net/sitaramireddy/ffvfyz0w/`