How to Convert a Component Design Into an MUI React Code
Tags: react, ux, design
Published: 2022-02-04 15:58:58

Material UI or MUI library provides you with robust, customizable,  accessible, and advanced components, enabling you to build your own design system and develop React applications faster. That includes a huge list of Material icons, foundational components with MUI Core, advanced and powerful components with MUI X, templates, and design kits!

In this tutorial, we will see how to take a given design and convert it into an actual component code by styling it with MUI Core configurations for a React app. Let’s begin!

## Converting a component design to an MUI code in React

If you are provided with a design file with a simple component to build on React there are so many ways, but here with MUI’s extensive pre-built components, the process becomes much easier, faster, accessible, and most importantly customizable! 

## What we will be making?

We will be taking the following barcode component design and implementing it with MUI for React:

As you can see, we have three items:

The barcode component with the two sections.
The first section holds the barcode image in a blue container.
The second section below the barcode image has all the typography elements like a heading and a paragraph.

### Step 1: Start a New React project

Make sure you have [Node.js installed](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm/) on your system and then run the following commands:

```
<code>npx create-react-app mui-barcode-app
cd mui-barcode-app
npm start</code>
```

This will bootstrap a new React application and run the default app on [http://localhost:3000/](http://localhost:3000/) in your default browser thanks to the [Create React App](https://create-react-app.dev/) tool.

#### Step 2: Install Material UI (MUI) Package

Before we start making changes to our default React code, we need the core MUI package because all these icons use the MUI [SvgIcon](https://mui.com/api/svg-icon/#main-content) component to render the SVG path for each icon. For each SVG icon, we export the respective React component from the `@mui/icons-material` package.

Run the following command from your terminal:

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

Or if you are using Yarn:

```
yarn add @mui/material @emotion/react @emotion/styled
```

#### Step 3: Do Some Housekeeping of The Default Code

Let’s make these initial changes:

1. Remove all the code from App.js file and simply return the <Barcode /> component as so:

```
import Barcode from "./barcode";
function App() {
  return <Barcode />;
}
export default App;
```

2. Create a new component file under the src directory called Barcode.jsx. This will house all of the MUI customization code for our component.

3. Add the barcode image you have to the assets directory under the images folder so you have access to the file when needed to render.

#### Step 4: Theme the component with MUI!

Here’s the nitty-gritty! We can now start to create our Barcode component.

Still inside the Barcode.jsx file, export the Barcode function with a return statement to follow. To start you can also simply render a `<p>` tag that says “Barcode component”. If you save your code the render should work.

```
export default function Barcode() {
  return <p>Barcode component</p>;
}
```

## The ThemeProvider Wrapper

By default all the MUI components and styles you will use have a set default theme that looks like this:

![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2tc1s2mcr4i02xo8p8ng.png)

As you can see above, this default theme is a collection of objects with their properties and values. For example, here it shows the color palette of an MUI app. If you wish to use the primary, the main color in any of your React elements like a button background color or a divider color, then its hex value will be [#1976d2](https://paper.dropbox.com/?q=%231976d2) as listed.

But in our design, we don’t see such colors as listed on their documentation so to make our own theme work we need the [ThemeProvider](https://mui.com/customization/theming/#theme-provider) component from `@material-ui/core` and make all of the elements as their child in our render method.

This component takes a theme prop. One thing to note is that It should preferably be used at **the root of your component tree**. So let’s remove the placeholder `<p>` tag we had before and use this as:

```
return <ThemeProvider theme={theme}>...</ThemeProvider>;
```

Make sure you import it too:

```
import { ThemeProvider } from "@material-ui/core";
```

## Create a Custom Theme

The obvious next step is to actually add our own theming values so that the theme prop works. Outside the Barcode function definition, create a new theme object that uses the [createMuiTheme()](https://mui.com/customization/theming/#createtheme-options-args-theme) method. This is used to generate a theme based on the options received which are later passed down to the theme variable of <ThemeProvider>.

createMuiTheme() takes in two arguments of which the first one is really important. It’s the options object that takes an incomplete theme object and this is the only argument that is processed. Inside this object, we can define our custom values to each of the different properties like typography, colors, spacing, font size, etc.

In this demo, let’s try to implement the current font styles. As per our design, the font used in the heading and the paragraph below is called [Outfit available on the Google Fonts](https://fonts.google.com/specimen/Outfit) directory. So to add a custom font in an MUI project we need to follow these steps:

1. Copy the HTML/CSS import(s) from the custom font CDN. In our case, simply copy the <link> tags that Google provides after selecting the two weights we need of the Outfit font family.

2. Update the index.html file by pasting in those link tags and removing the default Roboto font included in an MUI project.

```
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
  href="https://fonts.googleapis.com/css2?family=Outfit:wght@400;700&display=swap"
  rel="stylesheet"
/>
```

3. Create the typography object under the createMuiTheme call giving it the proper names and values like:

```
typography: {
  fontFamily: "Outfit",
  fontWeightRegular: 400,
  fontWeightBold: 700
}
```

Now that MUI knows that a custom font is to be used, let’s implement it in our Barcode component. But first, we need to make that card layout and add the image!

## Using Default MUI Components

We will need a total of 3 new components that MUI provides to make our barcode look exactly like it’s on the design. Here are those:

1. **The Card component:** the basic aim of the card is to contain content and actions about a single subject. MUI has various types of Card components under its belt. Here’s an example:


![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00s4avdca6u2rwsh7yh3.png)

One great thing about most of the elements in MUI is that we can pass a custom style to any element using the [sx prop](https://mui.com/system/the-sx-prop/#main-content).  It’s like is a shortcut for defining a custom style that has access to the theme. So if we quickly want to change the margins, or width of any element that’s not in our design system we can simply use the sx prop. 

For example in our <Card> the component we can provide it a custom padding, boxShadow, borderRadius, horizontal margin and maxWidth as:

```
<Card
  sx={{
    maxWidth: 350,
    mx: "auto",
    padding: "1rem",
    borderRadius: "4%",
    boxShadow: 24
    }}
>
```

2. **The CardMedia component:** this type of card is perfectly suited for our design as it has an image up top and the content below it. Let’s use it as follows:

```
<CardMedia
  component="img"
  height="350"
  image="path/to/image.png"
  alt="Barcode image"
  sx={{ borderRadius: "4%" }}
/>
```

This will house a new [<CardContent> API](https://mui.com/api/card-content/#main-content) for cards under which we can nest all the card content text like our heading and subheading as:

```
<CardContent>
// Other components 
</CardContent>
```

3. **[TheTypography](https://mui.com/components/typography/#main-content) component:** this is specifically used to render text elements from a big bold heading of a section to small captions generated on a video. Thus, it comes with a variety of props like align, mt, variant, etc. In our app, we use it for the heading of the card as:

```
<Typography
  gutterBottom
  variant="h5"
  component="div"
  align="center"
  fontFamily="Outfit"
  fontWeight="fontWeightBold"
  mt={2}
  mb={2}
  sx={{ color: "#182036" }}
>
Improve your front-end <br /> skills by building projects
</Typography>
```

Notice the use of our custom-defined fonts and their weights. We were able to pass the font family and font-weight props to it easily with the set values in the theme object defined above.

Next, we do a similar thing to the subheading with a few tweaks of color and fontWeight:

```
<Typography
  variant="body2"
  align="center"
  fontFamily="Outfit"
  fontWeight="fontWeightRegular"
  sx={{ color: "#7b879d" }}
>
Scan the QR code to visit Frontend <br /> Mentor and take your coding skills to <br /> the next level
</Typography>
```

With all that code, you should get the expected styling in your browser similar to this:


![Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/roudd3llx24igxkbiafv.png)

If you implemented the above steps successfully, you should have the following code:

```
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import CardMedia from "@mui/material/CardMedia";
import Typography from "@mui/material/Typography";
import { createMuiTheme, ThemeProvider } from "@material-ui/core";

const theme = createMuiTheme({
  typography: {
    fontFamily: "Outfit",
    fontWeightRegular: 400,
    fontWeightBold: 700
  }
});

export default function Barcode() {
  return (
    <ThemeProvider theme={theme}>
      <Card
        sx={{
          maxWidth: 350,
          mx: "auto",
          padding: "1rem",
          borderRadius: "4%",
          boxShadow: 24
        }}
      >
        <CardMedia
          component="img"
          height="350"
          image="https://i.imgur.com/AJJqWpN.png"
          alt="Barcode image"
          sx={{ borderRadius: "4%" }}
        />
        <CardContent>
          <Typography
            gutterBottom
            variant="h5"
            component="div"
            align="center"
            fontFamily="Outfit"
            fontWeight="fontWeightBold"
            mt={2}
            mb={2}
            sx={{ color: "#182036" }}
          >
            Improve your front-end <br /> skills by building projects
          </Typography>
          <Typography
            variant="body2"
            align="center"
            fontFamily="Outfit"
            fontWeight="fontWeightRegular"
            sx={{ color: "#7b879d" }}
          >
            Scan the QR code to visit Frontend <br /> Mentor and take your
            coding skills to <br /> the next level
          </Typography>
        </CardContent>
      </Card>
    </ThemeProvider>
  );
}
```

And just like that, you were able to understand MUI’s core components needed to make such a component from scratch with a custom theme!

In this tutorial, you got to know the setup MUI React UI library, its installation, and how to make use of its important components like ThemeProvider, Card, Typography, etc to finally convert a design to a custom code. 

Next, you can take it further by defining more values inside the createMuiTheme() function like spacing, colors, etc to create even more custom interfaces.

Also if you’re looking for pre-built Material UI Templates then there are some sites like [WrapPixel](https://www.wrappixel.com/?ref=232) and [AdminMart](https://adminmart.com/?ref=6) that could skyrocket your development process, then visit the page now. Good luck!