Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import material-ui components?

Heavily using material-ui in my app, is there a way to avoid doing imports in each app component like this?

import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import Grid from "@material-ui/core/Grid";
import Container from "@material-ui/core/Container"; 
....

or this:

import {Typography, Box, Grid, Container} from "@material-ui/core";

Is there such thing like this? So that I don't need to import each component?

import * from "@material-ui/core"

Thanks in advance! :D

like image 281
Kiki Avatar asked Sep 03 '25 06:09

Kiki


2 Answers

Yes, there is an import all in JavaScript. You can do it like so:

import * as Mui from '@material-ui/core';

This puts all of the named exports of @material-ui/core into the Mui "namespace". Then, you can easily access any of the components i.e.:

<Mui.Typography>Test</Mui.Typography>

You can read more about import here.

like image 181
Remolten Avatar answered Sep 05 '25 01:09

Remolten


The first option is not much clean from an import statement perspective, especially when you want to import and use a lot of Mui components, but as you use path imports to avoid pulling in unused modules, gets an optimized bundle size automatically.

The second option (import * from "@material-ui/core"), on the other hand, is the most convenient from a development perspective, and also makes you have a clean import statement, but will make your application packages larger than they import each component separately depending on what part of components you are using. Moreover, there is a large scale application you need to import from different sources of Material-ui:

import {} from '@material-ui/core';
import {} from '@material-ui/icons';
import {} from '@mui/material';

A better optimized approach, is to create a single file in your project where you import each component that you use individually, then export them all under a single namespace:

// src/mui/index.js
export { default as MenuItem } from '@material-ui/core/MenuItem';
export { default as TextField } from '@material-ui/core/TextField';
export { default as Select } from '@material-ui/core/Select';
export { default as ClearIcon} from '@material-ui/icons/Clear';
export { default as FormControl } from '@material-ui/core/FormControl';
export { default as Button } from '@mui/material/Button';
...

Then you can import that file wholesale into each component where you need it:

// ../../MyComponent.js
import {
  MenuItem,
  TextField,
  Select,
  ClearIcon,
  FormControl
} from 'mui';

Now you have a clean import statement and optimized bundle size as well.


Working with absolute path: I never address components with a relative path (e.i ../../../mui). you can take a look here if you don't know how to use absolute path in React.

like image 23
Hamidreza Soltani Avatar answered Sep 05 '25 00:09

Hamidreza Soltani