React MaterialUI Card: How To Change Card's Class On Expand? -> Custom React Component
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';
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>
)
}
}
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:
import React from 'react';
import {Card} from 'material-ui/Card';
class CustomCard extends React.Component<any, any> {
state = {
expanded: false
}
handleExpandChange = (expanded) => {
this.setState({expanded: expanded});
};
render() {
return
<Card
className={this.state.expanded ? 'controller-card expanded' : 'controller-card'}
expandable={true}
expanded={this.state.expanded}
onExpandChange={this.handleExpandChange}>
{this.props.children}
</Card>
}
}
export default CustomCard;
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"