trying to create a button in the component that sorts the array of objects by each objects name alphabetically and renders in component when clicked
menuItems = [{name: pizza}, {name: burger}]
class MenuItems extends Component {
handleclick = (item) => {
this.props.deleteMenuItem(item.id);
}
render(){
return (
<div>
<button onClick={this.handlechange}>filter a to z</button>
{this.props.menuItems.map((item) =>(
<li class="list" key={item.id}>
{item.name}
<br></br>
{item.body}
<br></br>
<img src={item.image}></img>
<br></br>
<button id={item.id} onClick={() => this.handleclick(item)}>delete </button>
</li>
))}
</div>
)
}
}
export default connect(null, {deleteMenuItem})(MenuItems)```
CodePudding user response:
you could try this
menuSort = () => {
const newMenuItems = { ...this.props.menuItems };
newMenuItems.sort((a, b) => a.name.localeCompare(b.name));
this.setState({MenuItems: newMenuItems });
};
The localeCompare() method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.
then use MenuItems in your render function, like you already have