how to use onClick while mapping

Viewed 54

can someone help me for correcting this code I want use onClick on the data i map but the onClick runs every time the page render. :| i mean it doesn't run when i click but it runs every time the page render. please check the CollectionOption part

import React, {useState, useEffect} from "react";
import axios from "axios";
import ModalSubHeader from "../../styles/ModalSubHeader";
import CollectionHolder from "../../styles/CollectionHolder";
import {CollectionOption, CollectionOptionInner} from "../../styles/CollectionOption";
import CollectionIcon from "../../styles/CollectionIcon";
import CollectionIcons from "../../../../images/index";

function Collection(props) {
    
    const [collectionList, setCollectionList] = useState(null);
    useEffect(() => {
        axios
        .get("https://reg.my-waste.mobi/collections?project_id=556&district_id=556&zone_id=zone-z1250-z1261")
        .then(({data}) => {

            const collections = Object.values(data.collection.types).map(collection =>
                <CollectionOption onClick={props.onChoosed(collection.title)}>
                    <CollectionOptionInner> 
                        <CollectionIcon 
                        src={CollectionIcons.CollectionIcons[collection.iconicShape]} 
                        color={"#" + collection.colour} />
                    </CollectionOptionInner>
                        
                    <CollectionOptionInner>
                        {collection.title}
                    </CollectionOptionInner>
                </CollectionOption>
            );

            setCollectionList(collections)
        })        

        
        console.log(CollectionIcons);
    }, [])

    return(
        <div>
            <ModalSubHeader>What type of collection or event would you like to be reminded about?</ModalSubHeader>
            <CollectionHolder>
                {collectionList}
            </CollectionHolder>
        </div>
    )
}

export default Collection;
2 Answers

This is because you are explicitly calling the onClick handler immediately when the map is executed.

Instead you should pass a callback function to execute it when the onClick event actually happens:

 <CollectionOption onClick={() => props.onChoosed(collection.title)}>

Also consider using a key in the <CollectionOption key={collection.id} .../> that way you can avoid unnecessary re-renders.

The way you've provided the function it will be called immediately when the map function is executed ie. when the component gets rendered.

You need to pass a callback instead so that the onChoosed function will be called only when you click the CollectionOption.

So, use:

<CollectionOption onClick={() => props.onChoosed(collection.title)}>

Instead of:

<CollectionOption onClick={props.onChoosed(collection.title)}>
Related