Matthew Bussen
Matthew Bussen

Reputation: 55

How do you pass a prop as well as the (event) to onClick callback in React?

I am trying to add an 'Edit Load' button that gets added inside every article as it is displayed. I need the button to pass the {article.id} as a prop to the onClick function that gets called: handleEdit. So that when the EditLoadModal's showEdit gets switched to open I can use the article.id to pull correct data about 'article' by updating the loadID prop that gets passed to EditLoadModal component.

So that I can then use that ID inside of EditLoadModal.js to pull relevant data and use for the write back to database with updated info.

<EditLoadModal
        loadID={loadID}
        showEdit={showEdit}
        handleClick={handleEdit}
      />

      <Content>
        {props.loading && (
          <img alt="" src={require("./image/spinning-arrow.gif")} />
        )}
{props.articles.length > 0 &&
          props.articles.map((article, key) => (
            <Article key={key}>
              <SharedActor>
                <a>
                  <img src={article.actor.image} alt="" />
                  <div>
                    <span>{article.actor.title}</span>
                    <span>
                      {article.actor.date.toDate().toLocaleDateString()}
                    </span>
                    <span>{article.id}</span>
                  </div>
                </a>
                <a
                  href="/LoadManager"
                  onClick={handleEdit}
                  className="theme_btn"
                >
                  Edit Load
                </a>
              </SharedActor>

And here is my handleEdit function

const [showEdit, setShowEdit] = useState("close");
const [loadID, setLoadId] = useState("1");

const handleEdit = (e) => {
    e.preventDefault();
    if (e.target !== e.currentTarget) {
      return;
    }

    switch (showEdit) {
      case "open":
        setShowEdit("close");
        break;
      case "close":
        setShowEdit("open");
        break;
      default:
        setShowEdit("close");
        break;
    }
  };

I was thinking that I could just add setLoadId(idProp) to the prop that gets passed inside handleEdit(article.id). But can't figure out how to make that happen.

Maybe there is a better approach all together?

Thanks for your help!

Upvotes: 2

Views: 2431

Answers (1)

tuomokar
tuomokar

Reputation: 388

<a
  href="/LoadManager"
  onClick={(e) => handleEdit(e, article.id)}
  className="theme_btn"
>
  Edit Load
</a>

Basically don't pass the handleEdit directly to the anchor element, but have a separate callback that calls handleEdit. That way you can pass any parameters you want to the function.

Upvotes: 2

Related Questions