Search code examples
javascriptreactjsmaterial-uiastrojs

How to integrate MUI in React Integrated Astro site?


I am learning Astro. I thought of using MUI's material components, like Button, Typography, etc., in the Astro components as I already enabled React integration.

astro.config.js

import { defineConfig } from 'astro/config';
import react from '@astrojs/react';

// https://astro.build/config
export default defineConfig({
    // Enable React to support React JSX components.
    integrations: [react()],
});

Counter.tsx:

import { useState } from "react";
import Container from "@mui/material/Container";
import "./Counter.css";
import { Button, Typography } from "@mui/material";

export default function Counter({
  children,
  count: initialCount
}: {
  children: JSX.Element;
  count: number;
}) {
  const [count, setCount] = useState(initialCount);
  const add = () => setCount((i) => i + 1);
  const subtract = () => setCount((i) => i - 1);

  return (
    <Container>
      <div className="counter">
        <button onClick={subtract}>-</button>
        <Typography variant="h6">{count}</Typography>
        <Button variant="contained" color="secondary" onClick={add}>
          +
        </Button>
      </div>
      <div className="counter-message">{children}</div>
    </Container>
  );
}

In local, I tried with client:only="react". Still, astro's styles are taking precedence. Is there any official/best way or at least a workaround of integrating MUI with Astro that I am missing out or simply MUI doesn't work with Astro?

Thanks in Advance

CodeSandBox Link for Quick Overview: https://codesandbox.io/s/cranky-ride-3yw946?file=/src/components/Counter.tsx:0-777


Solution

  • As noktasizi#3070 stated, It seems UI libraries like MUI (which rely on CSS-in-Javascript for their component styling) are not yet supported by Astro.

    You can follow https://github.com/withastro/astro/issues/4432 for more info on the same.