skip to Main Content

I am developing single component toggle module, Currently I am facing one issue. I have populated data in list but in the center of data are populated as per the requirements.

import { useState } from "react";

const data = [{
    "postId": 1,
    "id": 1,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "body": "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et"
}, {
    "postId": 2,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "body": "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et"
}, {
    "postId": 3,
    "id": 3,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "body": "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et"
},];
export default function Test() {
    const [show, setShow] = useState([]);
    console.log('show ==> ', show);
    return (
        <div>
            {data.map((item, i) => (
                <div key={i}>
                    <button onClick={() => {
                        if (show[i] === i) {
                            const item = [...show];
                            const final = item.splice(item.indexOf(i), 1)
                            setShow(final);
                        } else {
                            setShow(prev => [...prev, i]);
                        }
                    }}>Toggle</button>
                    {show[i] === i ? 'SHOW' : 'HIDE'}
                    <hr />
                </div>
            ))}
        </div>
    );
}

Could you please support me ?

I have created array list state,

3

Answers


  1. Try this;

    const [allData, setAllData] = useState(data.map(x => {...x, visible: true });
    
    const toggle = (id: number) => {
      const copy = allData;
    
      copy.forEach(x => {
        if (x.id === id) {
          x.visible = !x.visible
        }
      }
    
      setAllData(copy)
    }
    
    return (
    <div>
        {allData.filter(x => x.visible).map((x, i) => (
          <div key={i}>
            <p>{x.name}</p>
            <p>{x.email}</p>
            <p>{x.body}</p>
            <button onClick={toggle(x.id)}>{x.visible ? 'Show' : 'Hide' }</button>
          </div>)
        )}
    </div>)
    
    Login or Signup to reply.
  2. could you try this way?

    example

    let me know if it is missing what you want

    import { useState } from "react";
    
    const data = [
      {
        postId: 1,
        id: 1,
        name: "quo vero reiciendis velit similique earum",
        email: "[email protected]",
        body:
          "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et"
      },
      {
        postId: 2,
        id: 2,
        name: "quo vero reiciendis velit similique earum",
        email: "[email protected]",
        body:
          "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et"
      },
      {
        postId: 3,
        id: 3,
        name: "quo vero reiciendis velit similique earum",
        email: "[email protected]",
        body:
          "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et"
      }
    ];
    export const Test = () => {
      const [show, setShow] = useState([]);
      const handleSelect = (id) => {
        const isHas = show.find((item) => item === id);
        if (isHas) {
          const filtered = show.filter((item) => item !== id);
          setShow(filtered);
        } else {
          setShow([...show, id]);
        }
      };
      const isSelected = (id) => !!show.find((item) => item === id);
      return (
        <div>
          {data.map((item, i) => (
            <div key={i}>
              <button onClick={() => handleSelect(item?.id)}>
                <span>Toggle</span>
              </button>
              {isSelected(item.id) ? <span>HIde</span> : <span>Show</span>}
              <hr />
            </div>
          ))}
        </div>
      );
    };
    
    
    Login or Signup to reply.
  3. Try this code.

    import { useState } from "react";
    
    const data = [
      {
        postId: 1,
        id: 1,
        name: "quo vero reiciendis velit similique earum",
        email: "[email protected]",
        body: "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et",
      },
      {
        postId: 2,
        id: 2,
        name: "quo vero reiciendis velit similique earum",
        email: "[email protected]",
        body: "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et",
      },
      {
        postId: 3,
        id: 3,
        name: "quo vero reiciendis velit similique earum",
        email: "[email protected]",
        body: "est natus enim nihil est dolore omnis voluptatem numquamnet omnis occaecati quod ullam atnvoluptatem error expedita pariaturnnihil sint nostrum voluptatem reiciendis et",
      },
    ];
    
    export default function App() {
      const [show, setShow] = useState([]);
    
      const toggleShow = (index) => {
        setShow((prevShow) => {
          const updatedShow = [...prevShow];
          const showIndex = updatedShow.indexOf(index);
          if (showIndex > -1) {
            updatedShow.splice(showIndex, 1); // Hide the item
          } else {
            updatedShow.push(index); // Show the item
          }
          return updatedShow;
        });
      };
    
      return (
        <div>
          {data.map((item, index) => (
            <div key={index}>
              <button onClick={() => toggleShow(index)}>
                {show.includes(index) ? "Hide" : "Show"}
              </button>
              {show.includes(index) ? (
                <div>
                  <p>Name: {item.name}</p>
                  <p>Email: {item.email}</p>
                  <p>Body: {item.body}</p>
                </div>
              ) : null}
              <hr />
            </div>
          ))}
        </div>
      );
    }
    

    Here is the output:
    enter image description here
    Let me know, if you’ve any doubts!!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search