CLASSFUNC BLOG
We Share Our Knowledge
Custom giao diện màu trong React
Dam Van Duong
14 Th01 2021 13:09

Có nhiều cách để custom giao diện khi bạn sử dụng các framworks khác nhau như Material Ui, Antd design. Mình sẽ đi vào Custom giao diện với React js + Material Ui, cụ thể ở đây là custom các màu chủ đạo cho website của bạn nhé.

Trước tiên tạo Context Provider Theme.

export const UseThemeContext = createContext(); export const ThemeProviderContext = ({children}) => { const theme = useThemeConText(); return ( <UseThemeContext.Provider value={theme}> <ThemeProvider theme={theme}> {children} </ThemeProvider> </UseThemeContext.Provider> ); }; export const useThemeConText = () => { const [colors] = useGlobal('colors'); const [theme, setTheme] = useState(createMuiTheme({})); console.log(colors); useEffect(() => { if (!colors?.primary) return; setTheme(createMuiTheme({ props: { primaryColor: colors.primary, secondaryColor: colors.secondary, }, // and more setting to use })); }, [colors]); return theme; };

Sau khi khởi tạo xong mui-theme, tiến hành thực hiện khai báo ThemeProviderContext ở file Index.js của App (Đã bao gồm ThemeProvider của Material Ui)

ReactDOM.render( <React.StrictMode> <ThemeProviderContext> <App/> </ThemeProviderContext> </React.StrictMode>, document.getElementById('root'), );

Sau đó sử dụng props này ở bất cứ đâu bạn muốn với thuộc tính theme.props.primaryColor và theme.props.secondaryColor:

const useStyles = makeStyles(theme => ({ divRoot1: { background: theme.props.primaryColor, width: '100%', height: '40vh', position: 'relative', }, divRoot2: { background: theme.props.secondaryColor, width: '100%', height: '40vh', position: 'relative', }, Button: { width: 250, height: 50, background: theme.props.primaryColor, color: theme.props.secondaryColor, marginBottom: 20, }, }));

Link github demo code tại đây: https://github.com/duongdam/create-mui-theme-matarial-ui-custom-with-react-js-context-provider