Raushan Singh
Raushan Singh

Reputation: 105

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 enter image description here

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

Upvotes: 0

Views: 2187

Answers (1)

Lucas L.
Lucas L.

Reputation: 437

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

Upvotes: 2

Related Questions