Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Prevent onClick event on dynamically created elements

I’am fetching data from a database table into my react app. With the elements from the table I render dynamically buttons and this buttons should have a onClick event. Because of the map function the onClick event is fired as often as elements are stored in the database table. So my question is if it is possible to prevent the firing of onClick at dynamically creation?

//GET request with axios
const getColorHandler = () => {
    httpInstance
        .get("/api/color")
        .then(res => {
            console.log(res.data);
            setColorData(res.data);
        }).catch(err => {
            setColorData(null);
            console.log(err);
        })
};

//JSX
return(
    <section className="uk-flex">
        {colorData.map(color=> (
            <div className="uk-flex-row" key={color.id}>
                <div onClick={setColorHandler(color.type, color.price)}
                     className={
                            (color.id === 1 ? "greyColor" : "") ||
                            (color.id === 2 ? "redColor" : "") ||
                            (color.id === 3 ? "blueColor" : "") ||
                            (color.id === 4 ? "greenColor" : "")
                     }
                ></div>  
            </div>
        ))}
    </section>
);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your use of onClick si fired immediately, as you’ve experienced.
If you want to use true onClick event, then you have to have your event this way:

<div onClick={() => setColorHandler(color.type, color.price)}

Or, if you woudl want to use event information:

<div onClick={(e) => setColorHandler(color.type, color.price)}

Small under the line notice: using clickable <div> is antipattern, you could have aria accessibility issues. Better use <button> element.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading