Search code examples
javascriptreactjsfunctiononclickhandler

onClick function is not working as expected in React component


So i have this component ExpenseItem. Im trying to use onClick on the sub component Card. First i tried putting an arrow function inside the brackets, but it didn't work. Then i initialized the arrow function outside the return and tried to put the function inside the onClick brackets, but im not sure why its still not working. Here's the code:

import React from 'react';
import '../styles/ExpenseItem.css';
import ExpenseDate from './ExpenseDate';
import Card from '../Card.jsx';

const ExpenseItem = (props) => {
  
    const clickHandler = () => alert('im working');

    return (

        <Card className='expense-item' onClick={clickHandler}>
            <div>
                <ExpenseDate date={props.date} />
            </div>
            <div className='expense-item__description'>
                <div className='expense-item__descbox'>
                    <h2>{props.title}</h2>
                    <span>{props.type}</span>
                </div>
                <div className='expense-item__price'>{props.amount}</div>
            </div>
        </Card>
    )
};

export default ExpenseItem;


Thanks.


Solution

  • You also need to implement onClick on your Card component.

    you can do something like below to your Card:

    const Card = (props) => {
      return (
        <div className="card" {...props}>{props.children}</div>
      );
    }
    

    OR

    const Card = (props) => {
      return (
        <div className="card" onClick={props.onClick}>{props.children}</div>
      );
    }