How to show html filter/map array with Onclick in React

I am attempting to show a filtered array though onClick event in React. I would like the li tag to only show when the Button is clicked. I get no error message but nothing is populated when i click my Button

Essentially I would like to render my li tag with the filtered results and show it on my page when Button is clicked

class SmoothieFilter extends React.Component {
    smoothie = () => {
        const smoothieNames = ["tasty", "chocolate", "yummy", "strawberry", "banana", "blueberry", "raspberry", "mango" ];
        smoothieNames.filter(faves => faves.includes("yummy")).map(faveSmoothie => (
            <li>{faveSmoothie}</li>
        ));
    }

    render() { 
        return (
            <Button variant="dark" onClick={this.smoothie}>CLICK ME</Button>
        )
    }
}

export default SmoothieFilter;

Any ideas?

8 thoughts on “How to show html filter/map array with Onclick in React”

  1. First, we need to track if the button was clicked or not (we can use a state property to track it, eg. clicked)
    Second, we need to return in the render also the LIs so it will be attached to the DOM, in your example it doesn’t do anything
    I have rewritten the your script a bit

    import React from 'react';
    
    class SmoothieFilter extends React.Component {
    
        constructor(props) {
            super(props);
            this.state = {
                clicked: false,
            };
        }
    
        smoothie = () => {
            if (this.state.clicked !== true) {
                return;
            }
            const
                nodes = [],
                smoothieNames = ["tasty", "chocolate", "yummy", "strawberry", "banana", "blueberry", "raspberry", "mango"];
    
            smoothieNames.filter(faves => faves.includes('yummy')).map(faveSmoothie => (
                nodes.push(<li key={faveSmoothie}>{faveSmoothie}</li>)
            ));
            console.log('return', nodes, smoothieNames.filter(faves => faves === 'yummy'));
            return <ul>{nodes}</ul>;
        }
    
        render() {
            return (<div>
                <div className="a-button" variant="dark" onClick={() => {
                    this.setState({clicked: true})
                }}>CLICK ME
                </div>
                {this.smoothie()}
            </div>);
        }
    }
    
    export default SmoothieFilter;
    Reply

Leave a Comment