Home > Net >  Can I write if /else conditions in onClick element is JSX/ ReactJS?
Can I write if /else conditions in onClick element is JSX/ ReactJS?

Time:09-01

hope you all are doing well, I am new to ReactJS and JSX syntax below in the problem I am rendering a table element based on different roles from the same Generic Table component now I have to set onClick attribute's navigation on basis of role and I cannot make a function outside of the scope because I am using the rowIndex to fetch the resignation_Id so can anybody please explain me how to resolve this problem?

    <TableCell>
                                                    <Button
                                                        onClick={
                                                            //      if(`${props.heading}` == "CLEARANCES"){
                                                            //  markCleared(`${row.resignationId}`)
                                                            // } else if{
    
                                                            // }
                                                            `${props.heading}` == "CLEARANCES"
                                                                ? () => markCleared(`${row.resignationId}`)
                                                                : () =>
                                                                    navigate(`/resignations/${props.role}/action/${row.resignationId}`)
                                                        }
                                                        variant="outlined"
                                                        size="small"
                                                        color="success"
                                                    >
                                                        {props.buttonTitle}
                                                    </Button>
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                </TableBody>

CodePudding user response:

Pass a function directly to the onClick prop and handle your if statement in there.

<Button
  onClick={() => {
    if (props.heading === "CLEARANCES") {
      markCleared(row.resignationId)
    } else if {
      navigate(`/resignations/${props.role}/action/${row.resignationId}`)
    }
  }}
  variant="outlined"
  size="small"
  color="success"
>
  {props.buttonTitle}
</Button>

CodePudding user response:

Yes you can. OnClick gives you an event that you can catch in following way: onclick((e) => { your code goes here

}

  • Related