kakaja kakaja -4 years ago 61
React JSX Question

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:

<Card expandable={true} onExpandChange={this.clickHandle}>


In this action I can easily know if the clicked card is expanded or not, because the callback function is defined like this in the MaterialUI:
function(newExpandedState: boolean) => void


clickHandle = (newExpandedState: boolean) => {
//do something
}


Now I would like to change card's class, for example, give it class
expanded
when
newExpandedState
is
true
.

The problem is that I don't know how to tell this function which card has been expanded. Things like
onExpandChange={this.clickHandle(newState, 'card1')}
don't work. I have 20 cards on the page and I don't know which one should get
expanded
class. Any ideas how to do this?

Answer Source

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';

class MyCustomCard extends React.Component {
  state = {
    expanded: null
  }

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

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

Then you can use it like this:

import React from 'react';
import Card from '../MyCustomCard';

class App extends React.Component {
  ...

  render() {
    return (
      <div>
        <Card />
        <Card />
        <Card />
        <Card />
        <Card />
        ...
      </div>
    )
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download