简体   繁体   中英

How to change image on button after click reactJs

I have a save button with an image (bordered icon). I want to change icon color on button click is success

const saveClickProperty = () => {
    console.log("test");
    if(userId) {
        setLoading(true);
        propertyUserSave({
            userId: userId,
            propertyId: property._id
        }).then((resp) => {
            console.log("hello");
            openNotification("", "Property Saved");
            if (isSuccess(resp)) {
                console.log("inside");
                openNotification(userMessage.successHeader, userMessage.propertySaved);  
            }
        }).finally(() => setLoading(false));
    }
}

and i want to change save.png

<div className="saveAction">
                {userId && 
                    <a onClick={saveClickProperty} className="">
                        <div className="ActionDiv">
                            <img src="/images/index/save.png" alt="save" /> {' '} Save
                        </div>
                    </a>
                }

            </div>

right now this is look like在此处输入图像描述

Any idea to change save.png image color after button click (i mean when property is successfully saved).

A possible solution is to create a state and after the property is saved, change that state, in order to the components (icon colors and image) re-render.

Example for State:

const [success, setSucess] = useState(false);

Example for Image:

const sucessImage = <img src="/images/index/NEWIMAGE.png" alt="save" />;
const defaultImage = <img src="/images/index/save.png" alt="save" />;

    <div className="saveAction">
                    {userId && 
                        <a onClick={saveClickProperty} className="">
                            <div className="ActionDiv">
                                ${success ? sucessImage : defaultImage} {' '} Save
                            </div>
                        </a>
                    }

                </div>

Example of changing the state:

...
        }).then((resp) => {
            setSucess(true);
            console.log("hello");
            openNotification("", "Property Saved");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM