I'm learning reactjs and I want to change the color of a badge component depending on the value of a record that I call from the database through an API. However, when I try to do this it shows me nothing when I run it, do you know what I am missing or how I can do it?
<tbody>
{this.state.SociosData.map((e, key) => {
return (
<tr className="trTable">
<td>
<b>{e.nombre_tienda}</b>{" "}
<p className="mt-3 ">
{e.id_tienda} | {e.tipo_tienda} | Area {e.area_tienda}
</p>
<p>{e.direccion_tienda}</p>
</td>
<td>
{() => {
if (e.estatusfirma_tienda === "Aprobado") {
return <Badge bg="success">Firmado</Badge>;
} else if (e.estatusfirma_tienda === "Rechazado") {
return <Badge bg="danger">Firmado</Badge>;
} else {
return <Badge bg="warning">Firmado</Badge>;
}
}}
{() => {
if (e.estadolinea_tienda === "Activo") {
return <Badge bg="success">Activo</Badge>;
} else {
return (
<Badge bg="light" text="dark">
Inactivo
</Badge>
);
}
}}
</td>
<ModalFirma></ModalFirma>
</tr>
);
})}
</tbody>
CodePudding user response:
{() => {
if (e.estatusfirma_tienda === "Aprobado") {
return <Badge bg="success">Firmado</Badge>;
} else if (e.estatusfirma_tienda === "Rechazado") {
return <Badge bg="danger">Firmado</Badge>;
} else {
return <Badge bg="warning">Firmado</Badge>;
}
}}
If you want to use a function to embed if
statements in the middle of your jsx, you need to wrap it in parentheses and then call the function. This makes it a case of an "immediately invoked function expression", or IIFE:
{(() => {
if (e.estatusfirma_tienda === "Aprobado") {
return <Badge bg="success">Firmado</Badge>;
} else if (e.estatusfirma_tienda === "Rechazado") {
return <Badge bg="danger">Firmado</Badge>;
} else {
return <Badge bg="warning">Firmado</Badge>;
}
})()}
But it's more common in react to see this done with ternary expressions, so i would recommend instead doing something like this:
{e.estatusfirma_tienda === "Aprobado" ? (
<Badge bg="success">Firmado</Badge>
) : e.estatusfirma_tienda === "Rechazado" ? (
<Badge bg="danger">Firmado</Badge>
) : (
<Badge bg="warning">Firmado</Badge>
)}
CodePudding user response:
Your problem is that you are running you're if statement as a function. As @Nicholas Tower mentioned you would have to wrap it and invoke it.
I would make a ternary operator in your badge prop that will check the status and change accordingly.
<Badge bg={e.estatusfirma_tienda === 'Aprobado' ? 'success' : e.estatusfirma_tienda === 'Rechazado' ? 'danger' : 'warning'}>Firmado</Badge>
I tested it myself and confirm this works.