I'm new to React and I'm trying to sort an array of objects by name is ascending and descending order. I'd also like the sorting to start as soon as the DOM renders hence why I'm using componentDidMount().
The problem I'm having is when you select 'Z - A' option from the dropdown. For some reason the sorting function doesn't work first time then when you select 'A - Z' it's ordering in the opposite order. Any ideas where I'm going wrong? been at this for weeks and I'm completely stumped.
For componentDidMount() are you supposed to call custom functions like that or should I be doing it differently?
Thanks
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.updateValue = this.updateValue.bind(this);
this.sortData = this.sortData.bind(this);
this.state = {
people: [
{ name: 'Abi', age: 18 },
{ name: 'Britney', age: 22 },
{ name: 'Carol', age: 52 },
{ name: 'Danni', age: 17 },
],
sortBy: 'AZ'
}
}
sortData() {
if (this.state.sortBy === 'AZ') {
this.setState((prevState) => {
return {
people: prevState.people.sort((a, b) => a.name > b.name ? 1 : -1)
}
});
}
else if (this.state.sortBy === 'ZA') {
this.setState((prevState) => {
return {
people: prevState.people.sort((a, b) => b.name > a.name ? 1 : -1)
}
});
}
}
updateValue(event) {
const value = event.target.value;
console.log(value);
this.setState(() => {
return {
sortBy: value
}
});
this.sortData();
}
componentDidMount() {
this.sortData();
}
render() {
return (
<div>
<p>{ this.state.sortBy }</p>
<select value={ this.state.sortBy } onChange={ this.updateValue }>
<option value="AZ">A - Z</option>
<option value="ZA">Z - A</option>
</select>
<ul>
{ this.state.people.map((person) => <li key={person.name}>{ person.name }</li>) }
</ul>
</div>
);
}
};
const root = document.querySelector('#appRoot');
ReactDOM.render(<App/>, root);