I have an api whose output is below and I saved it in a state called allDiseases
[
{
disease_id: 1,
unique_name: "1Mealybugs",
title: "title1",
show_status: "publish",
},
{
disease_id: 2,
unique_name: "Mealybugs",
title: "title2",
show_status: "draft",
},
];
I used the below code to display the items and I want it to be unchecked when the value of show_status
is equal to draft
and to be checked when its value is equal to publish
How can I do this?
<tbody>
{allDiseases.map((item) => {
return (
<tr>
<td>
{item.title}
</td>
<td>{item.unique_name}</td>
<td>
<input
className="checkHeight"
defaultChecked={false}
type="checkbox"
value={item.show_status}
id="defaultCheck1"
onChange={()=> activePost(item.disease_id)}
/>
</td>
</tr>
);
})}
</tbody>
There is an api in onChange (activePost) that changes the value of showStatus
when it is executed
const activePost = async (idPost) => {
try {
const api = "localhost/website/disease/change-show-status";
const { data } = await axios.post(api,{
disease_id: idPost
}, {
headers: { Authorization: `Bearer ${token}` },
});
console.log(data);
toast.success(data.message, { autoClose: 15000 });
} catch (e) {
console.log(e);
toast.error(e.response.data.error, { autoClose: 15000 });
}
};
CodePudding user response:
If you use a ternary statement in defaultChecked
and it should work.
<tbody>
{allDiseases.map((item) => {
return (
<tr>
<td>
{item.title}
</td>
<td>{item.unique_name}</td>
<td>
<input
className="checkHeight"
defaultChecked={item.show_status === "draft"}
type="checkbox"
value={item.show_status}
id="defaultCheck1"
onChange={()=> activePost(item.disease_id)}
/>
</td>
</tr>
);
})}
</tbody>