6

Here is my code.

<a onClick={handleClickOpen}>
  <Typography paragraph component="span" color="primary" variant="body1">
    {f('changeUnitsToCentimeters')}
  </Typography>
</a>

I want to be able to use that event listener on the typography component but Typography from Material UI does not accept the onClick event listener. I don't want to use a button because it will mess up how the text looks. Is there an element I can wrap the typography component in that will accept that listener?

morgancollado
  • 85
  • 3
  • 8
  • Howdy, did you try with a `div` or `span` ? With CSS you can solve the style issue with the text when you use the button. – rigojr Jun 26 '21 at 21:09

2 Answers2

7

If you check right below the props table on the page defining the Typography component API, you'll see that it says

Any other props supplied will be provided to the root element (native element).

So for example, if you have

  <Typography onClick={myFunction} paragraph component="span" color="primary" variant="body1">
    {f('changeUnitsToCentimeters')}
  </Typography>

Then myFunction will be applied as a click event directly on the span.

That said, you shouldn't not use a button simply because it will mess up your styles. Putting a click listener on a non-interactive element like a span is not accessible, and making it accessible isn't that straightforward. Here's a list of things to consider that probably isn't even exhaustive:

  1. does your span exist in the tab index?
  2. do assistive technologies recognize it as a button?
  3. can it be clicked via the enter key and space bar?
  4. does it automatically submit forms in the proper circumstances?

Native button elements take care of all that stuff for you automatically, so instead of making a span accessible, the far simpler solution is to style your button to look how you want with CSS.

For Material UI, you can look into the ButtonBase component as a wrapper for your Typography component since ButtonBase has all that functionality and more, without all the opinionated styles of the regular Material UI Button component. Or you can not bother with a component for the button and just use a regular <button> with custom styles. Here's an article from CSS Tricks on the topic of overriding default button styles.

cjl750
  • 4,380
  • 3
  • 15
  • 27
  • 1
    This is well reasoned and very helpful! I need to not be lazy about my styles programming and follow convention to keep things accessible. Thank you so much for your response. – morgancollado Jun 27 '21 at 17:46
0

Provide onClick props to the component

<a>
  <Typography onClick={handleClickOpen} paragraph component="span" color="primary" variant="body1">
    {f('changeUnitsToCentimeters')}
  </Typography>
</a>
Delice
  • 743
  • 9
  • 20