codegouvfr / react-dsfr

🇫🇷 The French Government Design system React toolkit
https://react-dsfr.codegouv.studio
MIT License
406 stars 51 forks source link

Button with linkProps and onClick creates a <button> instead of <a> #203

Closed eletallbetagouv closed 11 months ago

eletallbetagouv commented 11 months ago

This creates a <a>

<Button
      linkProps={{
        href: '/somewhere'
      }}
    >
      I'm a link
    </Button>

But if I add a onClick, it creates a <button>. We're still using linkProps so it should still be a <a>.

 <Button
      linkProps={{
        href: '#',
        onClick: e => {
          e.preventDefault()
          // ... do some stuff before navigating...
          router.push('/somewhere')
        },
      }}
    >
      I'm a link
    </Button>

Exemple usage : we have a button in our header to change the language. It changes the URL, so for accessibility reasons, it should be a <a>. Yet we have to do some stuff with cookies before navigating, so we still need the onClick.

garronej commented 11 months ago

Hello @eletallbetagouv,

Thanks for reporting.
The behaviour you are reporting seems suprising to me after having looked at the code:
https://github.com/codegouvfr/react-dsfr/blob/f3429eabc57d52a32cab5730c4d4c396ee88fd97/src/Button.tsx#L135-L168

The Link component is something that you provide to react-dsfr depending of what routing library you are using...

If you could provide a playground or a repro repo that would help me.

Best,

eletallbetagouv commented 11 months ago

Je repasse en français.

Tu peux tester sur cette branche : https://github.com/betagouv/signalconso-website/tree/repro_for_issue_reactdsfr_203 Tu devrais pouvoir démarrer avec yarn && yarn dev (attention yarn 3.2.1) La homepage devrait fonctionner. En haut à droite dans le header j'ai mis les différents cas. Le code est dans "SwitchLang.tsx". Si tu veux voir l'endroit où on fournit le Link à react-dsfr, c'est dans "StartDsfr.tsx" (je l'ai activé/désactivé, je n'ai pas vu de différence).

Je crois que je vois d'où vient ce comportement : https://github.com/codegouvfr/react-dsfr/blob/f3429eabc57d52a32cab5730c4d4c396ee88fd97/src/link.tsx#L27

garronej commented 11 months ago

Ah, bon point je n'avais plus le code en tête Cependant c'est du coup le comportement attendu et non un bug.
Un href: '#' génère une erreur d'accessibilité avec tous les détecteurs. Cela affiche un message du type "Utilisez

garronej commented 11 months ago

Après si vous avez vraiment besoin d'une ancre (ce que je déconseil si vous devez faire homologué votre app avec un certain niveau d'accessibilité) rien de nouve empèche d'utilise directement votre composant link ou même directement un <a />

eletallbetagouv commented 11 months ago

Ah ok, c'est à cause du #. Effectivement en fait je n'en ai pas besoin, je vais répéter l'URL dans le href, même si la navigation se fait via le onClick. Merci