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>
CodePudding user response:
simple one-liner, self-explanitory:
$( ".cartcontainer p:first-child" ).text();
CodePudding user response:
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
<button
type="button"
style={{
float: "right",
width: 40,
height: 40,
fontSize: 20,
borderRadius: 12,
display: "block",
}}
onClick={() => removeCartItemHandler(cart.findIndex(`NFT ID: ${item.id}`))}
>
X
</button>