Nadine
Nadine

Reputation: 357

How can I change the color of a Link in React with Material-UI?

I'm not able to change the color of a Link inside a Button. When I apply the secondary color to the Button, it doesn't take effect. In other components it does work this way.

<AppBar position='fixed'>
                <Toolbar>
                    <Button color='secondary'>
                        <Link to="/">Home</Link>
                    </Button>
                </Toolbar>
</AppBar>

In App.js I create the custom Theme and wrap it around all components with <ThemeProvider theme={customTheme}>

App.js:

const customTheme = createMuiTheme({
    palette: {
        primary: {
            main: '#36454B',
            contrastText: '#fff',
        },
        secondary: {
            light: '#55dab3',
            main: '#00a883',
            dark: '#007856',
            contrastText: '#000',
        }
    }
});

Upvotes: 13

Views: 36855

Answers (3)

DBrown
DBrown

Reputation: 5529

I know this is old, but you can change the color of all Link objects in the theme using the action object within the theme object (Material-UI v4 and MUI v5):

// Material-UI v4
import lightBlue from '@material-ui/core/colors/lightBlue'

// or for MUI v5
import { lightBlue } from '@mui/material/colors'

...
 palette: {
   primary { ... },
   secondary { ... },
   action: {
      active: lightBlue[200],
      activeOpacity: 1,
      hover: lightBlue[100],
      hoverOpacity: 0.7,
      focus: lightBlue[600],
      focusOpacity: 1,
      selected: lightBlue[300],
      selectedOpacity: 1
    },
    ...

Upvotes: 10

atazmin
atazmin

Reputation: 5687

This seem to work for me, might not be the best way:

import { Link as RouterLink } from 'react-router-dom';
import { 
  Link,
} from '@mui/material';

...

const buttonSx = {
                px: 6,
                textAlign: 'center',
              };

              const buttonProps = {
                key: link.id,
                variant: link.outlined ? 'outlined' : 'contained',
                className: 'book-grid__button',
              };
              return link.isExternal ? (
                <Button
                  href={link.Link}
                  rel="noreferrer noopener"
                  target="_blank"
                  {...buttonProps}
                  sx={buttonSx}
                >
                  {link.Text}
                </Button>
              ) : (
                <Button
                  to={link.Link}
                  component={RouterLink}
                  {...buttonProps}
                  sx={buttonSx}
                >
                  {link.Text}
                </Button>
              );

Upvotes: 0

Vencovsky
Vencovsky

Reputation: 31625

What you can do is pass component={Link} to button, so it will render the Link as it base component. See the docs.

<Button color='secondary' href="/" component={Link}>
    Home
</Button>

Upvotes: 12

Related Questions