Uno de mis proyectos utiliza una biblioteca llamada Fixed-Data-Table-2 (FDT2), y es excelente para representar de manera eficiente toneladas de filas de datos.
Su documentación muestra una tabla receptiva que cambia de tamaño según el ancho y la altura del navegador.
Pensé que sería genial compartir este ejemplo usando React Hooks.
¿Qué son los React Hooks?
Son funciones que le brindan características de React como enlaces de estado y ciclo de vida sin clases de ES6.
Algunos beneficios son
- aislar la lógica con estado, lo que facilita la prueba
- compartir lógica de estado sin accesorios de renderizado o componentes de orden superior
- separar las preocupaciones de su aplicación en función de la lógica, no de los ganchos del ciclo de vida
- evitando las clases de ES6, porque son extravagantes, no en realidad clases , y hacen tropezar incluso a los desarrolladores de JavaScript experimentados
Para obtener más detalles, consulte la introducción oficial de Hooks de React.
ADVERTENCIA: ¡No lo use en producción!
En el momento de escribir este artículo, los Hooks están en alfa. Su API puede cambiar en cualquier momento.
Te recomiendo que experimentes, te diviertas y uses Hooks en tus proyectos paralelos, pero no en el código de producción hasta que sean estables.
La meta
Construiremos una tabla de datos fija receptiva. No será ni demasiado estrecho ni demasiado ancho para nuestra página, ¡se ajustará perfectamente!
Preparar
Aquí están los enlaces de GitHub y CodeSandbox.
git clone //github.com/yazeedb/Responsive-FDT2-Hooks/ cd Responsive-FDT2-Hooks npm install
La master
sucursal tiene el proyecto terminado, así que verifique la start
sucursal si desea seguir adelante.
git checkout start
Y ejecuta el proyecto.
npm start
La aplicación debería estar ejecutándose localhost:3000
. Empecemos a codificar.
Importar estilos de tabla
Primero querrá importar la hoja de estilo de FDT2 index.js
, para que su tabla no se vea loca.
Generando datos falsos
Nuestra mesa necesita datos, ¿verdad? Cree un archivo en la src
carpeta llamada getData.js
.
Usaremos la increíble biblioteca faker.js para generar nuestros datos. Ya vino con tu npm install
.
Aquí está la fuente si desea copiar / pegar.
import faker from 'faker'; const createFakeRowData = () => ({ firstName: faker.name.firstName(), lastName: faker.name.lastName(), email: faker.internet.email(), city: faker.address.city(), salary: faker.random .number({ min: 50000, max: 500000 }) .toLocaleString('en-US', { style: 'currency', currency: 'USD' }) }); export default () => Array.from({ length: 2000 }, createFakeRowData);
createFakeRowData
devuelve un objeto con un nombre completo, correo electrónico, ciudad y salario en dólares estadounidenses.
Nuestra función exportada devuelve 2000 de ellos.
La mesa que no responde
Tenemos nuestros datos, codifiquemos la tabla ahora.
En la parte superior index.js
, importe nuestros datos y componentes FDT2.
import { Table, Column, Cell } from 'fixed-data-table-2'; import getData from './getData';
Y úsalos así.
function App() { const data = getData(); return (
{ return {data[rowIndex][columnKey]}; }} />
{ return {data[rowIndex][columnKey]}; }} />
{ return {data[rowIndex][columnKey]}; }} />
{ return {data[rowIndex][columnKey]}; }} />
{ return {data[rowIndex][columnKey]}; }} />
); }
Configuramos la tabla con nuestros datos y creamos una Column
para cada campo que queremos mostrar.
getData
los objetos contienen un nombre / apellido, correo electrónico, ciudad y salario, por lo que necesitamos una columna para cada uno.
Nuestra interfaz de usuario ahora se ve así.
Try resizing your browser window, you’ll notice it isn’t responsive at all. It’s either too big or too small for your viewport and can leave excess space.
Escape to the impure
As we’ve learned, React’s declarative nature lets you write your UI using pure, deterministic, and easily testable functions.
The same input should always return the same output.
However, we sometimes need to visit the “impure” world, for DOM manipulation, adding events such as listeners, subscriptions, and timers.
HOCS and render props
Render props and higher-order components (HOCS) are the standard solution, but have some tradeoffs that Hooks are now trying to solve.
Using Hooks
Hooks are the new escape hatch to use imperative code. In our case, getting the window size is the effect we’re after.
Create a new file called useWindowSize.js
.
We’ll need two things to achieve this:
- Listen to the window’s
resize
event, so we’re notified of when it changes - Save the width/height to share with our table
Two hooks can help:
useEffect
useState
useEffect
This will likely replace your componentDidMount
, componentDidUpdate
, and componentWillUnmount
lifecycle hooks once it’s stabilized.
useEffect
's perfect for most initialization logic and reading the DOM.
It’s where we’ll set up our window resize
event listeners.
For more detail, see the official docs.
useState
Super simple, this Hook returns a stateful value and a function to update it. Once we capture the window’s width/height, we’ll have useState
track it.
Writing our custom Hook
According to the official docs:
A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks.
Our custom hook will be called useWindowSize
, and it’ll call the useState
and useEffect
hooks.
This Hook’s mainly from Gabe Ragland’s useWindowSize
on useHooks.com.
// `useWindowSize.js` import { useState, useEffect } from 'react'; export default () => { const getSize = () => { return { width: window.innerWidth, height: window.innerHeight }; }; const [windowSize, setWindowSize] = useState(getSize); useEffect(() => { const handleResize = () => { setWindowSize(getSize()); }; window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }, []); return windowSize; };
Let’s break this down.
Getting the window size
const getSize = () => { return { width: window.innerWidth, height: window.innerHeight }; };
getSize
simply returns the window’s innerWidth
and innerHeight
.
Initializing useState
const [windowSize, setWindowSize] = useState(getSize);
useState
can take an initial value or a function that returns a value.
In this case we want the window’s dimensions to start, so getSize
is the perfect initializer.
useState
then returns an array, the first index is the value and the second index is the updater function.
Configuring useEffect
useEffect(() => { const handleResize = () => { setWindowSize(getSize()); }; window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); }; }, []);
useEffect
takes a function that will run your desired effect.
Whenever the window size changes, handleResize
sets the state by giving setWindowSize
the latest width/height.
Cleanup Logic
Our effect function then returns a new function, which useEffect
recognizes as cleanup logic.
return () => { window.removeEventListener('resize', handleResize); };
When we leave the page or somehow unmount our component, this cleanup function runs and removes the resize
event listener. This helps prevent memory leaks.
useEffect’s Second Argument
useEffect
's first argument is the function handling our logic, but we also gave it a second argument: an empty array.
useEffect(() => { ... }, []); // empty array
Why an empty array?
useEffect
's second argument is an array of values to watch over. If any of those values change useEffect
runs again.
We’re just setting/removing event listeners, which only needs to happen once.
An empty array is how we communicate “just run once” to useEffect
.
Empty array = no values ever change = just run once
Return windowSize
Now that our effect’s set up, just return windowSize
. As the browser’s resized, windowSize
will be updated.
Using our custom Hook
Time to throw our Hook at Fixed-Data-Table2!
Back in index.js
, go ahead and import useWindowSize
.
And use it like so.
For fun you can console.log(windowSize)
and watch it update in real-time.
Cool, we get back an object of the window’s width
and height
!
Instead of hardcoding our table’s width and height, we can use our Hook’s exposed state.
Now your table should adjust to the window’s dimensions.
I hope you enjoyed this tutorial!