Tari Ibaba

Tari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

How to Get the Height of an Element Before Render in React

To get the height of an element before render in React, we can combine two React hooks: useRef and useLayoutEffect.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { setHeight(elementRef.current.offsetHeight); }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} </div> ); }

See also: How to Get the Width of an Element Before Render in React

useLayoutEffect() works just like useEffect(), but the key difference is that it fires before the browser repaints the screen – before React renders the component.

We pass an empty dependencies array to useLayoutEffect() to make sure it only gets called once.

Here we create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() though, to create a state that we update when useLayoutEffect() gets called. So calling setHeight() will cause the component to be re-rendered.

To get the actual height, we use the offsetHeight property which includes borders, padding, and any scrollbars when calculating the element’s height.

It’s also possible to get the height of the entire window in React, instead of just one element.

Get height of element with clientHeight

clientHeight is another way to get the height of an element. Unlike offsetHeight, it includes padding but excludes borders and scrollbars.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { setHeight(elementRef.current.clientHeight); }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} <p>This element's height is measured using clientHeight.</p> </div> ); }

Get height of element before render and on resize in React

If you want to get the height of an element before render and also on resize, here’s what you’ll do:

  1. Combine the useLayoutEffect() and useRef() hooks to get the element’s height before it renders, like in the previous section.
  2. Track the current height with state.
  3. Add a resize event listener to the window object in useLayoutEffect().
  4. In the event listener, get the new height of the element, and update the state with it.

So it’s similar to what we did previously, but we’re adding a resize event listener this time.

JavaScript
import React, { useLayoutEffect, useState, useRef } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { const handleResize = () => { setHeight(elementRef.current.offsetHeight); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); } }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} </div> ); }

We call addEventListener() in useLayoutEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener we update the state that stores the element’s height, and this causes a re-render.

We call removeEventListener() in useLayoutEffect‘s clean-up function, to stop listening for resize events when the component is unmounted or when the dependencies change, to prevent memory leaks and unintended side effects.

Get height of element after render in React

We can also get the height of a React element after it renders in React, by combining the useRef() and useEffect() hooks.

JavaScript
import React, { useEffect, useState, useRef } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useEffect(() => { setHeight(elementRef.current.offsetHeight); }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} </div> ); }

So the difference between “before render” and “after render” is useLayoutEffect() and useEffect().

useEffect() runs after the component mounts or re-renders, unlike useLayoutEffect() that runs before. They both have a dependencies array that cause them to fire when any of those dependencies change.

As earlier, we create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() to create a state that we update when useEffect() gets called. This update causes the component to update again from useEffect().

Get height of element after render and on resize in React

If you want to get the height of an element after render and also on resize, here’s what you’ll do:

  1. Combine the useEffect() and useRef() hooks to get the element’s height before it renders, like in the previous section.
  2. Track the current height with state.
  3. Add a resize event listener to the window object in useEffect().
  4. In the event listener, get the new height of the element, and update the state with it.
JavaScript
import React, { useLayoutEffect, useState, useRef } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { const handleResize = () => { setHeight(elementRef.current.offsetHeight); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); } }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} </div> ); }

We call addEventListener() in useEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener, we update the state that stores the element’s height, and this causes a re-render.

We call removeEventListener() in useEffect‘s clean-up function, to stop listening for resize events when the component is unmounted or when the dependencies change, to prevent memory leaks and unintended side effects.

How to Get the Current Year in React

To get the current year in React, create a new Date object with the Date() constructor, then use the getFullYear() method to get the year of the DategetFullYear() will return a number that represents the current year.

JavaScript
import React from 'react'; function Footer() { const currentYear = new Date().getFullYear(); return ( <div> {currentYear} <div>&copy; {currentYear} Coding Beauty</div> </div> ); } export default Footer;
Displaying the current year in React.

We use the Date() constructor to create a new Date object. When Date() is called with no arguments, the Date object is created using the current date and time.

The Date getFullYear() method returns a number that represents the year of the Date. Since the Date object here stores the current date, getFullYear() returns the current year.

Get current month in React

If you also want to get the current month, the getMonth() method is for you.

getMonth() returns a zero-based index that represents the month of the Date. Zero-based here means that 0 = January, 1 = February, 2 = March, etc.

JavaScript
import React from 'react'; function MonthYear() { const currMonth = new Date().getMonth(); const currYear = new Date().getFullYear(); return <div>Month number {currMonth} in {currYear}</div>; } export default MonthYear;
The month number is displayed.

Get current month name

If you want the month name directly (the more likely case), the Date toLocaleString() method will do the job.

JavaScript
import React from 'react'; function MonthYear() { const currMonth = new Date().toLocaleString([], { month: 'long', }); const currYear = new Date().getFullYear(); return <div>{currMonth} in {currYear}</div>; } export default MonthYear;
Displaying the month name in React.

Check out this article for a full guide on how to convert a month number to its equivalent month name in JavaScript.

Get current day of month in React

Similarly, to get the current day in the month, you’d use the Date getDate() method:

JavaScript
import React from 'react'; function DateDisplay() { const currDay = new Date().getDate(); const currMonth = new Date().toLocaleString([], { month: 'long', }); const currYear = new Date().getFullYear(); return <div>{currMonth} {currDay}, {currYear}</div>; } export default DateDisplay;
The current day of the month is displayed.

Get current year, month, day, week…

While you could get each component of the date using different functions, a much more flexible and easy way to do this is by formatting the date in the given format with a format specifier.

We can carry out this formatting with the format() function from the date-fns library.

In the following example, we use date-fns format() to get the multiple individual parts of the date.

JavaScript
import React from 'react'; import { format } from 'date-fns'; function DateDisplay() { const dateString = format( new Date(), "EEEE, 'the' do 'of' LLLL, yyyy" ); return <div>{dateString}</div>; } export default DateDisplay;
Different parts of the date are displayed using formatting.

The format() function takes a pattern and returns a formatted date string in the format specified by the pattern. You can find a list of the patterns format() accepts here.

For our example, we use the following patterns:

  • EEEE: to get the full name of the day of the week.
  • do: to get the ordinal day of the month, i.e., 1st, 2nd, 3rd, etc.
  • LLLL: to get the full name of the month of the year.
  • yyyy: to get the full year.

We also use single quotes to escape strings (the and of) that are not patterns but should be included in the result of the formatting.

Key takeaways

  • To get the current year in React, use new Date().getFullYear().
  • To get the current month name, use toLocaleString() with the month: 'long' specifier.
  • To get the current day in the month, use the getDate() method.
  • Use the date-fns library’s format() function to easily format and obtain multiple parts of the date.

How to Get the Height of an Element After Render in React

To get the height of a React element after render in React, we can combine two hooks: useRef() and useEffect():

JavaScript
import React, { useEffect, useState, useRef } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useEffect(() => { setHeight(elementRef.current.offsetHeight); }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} </div> ); }

useEffect() runs after the component mounts or re-renders, unlike useLayoutEffect() that runs before. They both have a dependencies array that cause them to fire when any of those dependencies change.

We create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() to create a state that we update when useEffect() gets called. This update causes the component to update again from useEffect().

To get the actual height, we use the offsetHeight property, which includes borders, padding, and any scrollbars when calculating the element’s height.

It’s also possible to get the height of the entire window in React, instead of just one element.

Get height of element with clientHeight

clientHeight is another way to get the height of an element. Unlike offsetHeight, it includes padding but excludes borders and scrollbars.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useEffect(() => { setHeight(elementRef.current.clientHeight); }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} <p>This element's height is measured using clientHeight.</p> </div> ); }

Get height of element after render and on resize in React

To get the height of an element after render and on resize:

  1. Combine the useEffect() and useRef() hooks to get the element’s height before it renders.
  2. Track the current height with state.
  3. Add a resize event listener to the window object in useEffect().
  4. In the event listener, get the new height of the element, and update the state with it.
JavaScript
import React, { useLayoutEffect, useState, useRef } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useEffect(() => { const handleResize = () => { setHeight(elementRef.current.offsetHeight); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); } }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} </div> ); }

We call addEventListener() in useEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener, we update the state that stores the element’s height, and this causes a re-render.

We call removeEventListener() in useEffectβ€˜s clean-up function to stop listening for resize events when the component is unmounted or when the dependencies change to prevent memory leaks and unintended side effects.

Get height of element before render in React

To get the height of an element before render in React, we can combine two React hooks: useRef and useLayoutEffect.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { setHeight(elementRef.current.offsetHeight); }, [height]); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} </div> ); }

So the difference between “before render” and “after render” is useLayoutEffect() and useEffect().

useLayoutEffect() works just like useEffect(), but the key difference is that it fires before the browser repaints the screen – before React renders the component.

Here we create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() though, to create a state that we update when useLayoutEffect() gets called. So calling setHeight() will cause the component to be re-rendered.

To get the actual height, we use the offsetHeight property which includes borders, padding, and any scrollbars when calculating the element’s height.

Get height of element before render and on resize in React

To get the height of an element before render and also on resize:

  1. Combine the useLayoutEffect() and useRef() hooks to get the element’s height before it renders.
  2. Track the current height with state.
  3. Add a resize event listener to the window object in useLayoutEffect().
  4. In the event listener, get the new height of the element, and update the state with it.
JavaScript
import React, { useLayoutEffect, useState, useRef } from 'react'; function ExampleComponent() { const [height, setHeight] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { const handleResize = () => { setHeight(elementRef.current.offsetHeight); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); } }, []); return ( <div ref={elementRef}> {`The height of this element is: ${height}px`} </div> ); }

We call addEventListener() in useLayoutEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener, we update the state that stores the element’s height, and this causes a re-render.

We call removeEventListener() in useLayoutEffect‘s clean-up function, to stop listening for resize events when the component is unmounted or when the dependencies change, to prevent memory leaks and unintended side effects.

Key takeaways

  • To get the height of a React element after render, we can use the useRef() and useEffect() hooks.
  • The offsetHeight property includes borders, padding, and scrollbars, while clientHeight includes padding only.
  • To get the height of an element after render and on resize, we can use the useLayoutEffect() hook and add a resize event listener to the window object.
  • To get the height of an element before render, we can use useLayoutEffect() instead of useEffect().

How to Get the Width of an Element After Render in React

To get the width of a React element after render in React, we can combine two hooks: useRef() and useEffect():

JavaScript
import React, { useEffect, useState, useRef } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useEffect(() => { setWidth(elementRef.current.offsetWidth); }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} </div> ); }

useEffect() runs after the component mounts or re-renders, unlike useLayoutEffect() that runs before. They both have a dependencies array that cause them to fire when any of those dependencies change.

We create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() to create a state that we update when useEffect() gets called. This update causes the component to update again from useEffect().

It’s also possible to get the width of the entire window in React, instead of just one element.

Get width of element with clientWidth

clientWidth is another way to get the width of an element. Unlike offsetWidth, it includes padding but excludes borders and scrollbars.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useEffect(() => { setWidth(elementRef.current.clientWidth); }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} <p>This element's width is measured using clientWidth.</p> </div> ); }

Get width of element after render and on resize in React

To get the width of an element after render and on resize:

  1. Combine the useEffect() and useRef() hooks to get the element’s width before it renders, like in the previous section.
  2. Track the current width with state.
  3. Add a resize event listener to the window object in useEffect().
  4. In the event listener, get the new width of the element, and update the state with it.
JavaScript
import React, { useLayoutEffect, useState, useRef } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useEffect(() => { const handleResize = () => { setWidth(elementRef.current.offsetWidth); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); } }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} </div> ); }

We call addEventListener() in useEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener, we update the state that stores the element’s width, and this causes a re-render.

We call removeEventListener() in useEffect‘s clean-up function to stop listening for resize events when the component is unmounted or when the dependencies change to prevent memory leaks and unintended side effects.

Get width of element before render in React

To get the width and height of an element before render in React, we can combine two React hooks: useRef and useLayoutEffect.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { setWidth(elementRef.current.offsetWidth); }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} </div> ); }

So the difference between “before render” and “after render” is useLayoutEffect() and useEffect().

useLayoutEffect() works just like useEffect(), but the key difference is that it fires before the browser repaints the screen – before React renders the component.

We pass an empty dependencies array to useLayoutEffect() to make sure it only gets called once.

Here we create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() though, to create a state that we update when useLayoutEffect() gets called. So calling setWidth() will cause the component to be re-rendered.

To get the actual width, we use the offsetWidth property which includes borders, padding, and any scrollbars when calculating the element’s width.

Get width of element before render and on resize in React

To get the width of an element before render and also on resize:

  1. Combine the useLayoutEffect() and useRef() hooks to get the element’s width before it renders, like in the previous section.
  2. Track the current width with state.
  3. Add a resize event listener to the window object in useLayoutEffect().
  4. In the event listener, get the new width of the element, and update the state with it.
JavaScript
import React, { useLayoutEffect, useState, useRef } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { const handleResize = () => { setWidth(elementRef.current.offsetWidth); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); } }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} </div> ); }

We call addEventListener() in useLayoutEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener, we update the state that stores the element’s width, and this causes a re-render.

We call removeEventListener() in useLayoutEffect‘s clean-up function, to stop listening for resize events when the component is unmounted or when the dependencies change, to prevent memory leaks and unintended side effects.

Key takeaways

  • To get the width of a React element after it renders, we can combine the useRef() and useEffect() hooks.
  • The offsetWidth property includes borders, padding, and scrollbars, while clientWidth includes padding only.
  • To get the width of an element before render, use useLayoutEffect() instead of useEffect().
  • To get the width of an element on resize, add a resize event listener to the window object in useEffect() or useLayoutEffect().

How to Get the Width of an Element Before Render in React

To get the width of an element before render in React, we can combine two React hooks: useRef and useLayoutEffect.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { setWidth(elementRef.current.offsetWidth); }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} </div> ); }

See also: How to Get the Height of an Element Before Render in React

useLayoutEffect() works just like useEffect(), but the key difference is that it fires before the browser repaints the screen – before React renders the component.

We pass an empty dependencies array to useLayoutEffect() to make sure it only gets called once.

Here we create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() though, to create a state that we update when useLayoutEffect() gets called. So calling setWidth() will cause the component to be re-rendered.

To get the actual width, we use the offsetWidth property which includes borders, padding, and any scrollbars when calculating the element’s width.

It’s also possible to get the width of the entire window in React, instead of just one element.

Get width of element with clientWidth

clientWidth is another way to get the width of an element. Unlike offsetWidth, it includes padding but excludes borders and scrollbars.

JavaScript
import React, { useRef, useLayoutEffect, useState } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { setWidth(elementRef.current.clientWidth); }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} <p>This element's width is measured using clientWidth.</p> </div> ); }

Get width of element before render and on resize in React

If you want to get the width of an element before render and also on resize, here’s what you’ll do:

  1. Combine the useLayoutEffect() and useRef() hooks to get the element’s width before it renders, like in the previous section.
  2. Track the current width with state.
  3. Add a resize event listener to the window object in useLayoutEffect().
  4. In the event listener, get the new width of the element, and update the state with it.

So it’s similar to what we did previously, but we’re adding a resize event listener this time.

JavaScript
import React, { useLayoutEffect, useState, useRef } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useLayoutEffect(() => { const handleResize = () => { setWidth(elementRef.current.offsetWidth); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); } }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} </div> ); }

We call addEventListener() in useLayoutEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener we update the state that stores the element’s width, and this causes a re-render.

We call removeEventListener() in useLayoutEffect‘s clean-up function, to stop listening for resize events when the component is unmounted or when the dependencies change, to prevent memory leaks and unintended side effects.

Get width of element after render in React

We can also get the width of a React element after it renders in React, by combining the useRef() and useEffect() hooks.

JavaScript
import React, { useEffect, useState, useRef } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useEffect(() => { setWidth(elementRef.current.offsetWidth); }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} </div> ); }

So the difference between “before render” and “after render” is useLayoutEffect() and useEffect().

useEffect() runs after the component mounts or re-renders, unlike useLayoutEffect() that runs before. They both have a dependencies array that cause them to fire when any of those dependencies change.

As earlier, we create a ref for the target element with useRef(), and assign it to its ref prop, so we can access the HTMLElement object for this React element.

useRef returns a mutable ref object that doesn’t change its value when a component is updated. Also, modifying the value of this object’s current property does not cause a re-render. This is in contrast to the setState update function returned from useState.

We do use useState() to create a state that we update when useEffect() gets called. This update causes the component to update again from useEffect().

Get width of element after render and on resize in React

If you want to get the width of an element after render and also on resize, here’s what you’ll do:

  1. Combine the useEffect() and useRef() hooks to get the element’s width before it renders, like in the previous section.
  2. Track the current width with state.
  3. Add a resize event listener to the window object in useEffect().
  4. In the event listener, get the new width of the element, and update the state with it.
JavaScript
import React, { useLayoutEffect, useState, useRef } from 'react'; function ExampleComponent() { const [width, setWidth] = useState(0); const elementRef = useRef(null); useEffect(() => { const handleResize = () => { setWidth(elementRef.current.offsetWidth); }; handleResize(); window.addEventListener('resize', handleResize); return () => { window.removeEventListener('resize', handleResize); } }, []); return ( <div ref={elementRef}> {`The width of this element is: ${width}px`} </div> ); }

We call addEventListener() in useEffect() to set the resize event listener on the element before it renders on the screen.

The resize event listener is called whenever the user resizes the window. In the listener, we update the state that stores the element’s width, and this causes a re-render.

We call removeEventListener() in useEffect‘s clean-up function, to stop listening for resize events when the component is unmounted or when the dependencies change, to prevent memory leaks and unintended side effects.

req.body is undefined in Express? Here’s what to do

The req body undefined error occurs in an Express server when you fail to parse incoming POST request data with middleware from the body-parser NPM package. To fix it, install body-parser and parse the request with the json or the urlencoded middleware.

For example:

JavaScript
import express from 'express'; const app = express(); app.post('/register', (req, res) => { // ❌ req.body is undefined const email = req.body.email; const password = req.body.password; // do something with email and password... }); app.listen(3000, () => console.log('Server started'));

When a POST request comes in, we end up getting the cannot read property of undefined error.

To fix the error, first we install body-parser from NPM:

Shell
npm i body-parser

If we’re expecting JSON requests, we can use the json() middleware:

JavaScript
// πŸ‘‡ use body-parser to parse JSON bodies app.post('/register', bodyParser.json(), (req, res) => { // βœ… Now we can access the JSON body using `req.body` const email = req.body.email; const password = req.body.password; // do something with email and password... });

We use urlencoded() when we expect the data to be in a URL-encoded format, like from forms:

JavaScript
import express from 'express'; import bodyParser from 'body-parser'; const app = express(); // πŸ‘‡ URL-encoded request body app.post('/register', bodyParser.urlencoded(), (req, res) => { // βœ… req.body is now a JavaScript object const email = req.body.email; const password = req.body.password; // do something with email and password... }); app.listen(3000, () => console.log('Server started'));

POST requests and Express req.body

One great thing Express provides that makes life easier is the body property of the request object. Without it, reading POST data would be much more complex than accessing a property.

Internally, Express uses the data and end properties of the Request object from the native http module to read POST data. Here’s a basic example of how it works; what we’d have to do if we didn’t use a framework like Express:

JavaScript
import http from 'http'; http .createServer((req, res) => { // listen for post data let body = ''; req.on('data', (chunk) => { body += chunk; }); req.on('end', () => { // like using the json() method from body-parser req.body = JSON.parse(body); const email = req.body.email; const password = req.body.password; // do something with email and password... }); }) .listen(3000, () => console.log('Server started'));

How to make POST requests with Postman

Postman is a popular tool for testing APIs and making HTTP requests. We can use it to make POST requests easily, here’s a demo of how:

Making HTTP POST requests to the Express server using Postman.

As you can see, we can pass different body formats in the POST request. In this demo, we set the raw type and selected the JSON sub-type to specify a JSON content type.

You can also see the editor where we put in body data for the request. Postman makes provides JSON syntax highlighting to make things more readable.

To make the request we can use the send button or the Ctrl + Enter keyboard shorcut. In this case, the server simply responds with the input it received:

JavaScript
app.post('/register', bodyParser.json(), (req, res) => { const email = req.body.email; const password = req.body.password; res.send(`Email: ${email}, password: ${password}`); });

Key takeaways

  • The “req body undefined” error occurs in Express when POST request data isn’t parsed using the body-parser middleware.
  • Install body-parser and use either json() or urlencoded() middleware to parse incoming POST data.
  • Express simplifies reading POST data by providing the body property.
  • Postman is a useful tool for testing APIs and making HTTP requests, including POST requests.

How to Check if a Character Is a Letter in JavaScript

To check if a character is a letter in JavaScript, lowercase the character and compare it to the uppercased version, i.e., char.toLowerCase() !== char.toUpperCase(). If the result is false, the character is a letter. Otherwise, it isn’t.

For example:

JavaScript
function isCharLetter(char) { return char.toLowerCase() !== char.toUpperCase(); } console.log(isCharLetter('a')); // true console.log(isCharLetter('E')); // true console.log(isCharLetter('d')); // true console.log(isCharLetter('-')); // false console.log(isCharLetter('?')); // false

Note: This only works for most Latin, Greek, Armenian, and Cyrillic scripts. It won’t work for Chinese, Japanese, Arabic, Hebrew, or most other scripts.

One use for checking if a character is a letter is to validate forms. For example, if you have a form where a user needs to enter their name, you might want to ensure that only letters are entered, and not numbers or special characters.

We know that Latin letters have lowercase and uppercase forms that are different, so we take advantage of this using inequality.

JavaScript
console.log('z'.toLowerCase() !== 'z'.toUpperCase()); // true console.log('ΠΆ'.toLowerCase() !== 'ΠΆ'.toUpperCase()); // true

Non-letters, on the other hand, don’t have lowercase and uppercase forms; both toLowerCase() and toUpperCase() always give the same result.

JavaScript
console.log('.'.toLowerCase() === '.'.toUpperCase()); // true console.log('$'.toLowerCase() === '$'.toUpperCase()); // true console.log('='.toLowerCase() === '='.toUpperCase()); // true

Check if character is letter with regex

Alternatively, we can check if a character is a letter in JavaScript by calling the test() method on this regex: /^[a-z]$/i.

JavaScript
function isCharLetter(char) { return /^[a-z]$/i.test(char); } console.log(isCharLetter('g')); // true console.log(isCharLetter('Q')); // true console.log(isCharLetter('word')); // false console.log(isCharLetter('_')); // false console.log(isCharLetter('$')); // false

The RegExp test() method checks if a string matches the regular expression you specify. It returns true if there is a match, and false if there isn’t.

The forward slashes / / marks the start and end of the regular expression.

The ^ (caret) symbol indicates that the regex match must start from the beginning of the string. In this case, the letter must be the string’s first character.

The square brackets define a character set, which is a list of characters that can match any character at that position in the input string. In this case, [a-z] matches any single lowercase letter from a to z.

The $ symbol indicates that the regex pattern must be at the very end of the string. In this case, the letter must be the string’s last character. Combining ^ an $ in this way, ensures that the string is a single character.

The i flag lets us perform a case-insensitive search for the pattern. With i, we can omit the A-Z range that matches uppercase letters.

For a comprehensive guide to regular expression syntax, check out this cheat sheet from the MDN docs

Check if string contains letters

To instead check if a string contains any letters, we’ll use a different regex: /[a-z]/i

JavaScript
function containsLetter(str) { return /[a-z]/i.test(str); } console.log(containsLetter('code')); // true console.log(containsLetter('Q')); // true console.log(containsLetter('word')); // true console.log(containsLetter('_')); // false console.log(containsLetter('$')); // false

This is similar to the previous regex, except that we’ve removed the $ and ^ so that the search can occur at any point in the string, and a multi-character string containing at least one letter can be matched.

Check if string contains only letters

For checking if the string contains only letters, we’ll bring the $ and ^ back, and add a + before $:

JavaScript
function containsOnlyLetters(str) { return /^[a-z]+$/i.test(str); } console.log(containsOnlyLetters('code')); // true console.log(containsOnlyLetters('word')); // true console.log(containsOnlyLetters('coding_beauty')); // false console.log(containsOnlyLetters('s p a c e s')); // false console.log(containsOnlyLetters('8pm')); // false

With $ and ^ back again, the pattern is only matched if it’s the only pattern in the string. [a-z]+ only matches a consecutive series of letters. So altogether, the regex only matches strings that contain a continuous series of letters from the start to the end of the string.

Key takeaways

  • To check if a character is a letter, compare its lowercased and uppercased versions using char.toLowerCase() !== char.toUpperCase(). We can only regex by calling test() on /^[a-z]$/i.
  • To check if a string contains any letters, use the regex /[a-z]/i.
  • To check if a string contains only letters, use the regex /^[a-z]+$/i.

How to create a PDF from any HTML page or form using only JavaScript

With the jspdf library, we can easily convert any HTML page or form to a PDF:

For example:

JavaScript
import { jsPDF } from 'jspdf'; const pdfContentEl = document.getElementById('pdf-content'); const doc = new jsPDF(); await doc.html(pdfContentEl.innerHTML).save('test.pdf');

PDF is a popular file format we use to present and share documents with a fixed layout across different platforms and devices.

To start the conversion, we create a new jsPDF object with the constructor. Then we call the html() method, passing the element with the contents we want to be in the PDF. On the result, we call save(), passing our desired name of the output PDF file.

Let’s say we had HTML like this:

HTML
<div id="pdf-content"> <h1>Test</h1> <p>Here's what we're saving to PDF</p> </div> <button id="save-pdf">Save PDF</button>

with an output on the webpage like this:

The web page containing the PDF target HTML element.

When we click the “Save PDF” button, jsPDF will create a new PDF from the HTML element and download it as a file in the browser

Here’s what displays when we open the PDF:

The contents of the downloaded PDF.

Install jsPDF

To get started with the jsPDF library, we can install it from NPM with this command.

Shell
npm i jspdf

After the installation, we’ll be able to import it into a JavaScript file, like this:

JavaScript
import { jsPDF } from 'jspdf';

For this file to work in the HTML, we can use a module bundler like Parcel, which is what I use.

With Parcel, we can include the script in the HTML like this:

JavaScript
<script type="module" src="index.js"></script>

We can use modern tools like TypeScript and ES module imports in the script, and it will work just fine because of Parcel.

As far as we run the HTML with npx parcel my-file.html after installing Parcel with npm install parcel.

Shell
npm install parcel npx parcel my-file.html

Parcel makes the HTML available at localhost:1234, as you might have seen in the demo above.

Customize HTML to PDF conversion

The jsPDF constructor accepts an options object that customizes the PDF conversion process.

For example, the orientation option sets the orientation of the resulting PDF.

By default, it’s portrait, but we can set it to landscape.

Customize PDF orientation

JavaScript
const doc = new jsPDF({ orientation: 'landscape' });

Customize PDF unit and dimensions

With the unit and format options, we can set the unit and dimensions of each PDF page in the output file.

JavaScript
const doc = new jsPDF({ orientation: 'l', unit: 'in', format: [4, 2] });

Here we specify a landscape export that is 2 by 4 inches.

Convert HTML form to PDF

jsPDF also works with HTML elements whose appearance can change dynamically from user interaction, like form inputs.

HTML
<form id="form"> <input type="email" name="email" id="email" placeholder="Email" /> <br /> <input type="password" name="password" id="password" placeholder="Password" /> <br /><br /> <button type="submit">Submit</button> </form> <br /> <button id="save-pdf">Save PDF</button>
JavaScript
import { jsPDF } from 'jspdf'; const doc = new jsPDF(); const savePdf = document.getElementById('save-pdf'); const formEl = document.getElementById('form'); savePdf.addEventListener('click', async () => { await doc.html(formEl).save('test.pdf'); });

In the webpage, we’ve put in some test values in the two form inputs, to see that they display in the PDF output.

The PDF:

We can’t interact with the form inputs or button in the PDF file though.

Key takeaways

The jsPDF library provides a convenient way to convert HTML content, including forms, to PDF format. The entire process is pretty easy, as we can create a new jsPDF object, call the html() method to specify the content, and then use the save() method to generate the output file. Plus, we can customize the PDF output with options like orientation, unit, and format. Overall, using jsPDF simplifies creating PDF files from HTML content in our web apps.

How to Get the Length of a Map in JavaScript

To get the length of a map in JavaScript, we use it’s size property, e.g., console.log(map.size).

JavaScript
const map = new Map(); map.set('user1', 'John'); map.set('user2', 'Kate'); map.set('user3', 'Peter'); // πŸ‘‡ Get length of map console.log(map.size); // 3

Map size, set(), and delete() methods

A Map object’s size property stores of key-value pairs in the object.

As the set() method adds elements and delete() removes them, the size property changes accordingly.

When we add a new element to a map with the set() method, the size property goes up by 1. In the same way, when we remove an element from the map with delete() the size goes down by 1.

JavaScript
const map = new Map(); map.set('user1', 'John'); console.log(map.size); // 1 map.set('user2', 'Kate'); console.log(map.size); // 2 map.delete('user1'); console.log(map.size); // 1

Map size vs Array length

Of course, a map and an array serve different purposes, but each has a property that gives the length of items it stores, length for arrays, and size for maps.

One key difference between the two is that you can change an array’s length property directly.

JavaScript
const arr = []; arr.push('Pat'); arr.push('Matt'); console.log(arr.length); // 2 // πŸ‘‡ Array length changed arr.length = 1; console.log(arr.length); // 1

but you can’t do the same for maps:

JavaScript
const map = new Map(); map.set('user1', 'Pat'); map.set('user2', 'Matt'); console.log(map.size); // 2 map.size = 5; // πŸ‘‡ length can't be modified directly console.log(map.size); // 2

You can only change size with methods like set() and delete(), as we saw earlier.

When you change Array length to a lesser value directly, elements are chopped off the end.

JavaScript
const arr = ['Pat', 'Matt']; // πŸ‘‡ Length decreased directly arr.length = 1; // No more 'Matt' console.log(arr); // ['Pat']

On the other hand, when you directly change the Array length to a greater value, empty placeholder elements get added from the end of the array:

JavaScript
const arr = ['Pat', 'Matt']; // πŸ‘‡ Length increase directly arr.length = 3; // Empty item added console.log(arr); // [ 'Pat', 'Matt', <1 empty item> ]

While this works, I would recommend Array splice() to remove elements from an array, so you have greater control over the deletion and can access the deleted elements.

With splice() you can set the start index for the deletion, the number of elements to delete, and new elements that should be inserted in their place.

JavaScript
const arr = ['Pat', 'Matt']; // Delete 1 element at index 1 (2nd element) const deleted = arr.splice(1, 1); console.log(deleted); // ['Matt'] const arr2 = ['Pat', 'Matt']; // Delete 1 element at index 1 (2nd element) and insert 'John' at index 1 const deleted2 = arr2.splice(1, 1, 'John'); console.log(deleted2); // ['Matt']

Clear Map with clear() method

What the Map clear() method does should be pretty obvious from its name; it clears the map of all its elements:

JavaScript
const map = new Map(); map.set('user1', 'John'); map.set('user2', 'Kate'); map.set('user3', 'Peter'); console.log(map.size); // 3 map.clear(); console.log(map.size); // 0

Key takeaways

  • To get the length of a map in JavaScript, use the size property of the map object.
  • size updates when you add or remove elements with set(), delete() or clear().
  • Unlike arrays, you can’t change the size of a map directly.

How to Easily Handle the onPaste Event in React

To handle the onPaste event on a React element, set its onPaste prop to an event handler. You can get the pasted text from the handler using event.clipboardData.getData('text').

For example:

JavaScript
import React, { useState } from 'react'; export default function App() { const [pasted, setPasted] = useState(''); const handlePaste = (event) => { setPasted(event.clipboardData.getData('text')); }; return ( <div> <input placeholder="Message" onPaste={handlePaste} type="text" id="message" /> <br /> You pasted: <b>{pasted}</b> </div> ); }
Handling the onPaste event on an element in React

The function (event listener) passed to the onPaste prop is called when the user pastes text into the input field.

The event object has various properties and methods used to get more info and take actions concerned with the event.

For the paste event, event has a clipboardData property that stores the data stored on the clipboard.

getData() gives us the data in the clipboard in a particular format. We pass 'text' as the first argument to get text data.

For the purposes of our example, we create a state that’ll be updated to the latest text data pasted in the input field. We display this text to the user.

Note: We used the useState hook to manage the state. This hook returns an array of two values, where the first is a variable that stores the state, and the second is a function that updates the state when it is called.

Handle onPaste event in entire window

To handle the paste event on the entire document window in React, set a paste event handler on the window object with addEventListener():

JavaScript
import React, { useState, useEffect } from 'react'; export default function App() { const [pasted, setPasted] = useState(''); useEffect(() => { const handlePaste = (event) => { setPasted(event.clipboardData.getData('text')); } window.addEventListener('paste', handlePaste) return () => { window.removeEventListener('paste', handlePaste) }; }) return ( <div> Pasted: <b>{pasted}</b> <br /> <input placeholder="Message" type="text" id="message" /> <br /> <input placeholder="Sender" type="text" id="sender" /> </div> ); }
Handling the onPaste event in the entire window in React

The addEventListener() method takes up to two arguments:

  1. type: a string representing the event type to listen for. 'paste' is for a paste event.
  2. listener: the function called when the event fires.

It also takes some optional arguments, which you can learn more about here.

We call addEventListener() in the useEffect hook to register the listener once the component renders as the page loads. We pass an empty dependencies array to useEffect so this registration happens only once. In the cleanup function, we call the removeEventListener() method to unregister the event listener and prevent a memory leak.

As we saw earlier, the event object has many methods and properties that let us get more info and take event-related actions.

For the paste event, event has a clipboardData property that contains the data stored on the clipboard.

The clipboard.getData() is the clipboard data in a specific format. Like before, we pass 'text' as the first argument to get text data.

Get clipboard data without paste

We may not want to wait for the user to do a paste before getting the clipboard data. In a case like this, the clipboard.readText() method from the navigator object helps:

JavaScript
import React, { useState } from 'react'; export default function App() { const [pasted, setPasted] = useState(''); const handlePaste = async (_event) => { const clipboardText = await navigator.clipboard.readText(); setPasted(clipboardText); } return ( <div> Pasted: <b>{pasted}</b><br /> <button onClick={handlePaste}>Paste</button> </div> ); }
Getting the clipboard data without pasting.

Here we wait for a click before getting the text in the clipboard.

readText() is an async method, so we await it in an async event handler to get the Promise‘s result.

Note

Before the browser can read clipboard data, it’ll show the user a dialog to grant permission first:

Browser shows popup to grant clipboard permissions.

Prevent onPaste event in React

Like for many other events, we can prevent the default UI action of the paste event with event.preventDefault() in the handler:

JavaScript
import React, { useState, useEffect } from 'react'; export default function App() { const [pasted, setPasted] = useState(''); useEffect(() => { const handlePaste = (event) => { // πŸ‘‡ Prevent default paste UI action event.preventDefault(); setPasted(event.clipboardData.getData('text')); } window.addEventListener('paste', handlePaste) return () => { window.removeEventListener('paste', handlePaste) }; }) return ( <div> Pasted: <b>{pasted}</b> <br /> <input placeholder="Message" type="text" id="message" /> <br /> <input placeholder="Sender" type="text" id="sender" /> </div> ); }
Preventing the default paste action.

Key takeaways

To listen for pastes on an element and get clipboard text, we can use the event.clipboardData.getData() method. We can also handle pasted events on the entire window with window.addEventListener() and prevent the default UI action using event.preventDefault().

To get clipboard data without pasting, we use the clipboard.readText() method. These methods are useful for copying and pasting text between fields and preventing pasting behavior we don’t want.