Search code examples
reactjsantd

Antd how to do onClick on List or Card action?


Hi i can't figure out how to set up the onclick function for the action below for Antd Card. Could someone help me pls? thanks.

const expand = () =>{
    console.log("expand")
  }

const IconText = ({ icon, text, cb }) => (
    <Space>
      <div onClick={e => cb}>
      {React.createElement(icon)}
      {text}
    </div>
    </Space>
  );


<Card style={{ width: props.width, height: props.height }}

    actions={[
     <IconText icon={ExpandOutlined} text="Expand" key="list-vertical-star-o" cb={()=>expand}/>,
     <IconText icon={MessageOutlined} text="Comments" key="list-vertical-like-o" />,
       ]}
    >

https://ant.design/components/card/


Solution

  • see the callbacks ( Working codesandbox)

    cb = {
      () => {
        expand("Comments");
      }
    }

    also while binding:

    <div onClick={e=> cb}>

    import React from "react";
    import ReactDOM from "react-dom";
    import "antd/dist/antd.css";
    import "./index.css";
    import { Card, Avatar, Space } from "antd";
    import {
      EditOutlined,
      EllipsisOutlined,
      SettingOutlined
    } from "@ant-design/icons";
    
    const { Meta } = Card;
    
    const IconText = ({ icon, text, cb }) => (
      <Space>
        <div onClick={cb}>
          {/*React.createElement(icon)*/}
    
          {text}
        </div>
      </Space>
    );
    
    const expand = (text) => {
      console.log("expand", text);
    };
    
    ReactDOM.render(
      <Card
        style={{ width: 300 }}
        cover={
          <img
            alt="example"
            src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
          />
        }
        actions={[
          <IconText
            text="Expand"
            key="list-vertical-star-o"
            cb={() => {
              expand("Comments");
            }}
          />,
          <IconText text="Comments" key="list-vertical-like-o" />,
    
          <SettingOutlined key="setting" />,
          <EditOutlined key="edit" />,
          <EllipsisOutlined key="ellipsis" />
        ]}
      >
        <Meta
          avatar={
            <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />
          }
          title="Card title"
          description="This is the description"
        />
      </Card>,
      document.getElementById("container")
    );