Search code examples
reactjsmaterial-design

How do I animate card height in Material-UI (React)


I'm new to React and Material UI, so please bear with me :P

What I want to do is, have a card that dynamically changes height as the content changes. According to the docs, this should happen automatically, and it does, but I want the height to animate to the new value.

So this is the relevant code:

var SomeAwesomeComponent = React.createClass({

getInitialState: function(){
  return {
      text: 'Test'
  }
},

componentDidMount: function(){
  var self = this;
setInterval(function(){
    self.setState({
        text: 'Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello '
    })
  },2000)
},

render: function() {
    var cardStyle = {
        transition: '1s'
    }
    return (
        <div>
            <Card>
                <CardText transitionEnabled={true} style={{cardStyle}}>
                    {this.state.text}
                </CardText>
            </Card>
        </div>
    );
}

});

What I can see is, the height changes, but it jumps to the new value. I want it to 'transition' to the new value. The docs say this can be done using 'transitionEnabled', but I can't seem to get it to work. Can anyone help?

Thanks


Solution

  • So I found a solution that works.

    It was more of a CSS issue than React/Material-UI.

    You have to explicitly set the heights in both states of the card (and it cannot be 'auto'). What I did was, I saved the height as a state of the component, and updated it when I wanted it to expand (when I changed the text).

    Here:

    getInitialState: function(){
      return {
          text: 'Test',
          height: '10vh'
      }
    },
    
    componentDidMount: function(){
      var self = this;
    setInterval(function(){
        self.setState({
            text: 'Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello ',
            height: '15vh'
        })
      },2000)
    },
    
    render: function() {
        var cardStyle = {
            display: 'block',
            width: '80vw',
            transitionDuration: '0.3s',
            height: this.state.height
        }
        return (
            <div>
                <Card style={cardStyle}>
                    <CardText>
                        {this.state.text}
                    </CardText>
                </Card>
            </div>
        );
    

    I'm pretty sure this is not the best way to do this, so if anyone knows a better solution, do let me know.

    Thanks :)