I'm pretty new to React and JS, and I'm having trouble calling a function in my component with a button click. I want to call the sort function with a click event on my button, but right now the sort function is being called immediately after render. How can sort onClick with my button. Any help would be appreciated. Thanks!
import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchCards } from "../actions/cardActions";
import Card from "../components/Card";
class CardList extends Component {
componentDidMount() {
this.props.fetchCards();
}
sortCards = cards => {
cards.sort(function(a, b) {
return a.front > b.front;
});
};
render() {
const cards = this.props.cards;
return (
<div className="CardList">
<button onClick={this.sortCards(cards)}>Sort Cards</button>
{cards.map(card => (
<Card
key={card.id}
cardId={card.id}
front={card.front}
back={card.back}
/>
))}
</div>
);
}
}
const mapStateToProps = state => {
return {
cards: state.card.all
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
fetchCards: () => {
dispatch(fetchCards(ownProps.deckId));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(CardList);