次.MUI V 5チュートリアル


あなたがスターターチェックを探しているならばQuick Start
TypeScriptチェックを使用する必要がある場合

目次
  • What is this post about?
  • Why Next.js?
  • Why MUI?
  • Step one: Installing Next.js
  • Step two: Installing emotion
  • Step three: Installing MUI
  • Step four: Creating a MUI theme
  • Step five: Creating an emotion cache
  • Step six: Edit _app.js
  • Step seven: Creating a custom document file in Next.js
  • Step eight (Optional but recommended): Using prop-types package
  • Quick start
  • Conclusion

  • What is this post about?

    This post will help you to start a project using Next.js and MUI (formerly Material-UI). As you may notice using Next.js together with MUI may be a little bit tricky. I will explain each step to you to make it much more clear.


    Why Next.js?

    Well, You can find lots of articles and videos talking about Next.js benefits and I'm not really going to explain everything about Next.js features in this post, but shortly these are some of its amazing features:

    • It just load the JavaScript and CSS which page really need. This will make the page loading a lot faster.

    • All images can be optimized with the help of Next.js Image component.

    • Fast refresh

    to discover more about Next.js click here .

    Why MUI?

    as you can read on MUI site:

    MUI provides a robust, customizable, and accessible library of foundational and advanced components, enabling you to build your own design system and develop React applications faster.

    MUI is well documented and for every single component you can find out how to use or how to customize it.

    the latest version of MUI is faster and also has got a smaller bundle size.

    you can click here MUI最新バージョンについてもっと知りたい.

    Step one: Installing Next.js
    1. Run npx create-next-app@latest project-name or yarn create next-app project-name and replace project-name with your own.

    Tip: If you already have a project folder created and wanna install Next.js in that directory simply add period instead of project-name. So, it'll be npx create-next-app@latest . or yarn create next-app .

    I am going to name this starter "muxt" which is combination of MUI and Next. Also I am using NPM as package manager.

    so for me it'll be npx create-next-app muxt .

    1. After that the installation is done go to the project folder by cd project-name and open it in your favorite code editor which for me is VS Code.

    the initial folders and files structure should be like this image:

  • すべてが完全に動くことを確認するためにnpm run dev or yarn dev そして、あなたのブラウザーで3000をlocalhostにしてください.あなたはこのようなページを見るべきです.


  • Step two: Installing emotion

    as the MUI docs says:

    The default style library used for generating CSS styles for MUI components is emotion.


    次はmuiを使用します.これらのパッケージをインストールする必要があります.
  • @エモーションキャッシュ
  • @感情/反応
  • @エモーションサーバー
  • @エステスタイル
  • だから、実行npm i @emotion/cache @emotion/react @emotion/server @emotion/styled or yarn add @emotion/cache @emotion/react @emotion/server @emotion/styled
    Step three: Installing MUI
  • install MUI with this command npm i @mui/material or in case you use yarn run yarn add @mui/material

  • MUI uses Roboto デフォルトのフォントとして、このコマンドでインストールする必要があります.npm i @fontsource/roboto or yarn add @fontsource/roboto
  • (オプション) MUIアイコンコンポーネントを使用すると思われる場合は、そのパッケージをインストールする必要があります.しかし、私は私のスターターでそれを持つためにそれをインストールするつもりです.実行するnpm i @mui/icons-material or yarn add @mui/icons-material
  • はい、我々は必要なすべてをインストールしている.インストールした全てのパッケージを見てみましょう.


    Step four: Creating a MUI theme

    After installations, first we need to create a theme. With the help of MUI theme files you can create custom styles or different styles for light or dark mode. Here we are just going to create a theme file with only one option.

  • create a folder named 'theme' in styles folder
  • LightThemeの名前でファイルを作成します.テーマフォルダのJS.テーマの代わりにこのファイルLightThemeを命名することの後ろの考えは、我々が後で戻って来ることができて、我々のダーク・モードテーマオプションを含むDarkThemesの名前で別のファイルを加えることであるということです.そのファイルでこれらの行を追加します.
  • import { createTheme } from '@mui/material/styles';
    
    const lightTheme = createTheme({
      palette: {
        mode: 'light',
      },
    });
    
    export default lightTheme;
    
    ヒント:ダークモードを使用してアプリケーションを起動する場合は、ファイルdarkthemeを名前を付けることができますし、ダークにパレットモードを設定し、そのファイルを次の手順に従ってください.
    なぜ1つのオプションを持っている間、我々はこのファイルを作成するつもりですか?さて、後で、私はMUIのthemeProviderコンポーネントにテーマを渡す必要があります、そして、私が別々のファイルですべてを置かれる理由は最初から適切にファイルとフォルダを建設したいということです.
    これは、上記の手順を踏んだ後の新しいフォルダーの様子です.


    Step five: Creating an emotion cache

    You need to create a cache for your styles because you are using Next.js and this will help the app to figure out what style to apply. For now let's just create a folder name utility and create a file name createEmotionCache.js in that folder.

    Then add the following code:

    import createCache from '@emotion/cache';
    
    const createEmotionCache = () => {
      return createCache({ key: 'css' });
    };
    
    export default createEmotionCache;
    

    Here's the result in editor:



    Step six: Edit _app.js

    So, until now we've created a lightTheme for our app and we also create a function which create a cache for us, This step and the next one is about using them.

    1. First open _app.js file in the pages directory.
    2. Replace the code with the following one:
    import React from 'react';
    import { CacheProvider } from '@emotion/react';
    import { ThemeProvider, CssBaseline } from '@mui/material';
    
    import createEmotionCache from '../utility/createEmotionCache';
    import lightTheme from '../styles/theme/lightTheme';
    import '../styles/globals.css';
    
    const clientSideEmotionCache = createEmotionCache();
    
    const MyApp = (props) => {
      const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
    
      return (
        <CacheProvider value={emotionCache}>
          <ThemeProvider theme={lightTheme}>
            <CssBaseline />
            <Component {...pageProps} />
          </ThemeProvider>
        </CacheProvider>
      );
    };
    
    export default MyApp;
    

    Explanation of the code above:

    • First we import React
    • Next we import CacheProvider component from '@emotion/react', we use this component to provide a shared client-side cache for a user session.
    • We also import ThemeProvider and CssBaseline from '@mui/material'; using themeProvider let us to pass our theme throw the app and CssBaseline as mui says:

    CssBaseline kickstart an elegant, consistent, and simple baseline to build upon.

    • Below the import statements we create a constant which contains a emotion cache and we use it as default value for emotionCache prop.

    Step seven: Creating a custom document file in Next.js

    In the pages folder add _document.js file. for now just add these lines of code to the file. I'll explain theme in a second.

    import * as React from 'react';
    import Document, { Html, Head, Main, NextScript } from 'next/document';
    import createEmotionServer from '@emotion/server/create-instance';
    import createEmotionCache from '../utility/createEmotionCache';
    
    export default class MyDocument extends Document {
      render() {
        return (
          <Html lang="en">
            <Head>
              <link
                rel="stylesheet"
                href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
              />
            </Head>
            <body>
              <Main />
              <NextScript />
            </body>
          </Html>
        );
      }
    }
    
    // `getInitialProps` belongs to `_document` (instead of `_app`),
    // it's compatible with static-site generation (SSG).
    MyDocument.getInitialProps = async (ctx) => {
      // Resolution order
      //
      // On the server:
      // 1. app.getInitialProps
      // 2. page.getInitialProps
      // 3. document.getInitialProps
      // 4. app.render
      // 5. page.render
      // 6. document.render
      //
      // On the server with error:
      // 1. document.getInitialProps
      // 2. app.render
      // 3. page.render
      // 4. document.render
      //
      // On the client
      // 1. app.getInitialProps
      // 2. page.getInitialProps
      // 3. app.render
      // 4. page.render
    
      const originalRenderPage = ctx.renderPage;
    
      // You can consider sharing the same emotion cache between all the SSR requests to speed up performance.
      // However, be aware that it can have global side effects.
      const cache = createEmotionCache();
      const { extractCriticalToChunks } = createEmotionServer(cache);
    
      /* eslint-disable */
      ctx.renderPage = () =>
        originalRenderPage({
          enhanceApp: (App) =>
            function EnhanceApp(props) {
              return <App emotionCache={cache} {...props} />;
            },
        });
      /* eslint-enable */
    
      const initialProps = await Document.getInitialProps(ctx);
      // This is important. It prevents emotion to render invalid HTML.
      // See https://github.com/mui-org/material-ui/issues/26561#issuecomment-855286153
      const emotionStyles = extractCriticalToChunks(initialProps.html);
      const emotionStyleTags = emotionStyles.styles.map((style) => (
        <style
          data-emotion={`${style.key} ${style.ids.join(' ')}`}
          key={style.key}
          // eslint-disable-next-line react/no-danger
          dangerouslySetInnerHTML={{ __html: style.css }}
        />
      ));
    
      return {
        ...initialProps,
        // Styles fragment is rendered after the app and page rendering finish.
        styles: [
          ...React.Children.toArray(initialProps.styles),
          ...emotionStyleTags,
        ],
      };
    };
    

    Ok, time to explain what exactly going to happen.

    • On the first line we import React
    • On the second line we import Document, HTML, Head, Main, NextScript
    • We extend our custom Document component with imported Document from 'next/document'. Generally the purpose is to have everything from Document component by default and then customize something in it.
    • Imported Html component help us to set some properties like lang or dir for our app.
    • Imported Head component is useful if you wanna have some general thing in you app, for example you can import your app icon here. Just be aware that this component is different from the one that we can import from 'next/head'
    • In addition to Html and Head component, Main and NextScript are also required for the page to render properly.
    • Next, when we use getInitialProps we enable server-side rendering and it let us to have initial data population. as the Next.js docs says:

    it means sending the page with the data already populated from the server.


    Step eight (Optional but recommended): Using prop-types package

    It is a good practice to provide types for our props to avoid runtime errors and also make development easier. Since we don't use typescript in this starter, we can use "props-types" package to define type and enable runtime type checking for our app.

    So, run npm i prop-types or yarn add prop-types .

    after that open _app.js and replace the code with this one:

    import React from 'react';
    import PropTypes from 'prop-types';
    import { CacheProvider } from '@emotion/react';
    import { ThemeProvider, CssBaseline } from '@mui/material';
    
    import createEmotionCache from '../utility/createEmotionCache';
    import lightTheme from '../styles/theme/lightTheme';
    import '../styles/globals.css';
    
    const clientSideEmotionCache = createEmotionCache();
    
    const MyApp = (props) => {
      const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
    
      return (
        <CacheProvider value={emotionCache}>
          <ThemeProvider theme={lightTheme}>
            <CssBaseline />
            <Component {...pageProps} />
          </ThemeProvider>
        </CacheProvider>
      );
    };
    
    export default MyApp;
    
    MyApp.propTypes = {
      Component: PropTypes.elementType.isRequired,
      emotionCache: PropTypes.object,
      pageProps: PropTypes.object.isRequired,
    };
    

    What we do here is that we define some keys and their type which can be accessible through props of MyApp component.


    Quick start

    If you feel this process a bit boring or if you want to start faster you can check the link below which is the result of steps that I explained above. Just download the code and rename the project to whatever you want and run npm i or yarn .

    get starter from here

    Conclusion

    That's it, your app is now ready. Let me know if you need help or something else.