Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Toggle element data for element that I click on, not all elements

I want to toggle data for specific element I click on. Whenever I try to display element data then all items are toggling which I do not want. How can I only toggle the item I click on?

  const [displayToggles, setDisplayToggles] = useState([]);
...
   {post.map((item, i) => (
        <div key={item.id}>
          <p>{item.title}</p>
          <button
            onClick={() =>
              setDisplayToggles(
                displayToggles.map((bool, j) => (j === i ? !bool : bool))
              )
            }
          >
            Show ID
          </button>
          {displayToggles[i] && <p>{item.id}</p>}
        </div>
      ))}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You want to be able to show or hide each item of the array separately, so your state should reflect that – it should contain a value for each element of the array, instead of having just a single displayId boolean.

const [displayToggles, setDisplayToggles] = useState([]);
const getPosts = () => {
  fetch("https://jsonplaceholder.typicode.com/posts")
    .then((res) => res.json())
    .then((res) => {
      setPosts(res);
      setDisplayToggles(res.map(() => false));
    });
};

// ...
{post.map((item, i) => (
    <div key={item.id}>
    <p>{item.title}</p>
    <button
        onClick={() => setDisplayToggles(displayToggles.map((bool, j) => j === i ? !bool : bool))}
    >Show ID</button>
    { displayToggles[i] &&

Also

useEffect(() => {
  getPosts();
}, []);

simplifies to

useEffect(getPosts, []);
function App() {
  const [post, setPosts] = React.useState([]);
  const [name, setName ] = React.useState('');
const [displayToggles, setDisplayToggles] = React.useState([]);
React.useEffect(() => {
  fetch("https://jsonplaceholder.typicode.com/posts")
    .then((res) => res.json())
    .then((res) => {
      setPosts(res);
      setDisplayToggles(res.map(() => false));
    });
}, []);

  return post.map((item, i) => (
        <div key={item.id}>
        <p>{item.title}</p>
    <button
        onClick={() => setDisplayToggles(displayToggles.map((bool, j) => j === i ? !bool : bool))}
    >Show ID</button>
    { displayToggles[i] &&
          <p>{item.id}</p>
        }
        </div>
        ));
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading