Kevin Nett
Kevin Nett

Reputation: 429

How to undo OnClick function on second click in ReactJS

I have coded a OnClick function that opens a window with a detailed description of the selected object.

However, the window always remains open and to remove it you have to refresh the page. I would like to make sure that at the second click the page returns as before by undoing the function called at the first click.

   const setActiveTutorial = (tutorial, index) => {
        setCurrentTutorial(tutorial);
        setCurrentIndex(index);
      };

...

                    {tutorials &&
                      tutorials.map((tutorial, index) => (
                        <TableRow
                          className={
                            "list-group-item " + (index === currentIndex ? "active" : "")
                          }
                          onClick={() => setActiveTutorial(tutorial, index)}
                          key={index}
                        >
                          <TableCell>{tutorial.title}</TableCell>
                          <TableCell>{tutorial.size}</TableCell>
                          <TableCell>{tutorial.country}</TableCell>
...

Upvotes: 1

Views: 449

Answers (1)

WebbH
WebbH

Reputation: 2422

If you want to use the same function, you can just add a conditional where if currentTutorial already has a value, then it closes the page

 const setActiveTutorial = (tutorial, index) => {
    if(currentTutorial === tutorial){
      setCurrentTutorial(null)
      set setCurrentIndex(-1) //or whatever initial value
    }
    else{
      setCurrentTutorial(tutorial);
      setCurrentIndex(index);
  };

This assumes you can't click on another tutorial while the current one is active.

Upvotes: 1

Related Questions