Home > Mobile >  how do i animate multiple dropdowns in one page without repeating code in React?
how do i animate multiple dropdowns in one page without repeating code in React?

Time:12-06

This is my code so far and it works1 but if i make multiple dropdowns and click on only one they all open at the same time. enter image description here

const Dropdown = () => {
  const [drop, setDrop] = useState(false);

  const handleDrop = () => {
    setDrop(!drop);
  };

  return (
    <div>
      <h1>Help</h1>
      <div onClick={handleDrop}>
        {drop ? <AiOutlineMinus /> : <BsPlus />}
      </div>
    </div>
    <div className={drop ? "h-auto flex-col" : "fixed left-[100%]"}>
      <div>
         <h1>hello</h1>
      </div>
   </div>
   <div>
      <h1>Um</h1>
      <div onClick={handleDrop}>
        {drop ? <AiOutlineMinus /> : <BsPlus />}
      </div>
    </div>
    <div className={drop ? "h-auto flex-col" : "fixed left-[100%]"}>
      <div>
         <h1>hello</h1>
      </div>
   </div>
 )

How can i solve this issue without having to make multiple functions for each dropdown?

CodePudding user response:

You have to create a component from your <Drodown /> (save it in a sepearte file i.e. Dropdown.js) and then pass the headline (headline) and the options to select (content) dynamically to the component.

const Dropdown = ({headline, content}) => {
  const [drop, setDrop] = useState(false);

  const handleDrop = () => {
    setDrop(!drop);
  };

  return (
    <div>
      <h1>{headline}</h1>
      <div onClick={handleDrop}>
        {drop ? <AiOutlineMinus /> : <BsPlus />}
      </div>
    </div>
    {content.map((index, entry) => {
        return (
            <div 
                className={drop ? "h-auto flex-col" : "fixed left-[100%]"} 
                key={index}>
                <div>
                    <h1>{entry}</h1>
                </div>
            </div>
        })
     }
   </div>
 )
}

Note, the code rendering the content is sort of pseudocode. You have to adapt it (datastructure of content and function to render it) to your needs.

CodePudding user response:

We usually call this component "Accordion", and you have multiple accordions inside your "Dropdown" component.

You could create one component that would serve as THE accordion component, this component could receive the title (Hello, Um, etc..) and its content by props. This component would have his own individual state.

You would have something like:

<Accordion title="Hello" content="Content that is hidden by default" />

Or if you want to maintain them in the the same component you could create indexes for them and store the indexes in a array state, and instead of using "drop" to check if the accordion is opened, you could send to a function to check if the index is included in the state.

  • Related