Skip to content

Commit 9f1f7d0

Browse files
committed
add TS demo for DynamicCSS
1 parent cdc4b98 commit 9f1f7d0

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import React from 'react';
2+
import { withStyles, WithStyles } from '@material-ui/core/styles';
3+
import Button from '@material-ui/core/Button';
4+
import FormControlLabel from '@material-ui/core/FormControlLabel';
5+
import Switch from '@material-ui/core/Switch';
6+
7+
interface Styles {
8+
color: string;
9+
children: React.ReactNode;
10+
[key: string]: any;
11+
}
12+
13+
interface ColorsMapping {
14+
default: string;
15+
blue: string;
16+
[key: string]: any;
17+
}
18+
19+
interface ButtonStyles extends WithStyles<typeof styles> {
20+
color: string;
21+
}
22+
23+
// Like https://github.com/brunobertolini/styled-by
24+
const styledBy = (property: string, mapping: ColorsMapping) => (props: Styles) =>
25+
mapping[props[property]];
26+
27+
const styles = {
28+
root: {
29+
background: styledBy('color', {
30+
default: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
31+
blue: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
32+
}),
33+
borderRadius: 3,
34+
border: 0,
35+
color: 'white',
36+
height: 48,
37+
padding: '0 30px',
38+
boxShadow: styledBy('color', {
39+
default: '0 3px 5px 2px rgba(255, 105, 135, .3)',
40+
blue: '0 3px 5px 2px rgba(33, 203, 243, .3)',
41+
}),
42+
},
43+
};
44+
45+
const StyledButton = withStyles(styles)(({ classes, color, ...other }: ButtonStyles) => (
46+
<Button className={classes.root} {...other} />
47+
));
48+
49+
export default function DynamicCSS() {
50+
const [color, setColor] = React.useState('default');
51+
52+
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
53+
setColor(event.target.checked ? 'blue' : 'default');
54+
};
55+
56+
return (
57+
<React.Fragment>
58+
<FormControlLabel
59+
control={
60+
<Switch
61+
checked={color === 'blue'}
62+
onChange={handleChange}
63+
color="primary"
64+
value="dynamic-class-name"
65+
/>
66+
}
67+
label="Blue"
68+
/>
69+
<StyledButton color={color}>Dynamic CSS</StyledButton>
70+
</React.Fragment>
71+
);
72+
}

0 commit comments

Comments
 (0)