vijayst
vijayst

Reputation: 21836

Animate width of a div in React

I have a div whose content changes. Whenever the content changes, the div should animate its width. I tried the following and it does not work. Any pointers will be helpful.

class App extends React.Component {

 constructor() {
   super();
   this.state = {
     text: 'Hello world'
   }
  }
  
  changeText() {
    this.setState({
      text: 'Very long text stretching across screen'
    });
  }

  render() {
    return <div>
      <div className="text">{this.state.text}</div>
      <button onClick={this.changeText.bind(this)}>Change</button>
      </div>;
  }
}

ReactDOM.render( < App / > , document.getElementById('root'));
.text {
display: inline-block;
  background-color: cyan;
  transition: width 2000s;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

Views: 7704

Answers (2)

Vijay Venugopal Menon
Vijay Venugopal Menon

Reputation: 1520

You can do this with your current code by specifying initial and final width and setting the style class dynamically based on button click.Please find code below:

https://codesandbox.io/s/fervent-dawn-32bfl

Also note that you have given the transition as "2000s" which is 2000 seconds :-)

Note: Marudhupandiyan's comment in your original question also provides a solution where the width is determined dynamically, which is a much more optimal solution if you don't know the width beforehand. You can integrate that logic into the code I have provided above, if required.

Upvotes: 1

cbdeveloper
cbdeveloper

Reputation: 31365

I could do it like this:

class App extends React.Component {

 constructor() {
   super();
   this.state = {
     text: 'Hello world'
   }
   this.myRef = React.createRef();
  }
  
  changeText() {
    this.setState({
      text: 'Very long text stretching across screen'
    });
    this.myRef.current.style.width = '250px';
  }

  render() {
    return <div>
      <div ref={this.myRef} className="text">{this.state.text}</div>
      <button onClick={this.changeText.bind(this)}>Change</button>
      </div>;
  }
}

ReactDOM.render( < App / > , document.getElementById('root'));
.text {
display: inline-block;
  background-color: cyan;
  overflow: hidden;
  height: 18px;
  width: 80px;
  transition: width 1.5s;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 3

Related Questions