Im trying to find the value of the first <p>
tag inside my div when i click a button inside the same div.
Note: The $(this)
doesn’t seem to work.
Here’s my code:
<div className="cartcontainer">
<p
key={item.id}
style={{
display: "inline-block",
marginTop: "auto",
marginBottom: "auto",
float: "left",
}}
>
NFT ID: {item.id}
</p>
<p
key={item.id}
style={{
display: "inline-block",
marginTop: "auto",
marginBottom: "auto",
float: "left",
}}
>
Price: {item.price}
</p>
<button
style={{
float: "right",
width: 40,
height: 40,
fontSize: 20,
borderRadius: 12,
display: "block",
}}
onClick={() => removeCartItemHandler(cart.findIndex($(this).closest("p")))}
>
X
</button>
</div>
3
Answers
simple one-liner, self-explanitory:
jQuery has no place within a React project. The former operates on the DOM directly whereas the latter uses state to drive the display.
Instead of trying to access a known value from a previous element, just use the known value
JQuery has a method called siblings where you can find all the nodes associated with the same parent class. You can pass class name, id, and selector to fetch a particular element. as it returns an array, you can fetch the first element via indexing.