Home > Mobile >  Trying to change my image - ADD to ADDED when onclick on the img, no idea how to go about it. I am n
Trying to change my image - ADD to ADDED when onclick on the img, no idea how to go about it. I am n

Time:11-23

import React, { useState } from 'react';
import NavBar from "../../components/navBar/navbar";
import "./profile.scss"
import add from './Images/add.png'
import added from './Images/added.png'

    
const Profile = () => {

    return (

    <div className="navbar-display">

        <NavBar/>

                                <div className="right" >
                                <img id='imageid' src={add} alt='' onClick={''}/>
                                </div>
           



    </div>
    )
}

export default Profile;
                                <div className="right" >
                                <img id='imageid' src={add} alt='' onClick={''}/>
                                
                                </div>

This is the section im having troubles with. Ive tried lots of online methods but constantly ran into errors and cant seem to find a definitive way to onclick change image with ReactJS

CodePudding user response:

just simply use the useState to keep track of your image, something like this:

import React, { useState } from "react";
import NavBar from "../../components/navBar/navbar";
import "./profile.scss";
import add from "./Images/add.png";
import added from "./Images/added.png";

const Profile = () => {
  const [image, setImage] = useState("left");

  const handleClick = () => {
    if (image === "left") {
      setImage("right");
    } else {
      setImage("left");
    }
  };

  return (
    <div className="navbar-display">
      <NavBar />

      <div className="right">
        <img
          id="imageid"
          src={image === "left" ? add : added}
          alt=""
          onClick={() => handleClick()}
        />
      </div>
    </div>
  );
};

CodePudding user response:

I ended up fixing this issue by using state as above mentioned like this. Thank you for the reply <3

const [isFollowed, setIsFollowed] = useState(false);
const [isFollowedtext, setIsFollowedtext] = useState(false);

const followHandler = () => {
        setIsFollowed(!isFollowed);
        setIsFollowedtext(!isFollowedtext);
      };

<div className="right" onClick={followHandler}>
{isFollowed ? 
<p>Connected with user!</p> : <p>Connect with user!</p>}

{isFollowedtext ? 
<img src={added} alt="" /> : <img src={add} alt="" />}
</div>
  • Related