Search code examples
reactjsmernbootstrap-5card

How to call a function when a Card is Clicked - MERN Stack


I want to call a function when the user click on a Card (I have used Card from react-bootstrap). I tried putting an onclick function but it is not working.

clientCard.js

import React from "react";
import Card from 'react-bootstrap/Card'
import DeleteOutlineIcon from '@material-ui/icons/DeleteOutline';
import EditOutlinedIcon from '@material-ui/icons/EditOutlined';

const clientCard = ({client}) => (

    <Card className="text-center card-mine" >
        <Card.Header>{client.clientFirstName} {client.clientLastName}</Card.Header>
        <Card.Body >
            <Card.Text >
            {client.clientContactNumber}
            <br></br>
            {client.clientEmail}
            </Card.Text>
        </Card.Body>
        <Card.Footer >
            <button className="btn btn-info ClientEditBtn">
                <DeleteOutlineIcon></DeleteOutlineIcon>
            </button>
            <button className="btn btn-info ClientDeleteBtn">
                <EditOutlinedIcon></EditOutlinedIcon>
            </button>
        </Card.Footer>
    </Card>

);

export default clientCard;

I have imported the Client card into my main file and displayed it. This is how I called the function.

<ClientCard onClick={() => {function1()}}/>

Can you please help me on how I can call a function when user clicks on the card ?


Solution

  • You can pass the onClick function as a prop to the child (ClientCard) from the calling (parent) component..

    const ClientCard = (props) => {
        return (
            <Card className="text-center card-mine" onClick={props.onClick}>
                <Card.Header>
                    Header
                </Card.Header>
                <Card.Body>
                    Body
                </Card.Body>
            </Card>
        )
    };
    
    const Example = (props) => {
      return (
        <div>
            <ClientCard onClick={()=>{alert('clicked!')}} />
        </div>
      );
    }
    
    ReactDOM.render(
      <Example />,
      document.getElementById('root')
    )
    

    react-bootstrap on Codeply