Botón vs Div: ¿Qué es tan importante de todos modos?

Rate this content
Bookmark

Los defensores de la accesibilidad suelen decir "usa la plataforma", pero ¿por qué? En esta charla relámpago, te mostraré las diferencias de implementación entre el comportamiento de los elementos HTML nativos y sus contrapartes DIV.

12 min
02 Aug, 2021

Video Summary and Transcription

La charla de hoy discutió la preferencia de los defensores de la accesibilidad por usar la plataforma en lugar de los divs, destacando la facilidad de convertir los divs en botones. También se discutió el CSS para hacer que los divs se vean como botones, pero se concluyó que usar la plataforma es más fácil y accesible. La sesión de preguntas y respuestas abordó temas como el mercado objetivo y el uso de divs como botones para casos específicos. La charla también mencionó brevemente la función de toque de Match y el soporte para aplicaciones nativas en Ionic. Las palabras de cierre concluyeron la charla.

Available in English

1. Accessibility Advocates and the Platform vs Divs

Short description:

Hoy hablaré sobre por qué los defensores de la accesibilidad prefieren usar la plataforma en lugar de los divs. Demostraré el proceso de convertir un div en un botón y viceversa, destacando la facilidad de usar la plataforma para la accesibilidad. Para hacer que un botón sea accesible, proporciona un rol de botón y asegúrate de que no se envíe al presionar Enter. Convertir un div en un botón requiere agregar funcionalidad de tabulación y pulsación de teclas. Finalmente, podemos tabular, presionar espacio y Enter para activar el botón.

Mi nombre es Jen Lugar. Y hoy les hablaré sobre por qué los defensores de la accessibility a menudo hablan sobre el uso de la plataforma en lugar de los divs. Así que hoy voy a hacer una demostración en vivo sobre lo que sucede cuando tomas un div y lo conviertes en un botón, y cuando tomas un botón y lo conviertes en un div. Y la razón de esto es mostrarte lo mucho más fácil que es usar la plataforma en lugar de usar divs que luego intentas hacer accesibles.

Cuando miramos nuestra aplicación, puedes ver que tengo un botón y un div. El botón activa la sección. Lo que vamos a hacer ahora es hacer que nuestro botón sea accesible. Así que cuando miramos aquí, vemos que tenemos un botón y un div. Para hacer que este botón sea accesible, queremos proporcionar un rol de botón. Mucha gente dice que no necesariamente necesitas esto. Sin embargo, el primer botón en una página se asume que es un botón de envío, lo que significa que si no quieres que se envíe cuando presionas Enter en una página, entonces vas a querer convertir este rol en un botón. Después de eso, ya casi has terminado. Eso es más o menos todo. Así que vamos a ver qué necesitas hacer para convertir tu div en un botón.

Voy a hacer un poco de trampa. Tengo mi opción completada, pero echa un vistazo a esto por un momento. Tenemos nuestro rol de botón, pero sin la capacidad de tabular, no podemos tabular hasta nuestro div. Así que vamos a agregar eso. En este punto, podemos tabular, lo cual es genial. Eso es útil. Sin embargo, no podemos presionar Enter. No podemos presionar Espacio para ingresar si es un div. No hace nada. Así que vamos a tener que agregar nuestro onClick para ocultar y mostrar el texto dentro de nuestro botón div, que estamos pasando. En este punto, cuando haces clic en él, puedes ver que funciona. Pero aún no podemos tabular ni presionar espacio o enter para activarlo. Así que vamos a necesitar agregar esto a nuestro botón. Y también vamos a agregar nuestras teclas permitidas. Y en ese punto, podemos tabular, podemos presionar espacio, lo cual aún no funciona del todo, y podemos presionar Enter.

2. CSS for Divs and Buttons

Short description:

El CSS para hacer que un div se vea como un botón incluye establecerlo como inline block, alinear el texto al centro y heredar el color de otros botones en la página. También son necesarias otras propiedades como border radius, background color, padding, border y efectos hover. Sin embargo, en la mayoría de los casos, es más fácil y accesible usar la plataforma. Construir navegación o menús desplegables de selección múltiple con botones y checkboxes asegura la accesibilidad sin necesidad de código complejo. Para obtener más información, visita el sitio web de Yaria. En conclusión, los botones son más simples de hacer accesibles en comparación con los divs.

La siguiente sección será el CSS para hacer que se vea como un div. Y tenemos que ponerlo como inline block. Así es como funciona un div o un botón. Vamos a alinear el texto al centro, el color del texto del botón. Esto permite heredar el color que todos los botones en la página tienen.

El border radius se utiliza para asegurarse de que obtengas estas esquinas redondeadas. Vamos a tener el background color para que coincida. Podrás hacer lo que quieras con esto. Box sizing es interesante. El propósito de box sizing significa que el padding está incluido dentro del tamaño de un botón, lo cual es fantástico. Eso significa que no tienes que tener el ancho de tu botón como el ancho, y luego el padding, y luego el border. Todo está incluido en ese ancho real.

El padding en un botón por defecto es realmente extraño. No estoy seguro de por qué alguien eligió exactamente 7 píxeles, pero eso es lo que es. Luego también tenemos el border, que requiere un outset y una opción de color interesante. Y luego, si no lo sabías, en algunos dispositivos iOS, si no incluyes el pointer, nunca lo detectará como un botón. No lo abrirá realmente. Y luego también tenemos que tener nuestros hovers. Así que este es un bloque de código bastante grande que necesitaremos solo para que esto funcione. Puede parecer un botón. Y actúa como un botón. Pero hay mucha información que debes recordar para que esto funcione. ¿Preferirías tener role equals button, o preferirías tener que recordar todo esto?

Ahora, hay momentos en los que usar la plataforma no funciona. Por ejemplo, cuando intentas construir una navegación, o cuando intentas construir un menú desplegable de selección múltiple. Y lo que es realmente fascinante acerca de esos es que si te adhieres estrictamente a usar botones cuando quieres hacer clic en algo, o checkboxes cuando quieres seleccionar varios elementos, entonces no tienes que engañar al sistema para que sea accesible. Aún funciona. Si quieres obtener más información al respecto, el sitio web de Yaria incluye opciones y ejemplos de cómo construir ese tipo de componentes. Hoy aprendimos que un botón no requiere mucho para ser accesible, pero un div requiere muchas cosas que debes recordar. Si tienes alguna pregunta, siempre puedes contactarme en Twitter en NickCodeMonkey.

QnA

Q&A on Target Market and Using Divs as Buttons

Short description:

Y gracias de nuevo. Eso es mucho conocimiento en solo 20 o 28 minutos. Cuatro grandes temas. Me gustaría invitar a todos los oradores de las charlas relámpago al escenario para la última ronda de preguntas y respuestas del día. Voy a empezar con la primera pregunta de Matt McClure. ¿A qué mercado te diriges? ¿Y por qué alguien usaría Mux en lugar de Twitch o YouTube? Somos un producto dirigido a los desarrolladores, puramente APIs para que los desarrolladores las integren en sus plataformas. Si eres un streamer que solo quiere transmitir sin escribir código, Twitch y YouTube son excelentes plataformas. Pero si estás intentando construir una plataforma, probablemente seamos una mejor opción. La siguiente pregunta es para Jen. ¿Cuáles son las razones por las que a alguien del equipo web de React Native le gustaría usar un div como botón? La razón es que poner HTML dentro de un botón no es HTML semántico. Es posible que deseen envolver ese contenido en un div y convertirlo en un botón accesible en su lugar. Si tienes una tarjeta completamente clickable con diferentes elementos dentro, no puedes hacerlo de manera semántica dentro de un botón. En ese caso, querrás hacer un div accesible.

Y gracias de nuevo. Eso es mucho conocimiento en solo 20 o 28 minutos. Cuatro grandes temas.

Me gustaría invitar a todos los oradores de las charlas relámpago al escenario para la última ronda de preguntas y respuestas del día.

¡Hola a todos! Hola. Hola. Hola. Hola. Buenos días, tardes, noches, lo que sea para ti.

Voy a ir directamente a las preguntas. Voy a empezar con la primera pregunta de Matt McClure. ¿A qué mercado te diriges? ¿Y por qué alguien usaría Mux en lugar de Twitch o YouTube? Sí, es una pregunta válida. Somos un producto dirigido a los desarrolladores. Por lo tanto, somos puramente APIs para que los desarrolladores las integren en sus plataformas, a diferencia de Twitch y YouTube, que son productos más orientados al consumidor. Si eres un streamer que solo quiere transmitir sin escribir código, esas son excelentes plataformas. Deberías usarlas. Pero si estás intentando construir una plataforma, probablemente seamos una mejor opción. OK. Así que se trata más del público objetivo, supongo, y de que tienes más control sobre lo que estás haciendo. Sí, lo pensaría un poco como una mala analogía que mencioné en Slack. Son más como PayPal o Venmo. Nosotros somos más como Stripe, si lo piensas en términos de APIs de pago. OK, gracias.

La siguiente pregunta es para Jen. ¿Cuáles son las razones por las que a alguien del equipo web de React Native le gustaría usar un div como botón? La razón es que poner HTML dentro de un botón no es HTML semántico. Por lo tanto, es posible que deseen envolver ese contenido, por ejemplo, una tarjeta o un bloque de imagen y texto, en un div y convertirlo en un botón accesible en lugar de poner un botón alrededor de él. Sí, por lo tanto, si tienes una tarjeta completamente clickable con diferentes elementos dentro, no puedes hacerlo de manera semántica dentro de un botón. Correcto. En ese caso, querrás hacer un div accesible. Bueno, al menos deberías querer hacerlo.

Q&A on Tapping, Match, and Ionic

Short description:

Jen va a venir y te buscará. Te tocaré amablemente en el hombro y te haré sugerencias. Match se ve increíble. Muchas gracias. Después de probarlo, sentirás lo mismo. En la empresa para la que trabajo, Albert Heijn, lo estamos utilizando. Ha sido un placer. ¿Ionic admite aplicaciones nativas similares a React Native? Es una combinación de ambos, mostrando la mayoría de la interfaz de usuario en una vista web pero permitiendo la integración con vistas nativas personalizadas o actividades en Android. Gracias, chicos y señorita, por esta gran charla. La parte formal ha terminado. Adiós, adiós.

Quizás. Y puedo decir, si no lo haces, Jen va a venir y te buscará. Te tocaré amablemente en el hombro y te haré sugerencias. ¿Qué te parece eso?

Sí, pero tocar no funciona. Entonces tendré que hacerlo.

Sí, sí. Otra pregunta. Pero solo para Uri, un toque amable en el hombro de Martin van Houten. No es realmente una pregunta, solo quería decir, match se ve increíble. Siempre es agradable escuchar eso. Muchas gracias. Espero que después de probarlo, sientas lo mismo y no me odies. Bueno, en realidad en la empresa para la que trabajo, Albert Heijn, lo estamos utilizando. Y debo decir que ha sido un placer, así que muchas gracias.

Oh, eres mi vecino. Puedo ir a visitarte. Sí, sería un placer.

Mike, ¿Ionic admite aplicaciones nativas similares a React Native? ¿O es como una aplicación estándar de Cordova, donde es una interfaz de usuario web en lugar de una aplicación nativa? Es una combinación de ambos, donde la mayoría de la interfaz de usuario se muestra en una vista web, pero puedes integrar vistas nativas personalizadas o actividades en Android, y mezclar qué se muestra en una vista web o la vista nativa, o incluso superponer la vista nativa encima de la vista web. Así que obtienes lo mejor de ambos mundos. Eso suena poderoso.

De acuerdo, gracias, chicos y señorita, por esta gran charla. Para las personas que están viendo, también estarán en las salas de Zoom para preguntas, pero la parte formal ha terminado. Me voy a despedir por un rato. Así que gracias por unirse. Gracias. Gracias. Adiós. Gracias. Adiós. Gracias. Adiós.

Closing Remarks

Short description:

Gracias. Adiós. Gracias. Adiós. Gracias. Adiós.

Gracias. Adiós.

Gracias. Gracias. Adiós.

Gracias. Adiós.

Adiós.

Adiós.

Gracias. Adiós.

Gracias. Adiós.

Gracias. Adiós.

Adiós.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Advanced Conference 2021React Advanced Conference 2021
39 min
Don't Solve Problems, Eliminate Them
Top Content
Humans are natural problem solvers and we're good enough at it that we've survived over the centuries and become the dominant species of the planet. Because we're so good at it, we sometimes become problem seekers too–looking for problems we can solve. Those who most successfully accomplish their goals are the problem eliminators. Let's talk about the distinction between solving and eliminating problems with examples from inside and outside the coding world.
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
React Advanced Conference 2021React Advanced Conference 2021
47 min
Design Systems: Walking the Line Between Flexibility and Consistency
Top Content
Design systems aim to bring consistency to a brand's design and make the UI development productive. Component libraries with well-thought API can make this a breeze. But, sometimes an API choice can accidentally overstep and slow the team down! There's a balance there... somewhere. Let's explore some of the problems and possible creative solutions.
React Summit 2023React Summit 2023
23 min
React Concurrency, Explained
Top Content
React 18! Concurrent features! You might’ve already tried the new APIs like useTransition, or you might’ve just heard of them. But do you know how React 18 achieves the performance wins it brings with itself? In this talk, let’s peek under the hood of React 18’s performance features: - How React 18 lowers the time your page stays frozen (aka TBT) - What exactly happens in the main thread when you run useTransition() - What’s the catch with the improvements (there’s no free cake!), and why Vue.js and Preact straight refused to ship anything similar
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
As developers, we spend much of our time debugging apps - often code we didn't even write. Sadly, few developers have ever been taught how to approach debugging - it's something most of us learn through painful experience.  The good news is you _can_ learn how to debug effectively, and there's several key techniques and tools you can use for debugging JS and React apps.

Workshops on related topic

React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Top Content
Featured Workshop
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn
React Day Berlin 2022React Day Berlin 2022
53 min
Next.js 13: Data Fetching Strategies
Top Content
WorkshopFree
- Introduction- Prerequisites for the workshop- Fetching strategies: fundamentals- Fetching strategies – hands-on: fetch API, cache (static VS dynamic), revalidate, suspense (parallel data fetching)- Test your build and serve it on Vercel- Future: Server components VS Client components- Workshop easter egg (unrelated to the topic, calling out accessibility)- Wrapping up
React Summit 2022React Summit 2022
160 min
React at Scale with Nx
WorkshopFree
The larger a codebase grows, the more difficult it becomes to maintain. All the informal processes of a small team need to be systematized and supported with tooling as the team grows. Come learn how Nx allows developers to focus their attention more on application code and less on tooling.
We’ll build up a monorepo from scratch, creating a client app and server app that share an API type library. We’ll learn how Nx uses executors and generators to make the developer experience more consistent across projects. We’ll then make our own executors and generators for processes that are unique to our organization. We’ll also explore the growing ecosystem of plugins that allow for the smooth integration of frameworks and libraries.