Home > Mobile >  Prevent onClick event on dynamically created elements
Prevent onClick event on dynamically created elements

Time:08-14

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>
);

CodePudding user response:

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.

  • Related