0

I have an HTML page rendered using React. I've retrieved a list of objects representing websites and stored them in memory, and can display them in a long list on the page just fine.

I've added a button for each object rendered on the page. I've created an event handler for the onClick that should receive a property from the object (uid), then generate a new table on the page with details specific to that object.

I think I'm missing something crucial in React, because I can't seem to pass the object data to the event handler.

HTML/JSX

   <div>
        <h2>results</h2>
        <ul>
          {countriesToShow.map((x, i) => {
            let uid = x.uid;
            return (
              <li key={i} id={i}>
                {x.name.common}{' '}
                <button onClick={toggleShowCountry(uid)}>show</button>
              </li>
            );
          })}
        </ul>
      </div>
    )

toggleShowCountry

const toggleShowCountry = (x) => {
    console.log('this is uid', x);
    // TODO: get DOM object where the country resides and manipulate it
  };

Output

Nothing. Not even undefined. Clicking the button doesn't cause anything to appear in the console, and on the initial render it looks like toggleShowCountry fires automatically for each object as it is rendered.

I believe this might have somethign to do with the "bind" feature of JavaScript but am not totally sure.

fullstacc
  • 1
  • 1
  • You're looking for: `` What you have in the question is **calling** the function and using its return value as a click handler. Instead, create a function that, when run, will call your function with the relevant value. – T.J. Crowder May 11 '22 at 13:40
  • This is already **well** covered by previous questions and answers, so I suggest just deleting it. – T.J. Crowder May 11 '22 at 13:40
  • It’s because you’re calling it during render; that’s what the `()` does. Use an anonymous function; `onclick={() => toggleShowCountry(uid)}` – Dave Newton May 11 '22 at 13:40
  • thank you all, I understand my issue now. It looks like stackoverflow strongly advises against deleting questions unless they're exposing identifying details – fullstacc May 11 '22 at 15:40

1 Answers1

-1

try this one: <button onClick={() => toggleShowCountry(uid)}>show</button>

jcoder
  • 1
  • 1