Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 896

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T03:07:06+00:00 2024-11-25T03:07:06+00:00

Sync height between elements in React

  • 62k

A simple problem: make sure that the different elements in the app are the same height, as if they were in a table.

Let's start with a sample react app that renders 3 cards with different items (styles are omitted, but at the end they are all flex boxes):

  const ItemCard = ({   title,   items,   footerItems, }: {   title: string;   items: string[];   footerItems: string[]; }) => {   return (     <div className="card">       <h2>{title}</h2>       <div className="separator" />       <div className="items">         {items.map((item) => (           <p>{item}</p>         ))}       </div>       <div className="separator" />       <div className="footer">         {footerItems.map((footerItem) => (           <p>{footerItem}</p>         ))}       </div>     </div>   ); };  export const App = () => {   return (     <div>       <ItemCard title="Card one" items={['One', 'Two']} footerItems={['One']} />       <ItemCard         title="Card two"         items={['One', 'Two', 'Three', 'Four']}         footerItems={['One', 'Two', 'Three']}       />       <ItemCard title="Card three" items={['One']} footerItems={['One']} />     </div>   ); };   
Enter fullscreen mode Exit fullscreen mode

When you run this app, you will get this result:
Default result

The desired result would be something like this:
React elements have same height

In order to synchronize the height I came with the following idea: a custom hook that stores the references to all different elements that have to be matched in a {[key: string]: value: array of elements} object, and when there is a change in dependencies, the height of elements gets recalcualted in useLayoutEffect:

  import { MutableRefObject, useLayoutEffect } from 'react';  type Target = MutableRefObject<HTMLElement | null>;  // Store all elements per key, so it is easy to retrieve them const store: Record<string, Target[]> = {};  // Triggered when useLayoutEffect is executed on any of the components that use useSyncRefHeight hook const handleResize = (key: string) => {   // get all elements with the same key   const elements = store[key];   if (elements) {     let max = 0;     // find the element with highest clientHeight value     elements.forEach((element) => {       if (element.current && element.current.clientHeight > max) {         max = element.current.clientHeight;       }     });     // update height of all 'joined' elements     elements.forEach((element) => {       if (element.current) {         element.current.style.minHeight = `${max}px`;       }     });   } };  // Add element to the store when component is mounted and return cleanup function const add = (key: string, element: Target) => {   // create store if missing   if (!store[key]) {     store[key] = [];   }    store[key].push(element);    // cleanup function   return () => {     const index = store[key].indexOf(element);     if (index > -1) {       store[key].splice(index, 1);     }   }; };  // Receives multiple elements ([key, element] pairs). This way one hook can be used to handle multiple elements export type UseSyncRefHeightProps = Array<[string, Target]>; export const useSyncRefHeight = (refs: UseSyncRefHeightProps, deps?: any[]) => {   useLayoutEffect(() => {     // store cleanup functions for each entry     const cleanups: (() => void)[] = [];     refs.forEach(([key, element]) => {       // add element ref to store       cleanups.push(add(key, element));     });     return () => {       // cleanup when component is destroyed       cleanups.forEach((cleanup) => cleanup());     };   }, []);    useLayoutEffect(() => {     // when any of the dependencies changes, update all elements heights     refs.forEach(([key]) => {       handleResize(key);     });   }, deps); };   
Enter fullscreen mode Exit fullscreen mode

By using this hook we can change a bit ItemCard element:

  const ItemCard = ({   title,   items,   footerItems, }: {   title: string;   items: string[];   footerItems: string[]; }) => {   // create ref to the parent container, to only target its children instead of running query on the entire document   const itemsRef = useRef(null);   const footerRef = useRef(null);    // align elements with class items   // deps is an empty array, so it will only be aligned when the component is mounted.   // You can add your dependencies, or remove it to make sure the hook runs at every render   useSyncRefHeight(     [       ['items', itemsRef],       ['footer', footerRef],     ],     // trigger hook when items of footerItems changes, since it may change height     [items, footerItems],   );   return (     <div className="card">       <h2>{title}</h2>       <div className="separator" />       <div className="items" ref={itemsRef}>         {items.map((item) => (           <p>{item}</p>         ))}       </div>       <div className="separator" />       <div className="footer" ref={footerRef}>         {footerItems.map((footerItem) => (           <p>{footerItem}</p>         ))}       </div>     </div>   ); };   
Enter fullscreen mode Exit fullscreen mode

Now, items and footer elements height will be matched across all cards.

beginnersjavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.