-2

I have some button tabs I created in React. When I click on one, it resets all the other tabs to display the default text.

function resetAllTabs() works fine as a classic for loop. But .map() or for...of {} simply doesn't reset my tabs. No error, just silence...

  //// STATE MANAGER FOR TABS
  import React, { useState } from 'react';
  const [currentTab, setCurrentTab] = useState(null);

  const [tab1, setTab1] = useState(<p>SET 1</p>);
  const [tab2, setTab2] = useState(<p>SET 2</p>);
  ...
  const [tab10, setTab10] = useState(<p>SET 10</p>);

  let tabs = [[tab1, setTab1], [tab2, setTab2], [tab3, setTab3], 
              [tab4, setTab4], [tab5, setTab5], [tab6, setTab6], 
              [tab7, setTab7], [tab8, setTab8], [tab9, setTab9], 
              [tab10, setTab10]]

  // WORKS JUST FINE!
  function resetAllTabs() {
    for (let i=0; i<tabs.length; i++) { 
      tabs[i][1](<p>SET {i + 1}</p>) 
    }
  };

  // DOESN'T WORK IN BROWSER. NO ERROR. JUST DOESN'T DO ANYTHING...
  function resetAllTabs() {
    tabs.map = ((setTab, i) => setTab[1](<p>SET {i + 1}</p>));
  };

  resetAllTabs();
  • 6
    Do you mean `tabs.forEach((setTab, i) => ...)`? – p.s.w.g Feb 13 '20 at 22:06
  • 5
    `tabs.map = ((setTab, i) => setTab[1](

    SET {i + 1}

    ));` is *overriding* the `map` property with an arrow function.
    – VLAZ Feb 13 '20 at 22:06
  • 5
    Also, please don't use `.map` for a simple iteration when you're not doing a mapping operation. If you need to use an iteration method, then use `forEach`. – VLAZ Feb 13 '20 at 22:07
  • And probably you don't even need to use an iteration method, [just use os `for … of`](https://stackoverflow.com/a/50844413/1048572). – Bergi Feb 13 '20 at 22:33
  • I didn't notice I had an = operator after .map! It works now. I replaced map with forEach also. Thanks. – Superintendent UI Feb 13 '20 at 23:10

1 Answers1

1

you have a small syntax error with how you are using map. although may seem subtle you are basically doing an assignment with the = operator instead of envoking the Array.prototype.map function

just to keep in line with what you wrote originally you probably intended to write this

function resetAllTabs() {
  return tabs.map( (setTab, i) => setTab[1](<p>SET {i + 1}</p>) );
};

having said that, like vlaz pointed out, you are better off using a forEach for iteration

Denis S Dujota
  • 543
  • 5
  • 13