Using Material-UI in a project without the need for create-react-app

My objective is to utilize Material-UI without relying on create-react-app, as I feel that it abstracts too much and hinders my learning process. Unfortunately, all the instructions I have come across are centered around create-react-app.

I am aiming to set up the most minimalistic configuration possible for this, particularly for educational purposes. To begin with, my goal is to simply display a basic Material-UI Button.

To achieve this, I started with the most stripped-down React "Hello World" example from reactjs.org and integrated the Material-UI UMD in the following manner:


    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <title>Hello World</title>
          <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
          <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
          <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
          <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
      </head>
      <body>
        <div id="root"></div>
        <script type="text/babel">
    
          ReactDOM.render(
            <Button variant="contained" color="primary">
               Hello World
            </Button>,
            document.getElementById('root')
          );
    
        </script>
      </body>
    </html>

I am encountering difficulties importing the Button from material-ui.development.js and then rendering it.

I have experimented with various import and require() expressions at different points in the code, but it has been more of trial and error rather than truly understanding what is required.

I am hopeful that someone can provide guidance on this matter.

Answer №1

Appreciation to hotpink for the detailed explanations! Your input was instrumental in solving my issue. Here is how the code appears within my specific context:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">

      ReactDOM.render(
        <MaterialUI.Button variant="contained" color="primary">
          Appreciation to hotpink
        </MaterialUI.Button>,
        document.getElementById('root')
      );

    </script>
  </body>
</html>

Outcome

Answer №2

This covers a variety of subjects. The script file you have includes a module, where the module function is an IIFE. While it may not be simple code, the crucial part to note is:

factory(global.MaterialUI = {}, global.React, global.ReactDOM)

global is a parameter passed into the function as this, and factory is another function parameter that is itself a function. In this context, this refers to an object, which is actually window. Thus, what you can access is window.MaterialUI.

You can skip mentioning the window for ease of access. Your Button component can be accessed via MaterialUI.Button. If you intend to use multiple components, consider using a destructuring assignment:

const { Button, TextField, Typography } = MaterialUI

I would like to emphasize that these concepts are not specifically tied to Material-UI or React, so if you wish to learn them, using CRA is perfectly acceptable in my opinion.

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

Issue: The module 'react-dev-utils/getPublicUrlOrPath' cannot be located

I recently deployed my React.js application on Heroku but encountered a message stating: The Browserslist indicates that caniuse-lite is outdated and advises to run the following command: npm update. In response, I executed npm update followed by ...

React Native - state hook refreshes and causes the component to re-render, yet no changes are visible

Here is the code snippet: export default () => { const [albums, setAlbums] = useState([]); useEffect(() => { MediaLibrary.getAlbumsAsync().then((tmpAlbums) => { setAlbums(tmpAlbums); }); }, []); return ( ...

Is it possible to transform JSON Array Data from one format to another?

As someone who is new to the software field, I am working with a JSON array of objects: var treeObj = [ { "name": "sriram", "refernce_id": "SAN001", "sponer_id": "SAN000" }, { "name": "neeraja", "r ...

Exploring the variance in outcomes when directly accessing an AuthService state versus utilizing a function in a React AuthContext

I am currently working on creating an AuthContext, but I am encountering an issue with changing the state of a variable. Here is the code snippet: index.js import Head from "next/head"; import Image from "next/image"; import styles fro ...

Using multiple functions to organize nested variables within the useState hook

I'm stuck trying to figure out a part of my application, leading me to have some questions. I am working with a JSON string from an API as input for my project. This JSON string needs to generate multiple input fields on the page, which I then plan to ...

Using JavaScript to assign multiple classes to a function at separate intervals

I'm trying to add two classes to a JavaScript function, but I'm encountering some issues. When I try to add both classes in the same line, only one of them works. However, if I add each class on separate lines within the function, only the second ...

Updating Vue component with mismatched props

I am looking to optimize the Vue component where data is received in varying structures. Take for example Appointment.vue component: <template> <div> <div v-if="config.data.user.user_id"> {{ config.data.user.user_id ...

Adding auth0 authentication to a Next.js 13 application: A step-by-step guide

Currently, I am using a nextjs 12 application and set up auth0 as my authentication provider by following the guidelines provided here: . However, I am now looking to upgrade my application to nextjs 13, but I have not been able to find any documentation o ...

Exploring the concepts of closure and scope

It seems that the function inResult always returns false and the loop is not being executed, probably due to a lack of understanding of closures. However, I can confirm that the result variable contains the correct properties. function hasId() {return ...

What methods can I use to compare a React Component across multiple pages with Cypress?

One task I am trying to tackle is comparing a component on one page with the same component on another page using Cypress. For example, let's say I have a Pricing Component on the Home page, and I want to verify if the values on the Pricing Page are i ...

conceal menu upon click (gradually disappear)

This is a basic HTML/CSS menu. Currently, it is functioning properly for page redirection (href). However, I would like it to hide after being clicked on. I plan to call a function that will initiate an AJAX request upon clicking. Here is the code on JS ...

Angular utilizing external parameter for Ajax requests

As a newcomer to Angular, I am eager to upgrade some old jQuery code with AngularJS. The task at hand is to extract a string from a span element, split it into two separate strings, and then use these as parameters in a GET request. I am dedicated to lea ...

Issue with jQuery function not recognizing escaped double quotes in PHP script

Greetings! I am currently utilizing a custom control with PHP code. $parentLinkCombo = '<select name="ParentComboLink" onchange="changeChildCombo(\"LICENCE\");" id="ParentComboLink" >'; In order to handle the onchange event, I ...

The Angular route functions flawlessly in the development environment, but encounters issues when deployed to

I have a project built with Angular 2, During development on localhost, everything runs smoothly. However, once I build a production version using (npm run build: prod) and navigate to the route on the server, I encounter a 404 error indicating that the r ...

Struggling with dynamically updating fields based on user input in real time

I have a goal to update a field based on the inputs of two other fields. Currently, all the fields are manual input. Below is the code I'm using to try and make the "passThru" field update in real-time as data is entered into the other fields. The ma ...

NextJs not processing Bootstrap form submissions

I’m struggling to figure out why my form isn’t submitting when I click the submit button. The backend seems fine because Postman successfully sends the information to the database. However, nothing happens when I try to submit the form. My tech stack ...

Switching the endpoint renders the middleware ineffective

I've encountered a puzzling issue with my NodeJs - Express server, which serves as the backend for my mobile application. The problem arises when I send post requests to certain endpoints like checkmail and checkusername using axios from the frontend ...

Leverage context to facilitate communication between components operating at various levels of the system

I am currently working on the settings pages of my applications. Each page features a common SettingsLayout (parent component) that is displayed across all settings pages. One unique aspect of this layout is the presence of an ActionsBar, where the submit/ ...

Display/Conceal JavaScript

I recently implemented a JavaScript function on my website to show/hide specific elements. However, being new to JavaScript, I have encountered some difficulties. I've spent quite some time troubleshooting the code but haven't been able to pinpoi ...

Validating the KeyboardDatePicker in react-hook-form when the date is not valid

When validating a Material UI KeyboardDatePicker using react-hook-form, I ran into an issue: <Controller name="endDate" control={control} defaultValue={new Date()} rules={{ required: "End date is required" }} render={({ field, fieldState }) => { retu ...