Search code examples
reactjsantd

How can I put a button into collapse?


I want to put a button into a collapse, I am using the collapse of antd, that new button doesn't should open or close the collapse, I want to give her other functionality?

const {  Collapse, Button  } = antd;
const { Panel } = Collapse;

function callback(key) {
  console.log(key);
}

const text = ` hi `;

ReactDOM.render(
  <Collapse 

  defaultActiveKey={['1']} onChange={callback}>
    <Panel header={<Button type="primary">Primary Button</Button>} key="1" >
    <Button type="link">My button</Button>  > 
      <p>{text}</p>
    </Panel>
  </Collapse>,
  mountNode,
);

Why does the COLLAPSE open when I click the button? I don't want the COLLAPSE to open


Solution

  • I guess the button you want to not open the collapse is your Primary Button in header of Panel, To do that you have to control activeKey manually, and check that when user click on the Panel header are they click on the Primary Button or outside of it.

    Try this:

    import React, { useState, useRef } from "react";
    import * as antd from "antd";
    
    const { Collapse, Button } = antd;
    const { Panel } = Collapse;
    
    const text = ` hi `;
    export const App = () => {
      const [activeKey, setActiveKey] = useState(0);
      const isButtonClicked = useRef(false);
    
      const callback = key => {
        console.log(key, isButtonClicked.current);
        // Check if use click on the button don not update activekey
        if (
          isButtonClicked &&
          isButtonClicked.current &&
          isButtonClicked.current === true
        ) {
          isButtonClicked.current = false;
          return;
        }
    
        if (!activeKey) {
          setActiveKey(key);
        } else {
          setActiveKey(0);
        }
      };
      return (
        <Collapse activeKey={activeKey} onChange={callback}>
          <Panel
            header={
              <Button
                onClick={() => {
                  // set the isButtonClicked ref to tru when user click on Button
                  isButtonClicked.current = true;
                  // Do other functionality you want for this button here
                }}
                type="primary"
              >
                Primary Button
              </Button>
            }
            key="1"
          >
            <Button type="link">My button</Button> ><p>{text}</p>
          </Panel>
        </Collapse>
      );
    };

    I create a codesandbox to demonstrate it