Reputation: 323
In my app I render a confirm button if the user has requested to adopt a pet. How can i enable the confirm button to access the id of the user it is rendered with?
import React, { useEffect, useState } from "react";
import { BACK_PORT } from "../../var";
import axios from "axios";
import { Button } from "react-bootstrap";
function UsersDashboard() {
const [users, setUsers] = useState([]);
const token = localStorage.getItem("auth-token");
useEffect(() => {
axios
.get(`${BACK_PORT}/data/users`, { headers: { "auth-token": token } })
.then(function (response) {
setUsers(response.data);
})
.catch(function (error) {
});
}, [token]);
const onConfirm = () => {
//Send ID of user
};
return users.map((item) => (
<div key={item._id}>
<div>Username: {item.name}</div>
{item.adoptionRequest && (
<div>Adoption Request: {item?.adoptionRequest}</div>
)}
{item.adoptionRequest && (
<div>
<Button onClick={onConfirm}>Confirm</Button>
</div>
)}
{item.adoptionRequest && <div>hello</div>}
</div>
));
}
export default UsersDashboard;
Upvotes: 0
Views: 19
Reputation: 341
I'm confused as buttons are always "enabled" and therefore clickable.
I'm guessing you want to disable the button if the user has not requested for adoption?
If that's the case simply use the disabled attribute of the tag
const onConfirm = (userId) => {
axios.get(`data/user/${userId}`);
//Send ID of user by accessing userId
};
<Button disabled={item.adoptionRequest === null} onClick={() => onConfirm(item._id)}>Confirm</Button>
Upvotes: 1
Reputation: 560
Replace
onClick={onConfirm}
with
onClick={() => onConfirm(item._id)}
import React, { useEffect, useState } from "react";
import { BACK_PORT } from "../../var";
import axios from "axios";
import { Button } from "react-bootstrap";
function UsersDashboard() {
const [users, setUsers] = useState([]);
const token = localStorage.getItem("auth-token");
useEffect(() => {
axios
.get(`${BACK_PORT}/data/users`, { headers: { "auth-token": token } })
.then(function (response) {
setUsers(response.data);
})
.catch(function (error) {
});
}, [token]);
const onConfirm = (userId) => {
console.log(userId)
//Send ID of user
};
return users.map((item) => (
<div key={item._id}>
<div>Username: {item.name}</div>
{item.adoptionRequest && (
<div>Adoption Request: {item?.adoptionRequest}</div>
)}
{item.adoptionRequest && (
<div>
<Button onClick={() => onConfirm(item._id)}>Confirm</Button>
</div>
)}
{item.adoptionRequest && <div>hello</div>}
</div>
));
}
export default UsersDashboard;
Upvotes: 2