I am trying to call the handleClick method whenever the user clicks on the button, but nothing on the page will render and I get the error "Uncaught ReferenceError: handleClick is not defined".
Implementation of the component:
import {createElement} from 'react';
import {add} from '../action/cart';
import {connect} from 'react-redux';
import styles from './styles.css';
handleClick = (id) => {
add(id);
this.setState((prevState) => ({
...prevState,
items: prevState.items.map(
(item) =>
id === item.id
? {id, quantity: item.quantity + 1}
: {...item}
),
}));
};
const Product = ({add, id, title, image}) => (
<div className={styles.product} onClick={handleClick(id)}>
<img src={image} alt={title} className={styles.productImage}/>
{title}
</div>
);
export default connect(() => ({}), {add})(Product);
This shares state with the cart component:
const Cart = connect(
() => ({}),
{clear}
)(({items, clear, total}) => {
return (
<div>
<Heading><FontAwesomeIcon icon={faShoppingCart} /> Cart</Heading>
{items.length ? <button onClick={clear}>Clear all items</button> : null}
<table>
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
{items.map(({...item}, id) => (
<Item {...item} key={id} />
))}
</tbody>
</table>
{items.length ?
<div className={styles.total}>${total}</div>
: <div>Your cart is empty!</div>}
</div>);
});
export default connect((state) => {
return {
items: state.cart.items,
total: reduce(
(sum, {id, quantity}) => sum + products[id].price * quantity,
0,
state.cart.items
).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,'),
};
})(Cart);
It references this action:
import {ADD_ITEM, SET_QUANTITY, CLEAR_ITEMS} from './types';
import {createAction} from 'redux-actions';
export const add = createAction(ADD_ITEM);
export const setQuantity = createAction(SET_QUANTITY);
export const clear = createAction(CLEAR_ITEMS);
Which uses this reducer:
[ADD_ITEM]: (state, {payload: id}) => ({
...state,
items: [
...state.items,
{id, quantity: 1},
],
}),