What is the best way to apply typography theme defaults to standard tags using Material-UI?

After reading the documentation on https://material-ui.com/style/typography/ and loading the Roboto font, I expected a simple component like this:

const theme = createMuiTheme();

const App = () => {
  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      <p>Hello world!</p>
    </MuiThemeProvider>
  );
};

to style the p tag using Roboto as the default font. However, that was not the case. When I modified the code to this:

const theme = createMuiTheme();

const App = () => {
  return (
    <MuiThemeProvider theme={theme}>
      <CssBaseline />
      <Typography>Hello world!</Typography>
    </MuiThemeProvider>
  );
};

it worked as expected with the typography being applied. This left me questioning how the library should be used:

  1. Do I need to replace all regular HTML tags with custom React elements when using Material-UI?
  2. Is there a simple way to apply theme typography styles to standard HTML tags like h1-h6, p, etc?
  3. Am I required to manually style all the standard HTML elements myself by using withStyles on a top-level component?

Answer №1

  1. Is Material-UI's concept to replace all standard HTML tags with custom React elements?

No, the concept of typography in Material UI (and Material Design overall) is to offer a consistent range of styles throughout your application theme: https://material.io/design/typography/the-type-system.html#

You can then utilize these typography styles in various ways, as explained in points 2 and 3 below.

  1. Can the styles from the theme typography be easily applied to standard HTML tags like h1-h6, p, etc?

As mentioned by @Chimera.Zen, you can apply theme styles and font variants to any React component or HTML tag using the withStyles Higher Order Component (HOC). However, here's another method that I find more practical - reusing theme typography definitions in your JSS styles:

const styles = theme => ({
  paragraph: {
    ...theme.typography.body1
  }
});

const MyComponent = props => (
  <p className={props.classes.paragraph}>
    Styled text here
  </p>
);
  1. Am I supposed to individually style all standard HTML elements using withStyles on a top-level component?

No, you are not. While you can style individual components if needed, it's more common to use inheritance and leverage default styles of container components like Paper, Drawer, etc., or your custom container components.

You could create a global container component (e.g., "Root" or "App") applying the default "body1" style to your entire application.

Another approach is to utilize the 'jss-global' plugin as demonstrated by an MUI author here: https://github.com/mui-org/material-ui/issues/9988#issuecomment-426631645:

import { withStyles } from '@material-ui/core/styles';

export default withStyles({
  '@global': {
    body: {
      ...theme.typography.body1
    },
  },
})(() => null);

Answer №2

  1. Affirmative, but it is not mandatory.

  2. Aye, utilize the withStyles component with defined styles. An exemplar can be found at the conclusion of this response.

  3. Elements such as Paper, Drawer, etc will inherit theme defaults unless customized in the initiating component of <MuiThemeProvider>. Traditional HTML components necessitate a style definition within the using component or specified classname in a stylesheet.

If you possess something like style.root, it can be assigned to Material-UI components, a div, span, p, a, and so forth. When applied to an MUI component, the styles from style.root will take precedence over default styles.

Utilizing the Material-UI Paper component as a demonstration along with styles.paragraph for further illustration:

const styles = theme => ({
  root: {
    ...theme.mixins.gutters(),
    paddingTop: theme.spacing.unit * 2,
    paddingBottom: theme.spacing.unit * 2,
  },
  paragraph: {
    color: '#FFF',
    textAlign: 'center',
    paddingTop: theme.spacing.unit * 2,
    paddingBottom: theme.spacing.unit * 2,
});

These styles are now applicable to any element

<div className={styles.root}>
  <Paper className={styles.root}>
    <Typography component="p" className={styles.paragraph}>
      Paper aids in creating surface elements or other components for your project.
    </Typography>
  </Paper>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Achieving Perfect Alignment for Absolutely Positioned Divs in

I'm currently facing an issue where the image I'm trying to center horizontally also moves the parent div downward when I try to vertically center it using top-margin. This is not the desired outcome. If you'd like to see what I mean, I&apo ...

Customize MUI columns with unique widths for headers and cells using the pinn attribute

Currently, I am using the Data Grid feature from Material UI. One issue I encountered is that while I can successfully pin the column, there seems to be a slight discrepancy in the header and cell width of the pinned column when compared to other columns w ...

Heroku encounter an H14 error - "the absence of running web processes"

An H14 error occurred during deployment on Heroku. Here is my Procfile: web: gunicorn -w 4 -b 0.0.0.0:$PORT -k gevent main:app Error log on Heroku: 2017-01-23T10:42:58.904480+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method ...

Selenium RC: Utilizing the CSS :contains pseudo-class for Element Selection

I have a task to verify that the data in a table row matches my expectations for two different tables. Let's look at an example using HTML: <table> <tr> <th>Table 1</th> </tr> <tr> <t ...

Memory leakage in Internet Explorer as a result of JavaScript code

Recently, I created a website that utilizes jquery ajax to send an ajax request every minute in order to retrieve json data. This data is then parsed and added into the DOM. While this process runs smoothly on Chrome and Firefox, I noticed a significant m ...

How to retrieve an array from a JSON object with JavaScript

After receiving an object from the server, I am specifically looking to extract the array ITEMS. How can I achieve this? I attempted using array['items'] but it did not yield the expected result and returned undefined { "items": [ { ...

Maximum Age Setting for Iron Session Cookie

Currently, I am attempting to configure a Next JS application with iron-session and a 'remember me' feature. The objective is for the maxAge of the iron-session cookie to be extended to a week if the user selects the remember me option on the log ...

Navigate to a refreshed version of the page with varying parameters using React Navigation

Currently, I am utilizing React Navigation for navigating between different pages within my app. One of the pages is the Profile page which displays a user info card along with their posts. Within this Profile component, I have integrated the Post componen ...

The only information returned from calling mongoose's Model.save() method are the fields { _id, __

I've encountered a problem even though I believe I'm following all the right steps. I'm attempting to save an item from a form into my mongodb collection using mongoose. This is what my schema looks like: // stationmodel.js export const Sta ...

Display a horizontal progression indicator during the page download process

Occasionally, website pages may take a while to download without the user even realizing it. This can be problematic if the user clicks on an image or button with an event handler attached, as it may break the page functionality. To address this issue, I ...

Modify opacity of displayed items in image list with ng-repeat

My application showcases a list of images using ng-repeat. +---------------------------------------------+ | | Previous Image 0 | | | +------------------------------------+ | | +------------------------------------+ | | ...

Implementing React and Material UI: Maximizing Vertical Space Usage for a Box Component

Currently, I am working on a web application using React combined with Material UI. Within my code snippet below, you will see three Box components in play. Box 1 and Box 3 have specific heights set, but I am looking for a way to make Box 2 occupy the re ...

What is the process for downloading a package from unpkg or adding an unpkg package to dependencies?

Challenge I attempted to install IPFS from the unpkg website. https://www.unpkg.com/browse/[email protected] / My Project This is a project built with React. Unfortunately, I am having trouble downloading this package or installing it in my packa ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

Dealing with JSON data retrieved from a Django QuerySet using AJAX

I am utilizing a Django QuerySet as a JSON response within a Django view. def loadSelectedTemplate(request): if request.is_ajax and request.method == "GET": templateID = request.GET.get("templateID", None) ...

What is causing my component callback to not function properly?

I'm currently following a tutorial on AngularJS callbacks from . In my code at https://plnkr.co/edit/dxyI0p0pZFZdMalLfvXO?p=preview, I've attempted to showcase the issue I'm encountering. I have initialized the component in three different w ...

How to ensure that a React Material-UI Fab Button remains fixed in a specific position on the screen

My project involves creating a CRUD application using React and Material UI. One of the requirements is to have a main screen that displays records in a table format, with a floating Fab button positioned above the table. The challenge is to ensure that th ...

Tips for personalizing the text style of the Tab Component in React Material UI

Currently, I am utilizing the Tab Component from React Material UI library. In an effort to remove any automatic text capitalization applied to the tab labels, I attempted the following approach: const CustomTab = withStyles({ ".MuiButtonBase-root": { ...

Troubleshooting z-index problem with background image and parent tag of image

I seem to be facing an issue with the z-index property. Here is the code snippet in question: <div id="sidebarCont"> <div id="avatarCont" class="mask"> <img id="" class="" src="img.jpg" alt=""/> </div> And here is the correspo ...

Transaction response for embedded iFrame with Accept.js on Authorize.net

I've recently integrated authorize.net accept.js embedded iFrame into my application, but I'm facing difficulties in setting the transaction response in my lambda function to retrieve the expected data. Although I've checked similar queries ...