Adding a Theme in React to Change Element Colors and Text Font.

Tiempo de lectura: < 1 minuto

Reading Time: < 1 minute
Hello, today we are going to learn how to add a theme to customize the colors displayed in the theme of our React website.

For this tutorial, we will use Material UI.

First, we install the necessary dependencies:

npm install @mui/material @emotion/react @emotion/styled

Now, let’s create our theme by creating a file named theme.tsx (I use TypeScript, you can create it in JavaScript)

// theme.ts
import { createTheme, Theme } from '@mui/material/styles';
import { teal } from '@mui/material/colors';

const theme: Theme = createTheme({
  palette: {
    primary: teal,
  },
  typography: {
    fontFamily: 'Roboto, sans-serif',
  },
});

export default theme;

In my case, I have set Roboto as the fontFamily and the colors to Teal.

Now, we need to apply our theme in our main file, in my case main.tsx

// index.tsx or App.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ThemeProvider } from '@mui/material/styles';
import theme from './theme';

ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={theme}>
      <App />
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

And our theme is applied and ready.

Leave a Comment