Home > Software design >  Toggle element data for element that I click on, not all elements
Toggle element data for element that I click on, not all elements

Time:02-13

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>
      ))}

CodePudding user response:

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>

  • Related