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

How to create a dropdown menu in React js with an array of items

Can we structure the array without splitting it into two parts and iterating over them? arrayList=[Jeans, Jackets, Pants, Fragrance, Sunglasses, Health Products] <div className='Flexbox'> //arrayList1.map](//arrayList1.map)(x=>return(< ...

Partial view remains stagnant despite successful ajax post completion

I am currently in the process of developing a system that will showcase uploaded images from a file input into a specific div within my view. (with intentions to incorporate document support in the future) The challenge I am facing is that the partial vie ...

Next.js users have reported experiencing style flickering when utilizing material-ui's useMediaQuery feature upon initial rendering

Encountering style flickering on initial render in Next.js while using the @mui/material/useMediaQuery function. The issue arises from the useMediaQuery value changing between server side and client side rendering. Is there a solution to this problem? imp ...

Tips for transferring information from an express rendering to a Vue component?

When working with an express route, page.js router.post('/results', (req, res, next) => { output.terms = "hello" output.results = [{"text": "hello world"}, {"text": "hello sunshine"}] res.render("/myview",output) }) The cod ...

Next.js v.12: Issue with SSR hydration using useState hook

URL address and app info are used to determine the path, which is then passed down as props from getServerSideProps to the component. // Custom Hook export default function useCustomPath(app, path) { const [currentPath, setCurrentPath] = useState(' ...

What is the best way to set the v-model property to an object that is constantly changing

I'm in the process of creating a dynamic form that allows users to add additional fields by simply clicking on a button labeled "adicionar condição." The concept is similar to what can be seen in the screenshot below: https://i.stack.imgur.com/Mpmr6 ...

unable to retrieve real-time data using a search bar

I'm working on a drop-down menu of locations/Regions with a search box nested inside. The image shows a list of places followed by regions. The region section is static, while the rest of the places are fetched from a database. Currently, I can searc ...

Is there a way to dynamically add or modify a JavaScript timestamp component after the webpage has finished loading?

Context: Utilizing the SailsJS framework to showcase the timestamp of data model updates. The framework, originating from 'parasails', leverages Vue.js and offers the <js-timestamp :at="1573487792252"> component to display elapsed time like ...

Is it beneficial to separate React and WebAPI into two distinct projects?

After spending 4 years in Asp.Net MVC and JQuery, I am looking to take the next step and transition to .Net Core 2, WebAPI, and React. I have been following various how-tos and tutorials, but what puzzles me is why every tutorial suggests adding React dir ...

Is it time to refresh the sibling element when it's selected, or is there

I have recently started working with react and TypeScript, and I am facing some challenges. My current task involves modifying the functionality to display subscriptions and transactions on separate pages instead of together on the same page. I want to sh ...

Guide on passing a variable from AJAX response to a JavaScript function when a user clicks

I need to send the value of a variable as a parameter to a javascript function when clicking on a link. The value is obtained from an AJAX response. However, I am encountering an error in the console stating that 'test' is not defined. var test ...

Utilize Python to extract a table from an HTML document

I would like to retrieve a table from an HTML file. Below is the code-snippet I have written in order to extract the first table: import urllib2 import os import time import traceback from bs4 import BeautifulSoup #find('table',{'class&ap ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

I encountered an issue when trying to dynamically add a text field in Angular 2. The error message received was "ERROR TypeError: Cannot read property '0' of

I am currently utilizing Angular2 in my project, and I am attempting to dynamically add a text field. However, I keep encountering an error: Error Message (TS): ngOnInit() { this.myForm = this._fb.group({ myArray: this._fb.array([ ...

Using ng-style to apply a background image with a dynamic id

Hey there, I'm facing an issue here. The link provided below seems to not be working properly. Even though the id is set correctly within the scope, it seems like there might be a parsing error occurring. Any thoughts on what might be causing this pro ...

Tips for aligning my icon in the middle when I collapse my sidebar

Seeking assistance on centering the hamburger icon on my sidebar. Currently, when I adjust the width of the sidebar, the icon is not centered at all. Does anyone have a solution for achieving this? I attempted using justify-content: center in the main clas ...

Using a JavaScript array in Java

Currently, I am working on an Android app that requires me to download data from a JavaScript array representing the schedule for my school. The link to the data is here. I am looking for a way to parse this data into a Java array. I have considered using ...

Error code 400 encountered when processing Stripe webhooks

I've been working on integrating stripe webhooks into my node.js/express application, but I keep running into a 400 response from the stripe cli. Even though I followed the documentation closely and ensured that the secret key for the webhook is corre ...

Upgrading to React Router v6: Implementing Loader Functions with Context API

Having issues implementing loaders in React-Router V6 while making a request for a page through a function located in the context file. Unfortunately, I can't access the context from main.js where the router is defined. Main.js import ReactDOM from & ...

What's the best way to retrieve data on button click in Next.js?

I'm working on a web application that includes an input field and a button next to it. When the user clicks the button, I need to fetch data from the server. Initially, I tried using SWR for this functionality but I'm not entirely sure if SWR is ...