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 ?

Upvotes: 2

Views: 762

Answers (2)

Syed Ali Shahzil
Syed Ali Shahzil

Reputation: 1224

Pass the function to props and call it

 <ClientCard passfunction={myfunction1}/>

and use it like that

    const clientCard = ({ client, passfunction }) => (
        <div onClick={() => { passfunction() }}>
            <Card className="text-center card-mine" >
                <Card.Header>Header</Card.Header>
                <Card.Body >Body</Card.Body>
                <Card.Footer >Footer</Card.Footer>
            </Card>
        </div>
    );
    
    export default clientCard;

Upvotes: 0

Carol Skelly
Carol Skelly

Reputation: 362700

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

Upvotes: 1

Related Questions