user4674659
user4674659

Reputation:

Toggle property of different states

Small question here. I have 3 div classes that contain images that I want to toggle the state property for each picture every time a user presses on one of the images (div actually). The states are as follows:

  constructor(props) {
    super(props);

    this.state = {
      img_1: 0,
      img_2: 0,
      img_3: 0
    };
  }

And I want to have a single handle function that can toggle for all the different images that I have. Here is the div code (its the same for every image):

<div className="pics" onClick={(e) => this.handlePic(e)}>
  <h2>First picture</h2>
  <img alt="" src={pic1} className="tier2"/>
</div>

And The handle function is empty at the moment, because I have no idea how to pass into it the name of this.state.img_1. The value of course should toggle between 0 and 1, but I want to be able to use a single function for the toggle of all 3 images. I am not sure if my question makes a lot of sense, please let me know if you want me to explain a little bit more of my situation.

Thank you!

Upvotes: 0

Views: 39

Answers (3)

Meet Zaveri
Meet Zaveri

Reputation: 3059

Here is the solution if you are not using hooks then,

In render method(passing static string in parameter for handler method):

<div className="pics" onClick={e => this.handlePic('img1')}>
    <h2>First picture</h2>
    <img alt="" src={pic1} className="tier2" />
</div>

Your handler(Setting dynamic key):

handlePic = key => {
    this.setState(prevState => ({ [key]: !prevState[key] })); // This will toggle 0 or 1 simultaneously.
};

Upvotes: 0

behzad
behzad

Reputation: 857

You have 3 different div, in each of your dives define an onClick={()=>this.myhandle(nameofpic)} (you can hardcode nameofpic here,for example in each div put a name like "img1","img2" ... instead of nameofpic) Then in your myhandle() put your ifs ,like this :

myhandle(nameofpic){
if(nameofpic==="img_1")
 {this.setState({img_1:"valuechange"})
  } 
if(nameofpic==="img_2")
 {this.setState({img_2:"valuechange"})
 }
if(nameofpic==="img_3")
 {this.setState({img_3:"valuechange"})
 }}

I hope you get the idea and works for you

Upvotes: 1

Sandip Nirmal
Sandip Nirmal

Reputation: 2459

You should create a separate component for Image, which will handle it's own state. This way you can manage any number of Images not just 3.

function Image({url}) {
const [overlay, setOverlay] = useState(false);

const toggleState = () => {
setOverlay(!overlay)
}

return <img src={url} alt={url} onClick={toggleState} />
}

Here overlay can be anything.

Now you can use this component any number of time and it will have it's own state management.

Upvotes: 0

Related Questions