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.
CodePudding user response:
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.
CodePudding user response:
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>
CodePudding user response:
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