Bar
Bar

Reputation: 194

onClick on a TableRow in React MaterialUI

I want to add an onClick listener to my TableRow. To my surprise, simply giving an onClick prop like this works:

<TableRow onClick = {()=> console.log("clicked")}>
    <TableCell> Content </TableCell>
</TableRow>

I couldn't understand this behavior because, looking at the code : https://github.com/mui-org/material-ui/tree/master/packages/material-ui/src/TableRow I don't see a definition for the onClick prop anywhere.

So, why is it working?

Thanks.

Upvotes: 1

Views: 3933

Answers (2)

rid
rid

Reputation: 63610

It's not TableRow that listens to onClick, but rather the underlying component, which is React's tr by default, because TableRow passes to it all the props it gets and doesn't use.

If you supply a different underlying component with <TableRow component={...} onClick={...} />, then that component will have to do something with onClick if you want to keep the functionality.


This is what happens:

  1. TableRow takes the following props:
    • classes, className, component, hover and selected (line 39)
    • ...other (line 45), which contains all the other props that you pass to it
  2. It then returns a Component (line 50) which is whatever you passed as the component prop (see line 82 for the prop type), or, if you didn't pass anything, then tr by default (line 42 and line 33)
  3. The tr component then takes all the props sent by TableRow, which are:

Upvotes: 1

J Doe
J Doe

Reputation: 132

onClick is not Material UI feature (or prop).

Instead it is a native React onClick function that you can read more on: https://reactjs.org/docs/handling-events.html

Whatever feature you find in React docs, you can use in MaterialUI and on any MaterialUI element, since MaterialUI is based on React.

Upvotes: 1

Related Questions