Home > front end >  Show/Hide div onClick
Show/Hide div onClick

Time:10-14

I currently have my toggle action in place but the only help I need is that, I would like to close the div as well, like an toggle action. The one that I've currently done is that once I click on another div element the previous one that has been clicked closes, but I'd rather prefer that I have an toggle action on closing and opening on the div element being clicked, without needing to click on another just to close the previous div, I've only grabbed the parts that are needed in the code, just to prevent on copying and pasting the whole file, just to save time on reading.

Code Snippet

  const [posts, setPosts] = useState([]);
  const [commentState, commentChange] = useState({
    activeObject: null
  });

  const toggleComment = (index) => {
    commentChange({...commentState, activeObject: posts[index]})
  }

  const toggleActiveStyles = (index) => {
    if(posts[index] === commentState.activeObject) {
      return "dashboard__commentContent toggle";
    } else {
      return "dashboard__commentContent";
    }
  }


 return error ? (
    <span>{error}</span>
  ) : (
  
  {posts.map((post, i) => (
       <button onClick={() => toggleComment(i)} >toggle</button>


       <div className={toggleActiveStyles(i)}>
           <h1>{post.title}</h1>
       </div>
  )}

CodePudding user response:

Here is a working codesandbox that you can manipulate to fit to your needs.

Explanation

You would want to keep track of toggled divs and make sure to adjust your class based on that. You can filter out or add to the toggled divs state variable, and do whatever you want while rendering.

Code

import { useState } from "react";
import "./styles.css";

const DATA = ["1", "2", "3", "4"];

export default function App() {
  const [closedDivs, setClosedDivs] = useState([]);

  const toggleDiv = (i) => {
    setClosedDivs((divs) =>
      divs.includes(i) ? divs.filter((d) => d !== i) : [...divs, i]
    );
  };

  return (
    <div className="App">
      {DATA.map((d, i) => (
        <div
          className={`${closedDivs.includes(i) ? "close" : ""} box`}
          onClick={() => toggleDiv(i)}
        >
          <p> {d} </p>
        </div>
      ))}
    </div>
  );
}
  • Related