How to simulate expanding effect in bootstrap

Advertisements

I have this react code:

const[open, setOpen] = useState(false);
const zoom = () => {
    if(open){
        setOpen(false);
    }
    else{
        setOpen(true);
    }
}

return (
    <div><button>zoom in and out</button></div>
    <div className="row">
        <div className={`col col-${open ? '12' : '9'}`}>
            Content than can be expanded    
        </div>
        {
            !open && 
        <div className="col col-3">
            content that gets hidden when zooming in
        </div>  
        }
    </div>

)

By default you see 2 columns. The main that is 9/12. The right that is 3/12.
When button is clicked, the main column will become 12/12, hence taking up all the space of the row.
While the one that is 3/12 hides.

This works. But it is not a good effect. I would like to have some kind of animation. Like having the main div expanding to take over all the space.

>Solution :

When you change col-12 to col-9 and vice versa, you are infact changing the width of the div element.

Dom Elements, HTMLDivElement in this particular case, has a style attribute which is of type React.CSSProperties. Using the style attribute and the transition property, animate the width of the div element.

style={{transition: "width 0.5s"}}

<div className={`col col-${open ? '12' : '9'}`} 
     style={{transition: "width 0.5s"}}> 

Full code

const App = () => {
 const[open, setOpen] = React.useState(false);
 const zoom = () => setOpen(!open)

 return (
    <>
      <div>
        <button onClick={zoom}>zoom in and out</button>
      </div>
      <div className="container">
        <div className="row">
          <div style={{transition: "width 0.5s"}} className={`bg-primary col col-${open ? '12' : '9'}`}>
              Content than can be expanded
          </div>
          {
              !open && 
          <div className="col col-3">
           content that gets hidden when zooming in
          </div>  
          }
      </div>   
    </div>  
   </>)
}

Reference:

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions

Leave a ReplyCancel reply