Skip to content Skip to sidebar Skip to footer

React Materialui Card: How To Change Card's Class On Expand? -> Custom React Component

There are 20 cards on the page. MaterialUI Card has onExpandChange property where I can define an action like this:

Solution 1:

One way to do it is to wrap the material-ui's card with your own custom card and add a state to it: import React from 'react'; import { Card } from 'material-ui';

classMyCustomCardextendsReact.Component {
  state = {
    expanded: null
  }

  toggleExpanded = () => {
    this.setState((state) => ({
      expanded: !state.expanded
    }))
  }

  render() {
    return<Cardexpandableexpanded={this.state.expanded}onExpandChange={this.toggleExpanded}>
  }
}

Then you can use it like this:

importReactfrom'react';
importCardfrom'../MyCustomCard';

classAppextendsReact.Component {
  ...

  render() {
    return (
      <div><Card /><Card /><Card /><Card /><Card />
        ...
      </div>
    )
  }
}

Solution 2:

You can do this:

1. Maintain an array in state variable that will have the record of all the id's of card (any unique property of card) which are in expanded state.

constructor(){
   super();
   this.state = {
      cardStatus: []
   }
}

2. Pass the unique value to each onExpandChange method:

onExpandChange={() => this.clickHandle(card.name)}

3. Now if newExpandedState is true the push that value inside state array otherwise remove it:

clickHandle(name, newExpandedState){
    let cardStatus = this.state.cardStatus.slice();
    if(newExpandedState)
        cardStatus.push(name);
    else{
        let index = this.state.cardStatus.indexOf(name);
        cardStatus.splice(index,1);
    }
    this.setState({cardStatus});        
}

4. Now when generating the card check if that cardStatus array has that unique property of card or not and then apply different classNames.

<Card className={this.state.cardStatus.indexOf(card.name) >= 0 ? 'expanded': 'not'}>

Solution 3:

Just to share the result:

Finally got it working with the help of @glenn-reyers and got this code for the CustomCard component:

importReactfrom'react';
import {Card} from'material-ui/Card';


classCustomCardextendsReact.Component<any, any> {
  state = {
    expanded: false
  }

  handleExpandChange = (expanded) => {
    this.setState({expanded: expanded});
  };

  render() {
    return<CardclassName={this.state.expanded ? 'controller-cardexpanded' : 'controller-card'} 
            expandable={true}expanded={this.state.expanded}onExpandChange={this.handleExpandChange}>
                {this.props.children}
        </Card>
  }
}

exportdefaultCustomCard;

Working fiddle is here: https://codesandbox.io/s/76O8pnW9Q

Post a Comment for "React Materialui Card: How To Change Card's Class On Expand? -> Custom React Component"