Here is how I would do it:
import React, { useState } from "react";
import img5 from "../../Assets/Ground.png";
import img6 from "../../Assets/First.png";
import img7 from "../../Assets/Second.png";
const Location = () => {
const [imageClicked, setImageClicked] = useState({
first: false,
second: false,
ground: false
});
const onClickHandler = (order) => {
setImageClicked((prevState) => ({
...prevState,
[order]: !prevState[order]
}));
};
return (
<div>
<div className="Ccontainer">
<button onClick={() => onClickHandler("ground")} className="ground">
Ground Floor
</button>
<button onClick={() => onClickHandler("first")} className="ground">
First Floor
</button>
<button onClick={() => onClickHandler("second")} className="ground">
Second Floor
</button>
</div>
<div className="image">
{imageClicked.ground && <img src={img5} alt="ground" />}
{imageClicked.first && <img src={img6} alt="first" />}
{imageClicked.second && <img src={img7} alt="second" />}
</div>
</div>
);
};
export default Location;
I do not have the assets, but feel free to add them here and play with the solution.
With a little bit of details, we use the imageClicked state to save the state of clicked/unclicked for each image.
const [imageClicked, setImageClicked] = useState({
first: false,
second: false,
ground: false
});
We use the onClickHandler as the onClick function that gets the corresponding image key and use it to update only this part of the state object with the opposite of it it has been before, so if it was true it will be false and vice versa.
const onClickHandler = (order) => {
setImageClicked((prevState) => ({
...prevState,
[order]: !prevState[order]
}));
};
With this state we condition the rendering of the image so it will only show if imageClicked.X where X is first/second/ground
<div className="image">
{imageClicked.ground && <img src={img5} alt="ground" />}
{imageClicked.first && <img src={img6} alt="first" />}
{imageClicked.second && <img src={img7} alt="second" />}
</div>
If you want only one image to appear at a time please use this onClick function instead, to make all image state to false other than the clicked image.
const onClickHandler = (order) => {
const resetImages = {
first: false,
second: false,
ground: false
}
setImageClicked({
...resetImages,
[order]: true
});
};