I am trying to use styled-components to style my own child components.
As an example, I have created a custom card component, called myCard, as follows:
import React from "react";
import Card, { CardActions, CardContent } from "material-ui/Card";
import Button from "material-ui/Button";
import Typography from "material-ui/Typography";
const myCard = props => {
return (
<Card>
<CardContent>
<Typography>{props.cardName}</Typography>
</CardContent>
<CardActions>
<Button size="small">SELECT</Button>
</CardActions>
</Card>
);
};
export default myCard;
Now, in the parent component, I want to reuse this myCard component but with the possibility of giving any one of them a custom style, such as a border (when I eventually refactor the code to onClick):
import React, { Component } from "react";
import Grid from "material-ui/Grid";
import styled from "styled-components";
import myCard from "./myCard";
const StyledCard = styled(myCard)`
/* border-style: ${props => (props.border ? "solid" : "none")}; */
border-style: solid !important;
border-width: 5px;
width: 180px;
`;
class cardSelect extends Component {
render() {
return (
<div>
<Grid container spacing={24}>
<Grid item xs={12}>
<Grid container justify="center">
<Grid item>
<StyledCard
cardName="Bronze"
/>
</Grid>
<Grid item>
<StyledCard
cardName="Silver"
/>
</Grid>
<Grid item>
<StyledCard
cardName="Gold"
/>
</Grid>
</Grid>
</Grid>
</Grid>
</div>
);
}
}
export default cardSelect;
I admit, I find the styled-components documentation rather poor. And there is only one reference to this kind of situation, which suggests to pass the className prop to the component. However I am not truly understanding this concept.
I found the answer through trials and errors. Could not find this solution (at least holistic) anywhere, so for posterity and the benefit of others, this is how I solved it.
The solution is simply to pass the className prop to the myCard component as follows:
const myCard = props => {
const { className } = props;
return (
<Card className={className}>
...
So, in general, one has to pass the className prop on to the custom component that you want to render.