how to toggle between two list of arrays with one button react js

looking for advice on how to have one button that when clicked will switch the … Read more how to toggle between two list of arrays with one button react js

looking for advice on how to have one button that when clicked will switch the list of items to the alphabetized list of items and back when clicked again and so on. as of right now when i click the button it will show the alphabetized list but its just rendering on top of the original list already showing. not really sure on where to go from here

class MenuItems extends Component {

    state = {
        sortedItems: []
    }

    handleclick = (item) => {
        this.props.deleteMenuItem(item.id);
    }

    menuSort = () => {
         const ogList = [...this.props.menuItems]
        let sortedList = ogList.sort((a, b) => a.name.localeCompare(b.name));
        this.setState({sortedItems: sortedList})
    };

    render(){
        return ( 
            <div>
                <button onClick={this.menuSort}>filter a to z</button>

                {this.state.sortedItems.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>
                ))}

                
                {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)```

Source: JavaSript – Stack Overflow


Categories: NewsTags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *