Skip to content
Advertisement

MUI – How to animate Card depth on hover?

I want to animate the depth of the whole Card when the mouse is over it. I try this (so-so I’m new in React) but I have no idea how to do it:

<Card 
  linkButton={true}
  href="/servicios/"
  onClick={Link.handleClick} zDepth={3}
  onMouseEnter={this.setState({zDepth={1}})}>
</Card>

Thanks in advance.

Advertisement

Answer

constructor(props) {
  super(props);
  this.state = { shadow: 1 }
}

onMouseOver = () => this.setState({ shadow: 3 });
onMouseOut = () => this.setState({ shadow: 1 });

<Card 
   onMouseOver={this.onMouseOver}
   onMouseOut={this.onMouseOut}
   zDepth={this.state.shadow}
>

Updated #1

Full example

// StyledCard.js

import React, { Component } from 'react';
import { Card } from 'material-ui/Card';

class StyledCard extends Component {
  state: {
    shadow: 1
  }

  onMouseOver = () => this.setState({ shadow: 3 });

  onMouseOut = () => this.setState({ shadow: 1 });

  render() {
    return (
      <Card 
        onMouseOver={this.onMouseOver}
        onMouseOut={this.onMouseOut}
        zDepth={this.state.shadow}
      >
        {this.props.children}
      </Card>
    );
  }

export default StyledCard;

.

// Container.js

import React from 'react';
import StyledCard from './StyledCard';

const Container = () => [
  <StyledCard>Card 1</StyledCard>,
  <StyledCard>Card 2</StyledCard>,
  <StyledCard>Card 3</StyledCard>,
];

export default Container;

UPDATED #2

With HOC

// withShadow.js

import React from 'react';

const withShadow = (Component, { init = 1, hovered = 3 }) => {
  return class extends React.Component {
    state: {
      shadow: init
    };

    onMouseOver = () => this.setState({ shadow: hovered });

    onMouseOut = () => this.setState({ shadow: init });

    render() {
      return (
        <Component
          onMouseOver={this.onMouseOver}
          onMouseOut={this.onMouseOut}
          zDepth={this.state.shadow}
          {...this.props}
        />
      );
    }
  };
};

export default withShadow;

.

// Container.js

import React from 'react';
import { Card } from 'material-ui/Card';
import withShadow from './withShadow';

const CardWithShadow = withShadow(Card, { init: 2, hovered: 4 });

const Container = () => [
  <CardWithShadow>Card 1</CardWithShadow>,
  <CardWithShadow>Card 2</CardWithShadow>,
  <CardWithShadow>Card 3</CardWithShadow>,
];

export default Container;
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement