1

I am trying to make an onClick with a condition but have an issue when trying to pass with a parameter.

The reason I want to do this is because inside the TableRow I have button that is only visible on desktop. But when people are on 900px and below I want to make it possible to click the entire row. The IsDesktop returns true or false depending on wether the user is over or under 900px

<TableRow hover key={site.id} onClick={isDesktop&&(e)=>handleSubmit(e,site.url)}>
  <TableRowSite site={site} index={index} />
</TableRow>

This is what I have tried so far. But it keeps giving me an error.

Parsing error: Unexpected token, expected "}" (31:67)

I have seen several tutorials using a condition in the onClick but never with a parameter but I believe it is possible as it makes sense.

1
  • Use conditional rendering if its desktop render desktop version otherwise render mobile version. Commented Jul 24, 2022 at 23:47

3 Answers 3

3

I would try to do something like this:

<TableRow hover key={site.id} onClick={isDesktop ? (e) => handleSubmit(e, site.url) : undefined}>

Otherwise, you're simply trying to pass a Boolean value to an event handling prop that's expecting a callback which is seemingly what the issue at hand is caused by.

Sign up to request clarification or add additional context in comments.

Comments

1

Conditionally return an undefined handler

<TableRow
  hover
  key={site.id}
  onClick={isDesktop ? (e) => handleSubmit(e, site.url) : undefined}
>
  <TableRowSite {...{site, index }} />
</TableRow>

Or conditionally invoke the handleSubmit callback

<TableRow
  hover
  key={site.id}
  onClick={(e) => isDesktop && handleSubmit(e, site.url)}
>
  <TableRowSite {...{site, index }} />
</TableRow>

Comments

0

A quick fix you your component looks like

<TableRow hover key={site.id} onClick={isDesktop&&((e)=>handleSubmit(e,site.url))}>
    <TableRowSite site={site} index={index} />
</TableRow>

Simply wrap everything after the && in parentheses. That said, there's probably a better way to tackle this by rendering a desktop version or mobile version depending on the screen size of the user

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.