EDIT I need to sort team cards alphabetically inside my Container component with a button. At the moment the code sorts alphabetically without the button being pressed since I have the sorting logic being mapped to state. Syntax wise, how should I have it only sort when button is clicked and where should the sorting itself be done here?
I have previously had the sorting being done using a reducer case and an action but now want to do it without using actions or reducers and just using React.
Container which displays the Cards:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { NavLink } from 'react-router-dom';
import TeamCard from '../components/TeamCard'
import { displayObject } from '../actions/dataActions'
import CardColumns from 'react-bootstrap/CardColumns'
class DataContainer extends Component {
state = {
teamCards: [...this.props.teams.cards]
};
sortTeamCards = () => {
this.setState(prevState => ({
teamCards: [...prevState.teamCards].sort(function(team1, team2) {
if (team1.name < team2.name) {
return -1;
}
if (team1.name > team2.name) {
return 1;
}
return 0;
}),
}))
}
displayCards = () => {
switch(this.props.path) {
case "teams":
return (this.props.teams.cards.map(card => (
<NavLink style={{ color: "black" }} to={`/teams/${card.id}`} key={card.id}><TeamCard view={this.props.displayObject} info={card} /></NavLink>
)));
default:
return (<div>Empty</div>)
}
};
render() {
return (
<CardColumns>
<button id="sort-button" title="Sort Teams" onClick={this.sortTeamCards}>Sort Teams</button>
{this.displayCards()}
</CardColumns>
)
}
}
const mapStateToProps = state => {
return {
teamCards: state.teams,
teams: state.teams
}
};
const mapDispatchToProps = dispatch => {
return {
displayObject: (id, category, type) => dispatch(displayObject(id, category, type)),
}
};
export default connect(mapStateToProps, mapDispatchToProps)(DataContainer)
handleTeamSortnot correctly sorting/updating component state? Is the button'sonClickhandler not callinghandleTeamSort? The two buttons aren't rerendering? (They don't change depending on state so when they do rerender they look the same) Seems there's an implied question in there somewhere. How doesTeamFilterrelate toDataContainer?fetchTeamsconnected to your component? I see it referenced within asthis.props.fetchTeams. What does that action ultimately do? Presumably populate something intothis.state.teams? Far as I can tell from what is shared,this.state.teamsis an empty array.