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 to Scroll to an Element in Vue.js

To scroll to an element in Vue.js:

  1. Set a ref on the target element.
  2. Call scrollIntoView() on the target ref.
HTML
// Set ref on target element <div ref="targetRef" style="background-color: lightblue;"> My Target Element </div>
JavaScript
// Scroll to element this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' });

We can use this approach to scroll to an element when another trigger element is clicked.

We’ll first need to set a click event listener on the trigger element.

Then we’ll call scrollIntoView() in the listener.

App.vue
<template> <div id="app"> <button @click="handleClick">Scroll to element</button> <div style="height: 150rem;"></div> <div ref="targetRef" style="background-color: lightblue;"> Coding Beauty </div> <div style="height: 150rem;"></div> </div> </template> <script> export default { data() { return { ref: null }; }, methods: { handleClick() { this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' }); } } }; </script>
Using the button to scroll down to an element in Vue.js.

Scrolling on click is great for quick navigation.

It improves the user experience.

It’s great for long lists and pages with many sections.

It makes apps more interactive with smooth-scrolling animations.

We set the ref prop of the target element to create a Vue ref.

Doing this lets us access the component’s HTML element directly from the $refs instance property.

We use the @click event to set an event listener that will be called when the trigger element is clicked.

App.vue
<button @click="handleClick">Scroll to element</button>
App.vue
methods: { handleClick() { this.$refs.targetRef.scrollIntoView({ behavior: 'smooth' }); } }

We can use this same combo of refs and scrollIntoView() to scroll to an element in React.

In the click listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto.

auto is the default.

Scroll to dynamic element on click in Vue.js

We can do something similar to scroll to a dynamically created element in Vue.js:

App.vue
<template> <div id="app"> <div style=" position: fixed; background-color: white; bottom: 0; margin-bottom: 10px; " > <button @click="addFruit">Add fruit</button> <button @click="scrollToLastFruit" style="margin-left: 8px" > Scroll to last </button> </div> <div style="height: 5rem"></div> <div ref="fruitList"> <h2 v-for="fruit in fruits" :key="fruit" > {{ fruit }} </h2> </div> <div style="height: 150rem"></div> </div> </template> <script> const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default { data() { return { fruits: allFruits.slice(0, 3), }; }, methods: { addFruit() { this.fruits.push(allFruits[this.fruits.length]); }, scrollToLastFruit() { const lastChildElement = this.$refs.fruitList.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>
Scrolling to a dynamic element in Vue.js.

Here we have a list of fruits displayed.

The Add fruit button dynamically adds an item to the fruit list on click.

Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the @click event to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant.

Doing this sets the Vue instance’s $refs.inputList property to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

App.vue
methods: { addFruit() { this.fruits.push(allFruits[this.fruits.length]); }, scrollToLastFruit() { const lastChildElement = this.$refs.fruitList.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth', }); }, },

Scroll to element after render in Vue.js

To scroll to an element after render in Vue.js:

  1. Set a ref on the element
  2. Create a mounted lifecycle hook to run code just after the component mounts.
  3. Call scrollIntoView() on the ref object in the mounted hook.
App.vue
<template> <div> <div style="height: 150rem"></div> <div ref="target" style="background-color: blue; color: white" > Coding Beauty </div> <div style="height: 150rem"></div> </div> </template> <script> export default { mounted() { this.scrollToElement(); }, methods: { scrollToElement() { this.$refs.target.scrollIntoView({ behavior: 'smooth', }); }, }, }; </script>
Scrolling to an element after render in Vue.js

Scrolling after page loads help users find info.

It also helps fix errors.

It’s great for those who use special software.

It makes browsing the webpage easier.

We create a Vue ref by setting the target element’s ref prop to a string ("target")

We’ll then be able to access the HTMLElement object representing this object from the $refs property of the Vue instance (this.$refs.target).

The mounted method is a Vue lifecycle hook that runs just after the component has mounted. This is similar to useEffect in React.

In mounted, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame (auto).

auto is the default.

Key takeaways

  • To scroll to an element in Vue, set a ref on the target element and call scrollIntoView() on the ref.
  • To scroll to a dynamically created element in Vue.js, set the ref on the list element and use lastElementChild to scroll to its last item.
  • To scroll to an element after render in Vue.js, create a mounted lifecycle hook and call scrollIntoView() on the ref object in the mounted hook.

How to Scroll to an Element in React

To scroll to an element in React, set a ref on the target element, then call scrollIntoView() on the target ref.

We can use this approach to scroll to an element when another trigger element is clicked.

We’ll first need to set a click event listener on the trigger element.

Then we’ll call scrollIntoView() in the listener.

JavaScript
import { useRef } from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <button onClick={handleClick}>Scroll to element</button> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'lightblue' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to an element on click in React

Scrolling on click is great for quick navigation.

It improves the user experience.

It’s great for long lists and pages with many sections.

It makes apps more interactive with smooth-scrolling animations.

We create a ref object with the useRef hook and assign it to the ref prop of the target div element.

Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates.

Also, modifying the value of this object’s current property doesn’t cause a re-render.

This is unlike the setState update function return from the useState hook.

We use the onClick on the button to a click listener to it. So, this listener will be called when the user clicks the button.

JavaScript
const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); };

In the handleClick listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto.

auto is the default.

Scroll to dynamic element on click in React

We can do something similar to scroll to a dynamically created element in React:

JavaScript
import { useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit</button> <button onClick={scrollToLastFruit} style={{ marginLeft: '8px' }}> Scroll to last </button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a dynamic element on click in React.

Here we have a list of fruits displayed.

The Add fruit button dynamically adds an item to the fruit list on click.

Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the onClick prop to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant.

Doing this sets the current property of the ref object to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

JavaScript
const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); };

Scroll to element after render in React

To scroll to an element after render on React:

  1. Set a ref on the element.
  2. Create a useEffect hook to run code just after the component mounts.
  3. Call scrollIntoView() on the ref object in useEffect.
JavaScript
import { useEffect, useRef } from 'react'; export default function App() { const ref = useRef(null); const scrollToElement = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToElement(); }, []); return ( <div> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'blue', color: 'white' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a particular element after render in React.

Scrolling after page loads help users find info.

It also helps fix errors.

It’s great for those who use special software.

It aids web navigation.

Like before, we create a ref object with the useRef hook and assign it to the ref prop of the target div element.

Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates.

Also, modifying the value of this object’s current property doesn’t cause a re-render.

This is unlike the setState update function return from the useState hooks.

The useEffect hook performs an action after the component renders, and when one or more of its dependencies change.

We passed an empty dependencies array ([]) to make sure that action only runs when the component mounts.

In useEffect, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behavior option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame (auto).

auto is the default.

Key takeaways

In React, we can use refs to scroll to a specific element on the page.

We can set a click event listener on a trigger element and call scrollIntoView() on the target ref to scroll to the desired element.

useRef() returns a mutable object that maintains its value when a component updates, allowing us to reference DOM elements.

Setting a ref on a list container allows us to dynamically scroll to the last item in the list.

We can use useEffect() to scroll to an element after the component mounts, improving the user experience and aiding web navigation.

Setting the behavior option to smooth in scrollIntoView() produces a smooth scrolling animation instead of an abrupt jump to the element.

How to Scroll to an Element After Render in React

To scroll to an element after render on React:

  1. Set a ref on the element.
  2. Create a useEffect hook to run code just after the component mounts.
  3. Call scrollIntoView() on the ref object in useEffect.
JavaScript
import { useEffect, useRef } from 'react'; export default function App() { const ref = useRef(null); const scrollToElement = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToElement(); }, []); return ( <div> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'blue', color: 'white' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a particular element after render in React.

Scrolling to an element after the page loads in React helps users quickly find important information, fix errors, and is useful for those who use special software to navigate the web.

We create a ref object with the useRef hook and assign it to the ref prop of the target div element. Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates. Also, modifying the value of this object’s current property doesn’t cause a re-render. This is unlike the setState update function return from the useState hooks.

The useEffect hook performs an action after the component renders, and when one or more of its dependencies change. We passed an empty dependencies array ([]) to make sure that action only runs when the component mounts.

In useEffect, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behaviour option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame (auto). auto is the default.

Scroll to element on click in React

Learn more: How to Scroll to an Element on Click in React

We can do something similar to scroll to an element on click in React:

  1. Set a ref on the target element.
  2. Set a click listener on the element meant to cause the scroll.
  3. In the click event listener, call the scrollIntoView() method on the ref object.
JavaScript
import { useRef } from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <button onClick={handleClick}>Scroll to element</button> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'lightblue' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to an element on click.

Scrolling to an element on click improves user experience by allowing for quick navigation, especially for long lists or pages with multiple sections. It can also add a touch of interactivity through smooth-scrolling animations.

We create a ref object with the useRef hook and assign it to the ref prop of the checkbox input. Doing this sets the current property of the ref object to the DOM object that represents the target element.

useRef returns a mutable object that retains its value when a component updates. Changing the value of this object’s current property doesn’t cause a re-render. This is different from the setState update function that useState returns.

We use the onClick on the button to a click listener to it. So, this listener will be called when the user clicks the button.

JavaScript
const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); };

In the handleClick listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

As before, we set the behaviour option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – autoauto is the default.

Scroll to dynamic element on click in React

We can also scroll to a dynamically created element in React.

JavaScript
import { useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit</button> <button onClick={scrollToLastFruit} style={{ marginLeft: '8px' }}> Scroll to last </button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a dynamic element on click in React.

Here we have a list of fruits displayed. The Add fruit button dynamically adds an item to the fruit list on click. Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the onClick prop to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant. Doing this sets the current property of the ref object to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

JavaScript
const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); };

Key takeaways

  • To scroll to an element after render, set a ref on the element, then call scrollIntoView() on the ref object in useEffect.
  • To scroll to an element on click, set a click listener on the element and call scrollIntoView() on the ref object in the click event listener.
  • To scroll to a dynamic element on click, set the ref on the list, use lastElementChild to get the last item element and call scrollIntoView() on it.

How to Scroll to an Element on Click in React

To scroll to an element on click in React:

  1. Set a ref on the target element.
  2. Set a click listener on the element meant to cause the scroll on click.
  3. In the click event listener, call the scrollIntoView() method on the ref object.
App.jsx
import { useRef } from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <button onClick={handleClick}>Scroll to element</button> <div style={{ height: '150rem' }} /> <div ref={ref} style={{ backgroundColor: 'lightblue' }}> Coding Beauty </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to an element on click in React

Scrolling to an element on click improves user experience by allowing for quick navigation, especially for long lists or pages with multiple sections. It can also add a touch of interactivity to navigation through smooth-scrolling animations.

We create a ref object with the useRef hook and assign it to the ref prop of the target div element. Doing this sets the current property of the ref object to the DOM object that represents the element.

useRef returns a mutable object that maintains its value when a component updates. Also, modifying the value of this object’s current property doesn’t cause a re-render. This is unlike the setState update function return from the useState hook.

We use the onClick on the button to a click listener to it. So, this listener will be called when the user clicks the button.

App.jsx
const handleClick = () => { ref.current?.scrollIntoView({ behavior: 'smooth' }); };

In the handleClick listener, we call the scrollIntoView() method on the ref of the target div element to scroll down to it and display it to the user.

We set the behaviour option to smooth to make the element scroll into view in an animated way, instead of jumping straight to the element in the next frame – auto. auto is the default.

Scroll to dynamic element on click in React

We can do something similar to scroll to a dynamically created element in React:

App.jsx
import { useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit</button> <button onClick={scrollToLastFruit} style={{ marginLeft: '8px' }}> Scroll to last </button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }
Scrolling to a dynamic element on click in React.

Here we have a list of fruits displayed. The Add fruit button dynamically adds an item to the fruit list on click. Then the Scroll to last button scrolls to this item on click, as it’s the last in the list.

Like before, we use the onClick prop to set a click event listener on the button.

This time we set the ref on the list instead of the items since the items are created dynamically, and the last item will not be constant. Doing this sets the current property of the ref object to the DOM object that represents the list element.

In this listener, we use the lastElementChild property of the list element to get its last item element. Then we call scrollIntoView() on this last item to scroll down to it.

JavaScript
const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); };

Create and scroll to dynamic element on click

We can also combine the element creation and scroll as a single action caused by a button click.

To do this, we’ll add a useEffect hook to call scrollToLastFruit() whenever the fruits state array changes.

App.jsx
const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; // 👇 Call `scrollToLastFruit()` when `fruits` changes. useEffect(() => { scrollToLastFruit(); }, [fruits]);
Creating and scrolling to a dynamic element on click in React.

Here’s the full code for reference:

App.jsx
import { useEffect, useRef, useState } from 'react'; const allFruits = [ 'Apples', 'Bananas', 'Oranges', 'Grapes', 'Strawberries', 'Blueberries', 'Pineapples', 'Mangoes', 'Kiwis', 'Watermelons', ]; export default function App() { const ref = useRef(null); const [fruits, setFruits] = useState([...allFruits.slice(0, 3)]); const addFruit = () => { setFruits((prevFruits) => [...prevFruits, allFruits[prevFruits.length]]); }; const scrollToLastFruit = () => { const lastChildElement = ref.current?.lastElementChild; lastChildElement?.scrollIntoView({ behavior: 'smooth' }); }; useEffect(() => { scrollToLastFruit(); }, [fruits]); return ( <div> <div style={{ position: 'fixed', backgroundColor: 'white', bottom: 0, marginBottom: 10, }} > <button onClick={addFruit}>Add fruit and scroll</button> </div> <div style={{ height: '5rem' }} /> <div ref={ref}> {fruits.map((fruit) => ( <h2 key={fruit}>{fruit}</h2> ))} </div> <div style={{ height: '150rem' }} /> </div> ); }

Key takeaways

  • To scroll to an element on click in React, set a ref on the target element, set a click listener on the element meant to cause the scroll, and in the click event listener, call the scrollIntoView() method on the ref object.
  • To scroll to a dynamically created element in React, set the ref on the list container and call scrollIntoView() on the target item element.
  • We can combine element creation and scrolling as a single action by using the useEffect hook to call scrollToLastFruit() whenever the state array changes.

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.