Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React animate containers height

Tags:

css

reactjs

I have a demo here

Its a super simple app with four buttons and a text area.

When you click a buttons it loads different text

The text is different lengths so the grey container gets taller and shorter

Is it possible to animate the grey box when the text gets taller and shorter

const [text, setText] = useState(textArr[3])

  return (
    <div>
      <div className="nav">
        <button onClick={() => setText(textArr[0])}>
          One
        </button>
        <button onClick={() => setText(textArr[1])}>
          Two
        </button>
        <button onClick={() => setText(textArr[2])}>
          Three
        </button>
        <button onClick={() => setText(textArr[3])}>
          Four
        </button>
      </div>  
      <div className="text">
        {text}
      </div>
    </div>
  );
like image 757
cdmt Avatar asked Jun 06 '26 15:06

cdmt


1 Answers

I put a parent div with overflow: hidden applied to it then I used a useEffect to calculate the height of the text div when the text changes and then I set the height of the parent div to this height.

With transition on the parent div, it animates.

See demo here : https://stackblitz.com/edit/react-t7ctuf?file=src%2FApp.js

like image 129
Martin J Avatar answered Jun 09 '26 06:06

Martin J