Mastering the art of utilizing Modal components in Fluent UI

I recently started using React and Fluent UI, and I encountered an issue when trying to open a modal. I have loaded all my files from CDNs but the modal doesn't seem to open when executing the code below. I've tried looking for examples, but haven't found a solution yet. Below is the code snippet:

  const { DefaultButton,Fabric,Modal,IconButton} = window.FluentUIReact;
    const app = () =>{
      var isModalOpen = false;
      function showModal(){
        isModalOpen = true;
      }
      function hideModal(){
        isModalOpen = false;
      }
      return (
        <Fabric applyThemeToBody>
        <DefaultButton onClick={showModal}>Make a Poll</DefaultButton>
        <Modal
            titleAriaId={"id"}
            isOpen={isModalOpen}
            onDismiss={hideModal}
            isBlocking={true}
          >
            <div>
              <span id={"id"}>Lorem Ipsum</span>
              <IconButton
                iconProps = {{iconName: 'Cancel'}}
                ariaLabel="Close popup modal"
                onClick={hideModal}
              />
            </div>
            <div>
              <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas lorem nulla, malesuada ut sagittis sit
                amet, vulputate in leo. Maecenas vulputate congue sapien eu tincidunt. Etiam eu sem turpis. Fusce tempor
              </p>
            </div>
          </Modal>
        </Fabric>
      );
    };

    ReactDOM.render(app(), document.getElementById('app'))
<div id="app"></div>
  <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
  <script crossorigin src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f2d3a3e3c2b723b30321f6e69716e6b716f">[email protected]</a>/umd/react-dom.production.min.js"></script>
  <script src="https://unpkg.com/@fluentui/react@7/dist/fluentui-react.js"></script>
  <script src="https://unpkg.com/@uifabric/react-hooks@7/dist/react-hooks.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script defer type="text/babel" src="script.jsx"></script>

Any assistance would be greatly appreciated.

Answer №1

When using the isModalOpen = true/false in React, it's important to note that React won't automatically re-render the view. To handle state management, React provides the useState hook. By calling the setter function, you can update the value and trigger a re-render of the component.

Hooks can only be called inside components and custom hooks. Therefore, we need to convert the app function into a proper component by renaming it to start with a capital letter.

According to Components and Props:

Note: Component names should always begin with a capital letter.

React interprets lowercase component names as DOM tags. For instance, <div /> represents an HTML div element, while <Welcome /> represents a component and requires Welcome to be within scope.

To understand more about this naming convention, refer to JSX In Depth.

After updating our function to a component, we also need to adjust how we call App. Instead of passing app() to ReactDOM.render(), now we pass <App />.

const { useState } = React;
const { DefaultButton, Fabric, Modal, IconButton } = FluentUIReact;

const App = () =>{
  const [isModalOpen, setIsModalOpen] = useState(false);
    
  function showModal() {
    setIsModalOpen(true);
  }
  function hideModal() {
    setIsModalOpen(false);
  }
  return (
    <Fabric applyThemeToBody>
      <DefaultButton onClick={showModal}>Make a Poll</DefaultButton>
      <Modal
        titleAriaId="id"
        isOpen={isModalOpen}
        onDismiss={hideModal}
        isBlocking={true}
      >
        <div>
          <span id="id">Lorem Ipsum</span>
          <IconButton
            iconProps = {{iconName: 'Cancel'}}
            ariaLabel="Close popup modal"
            onClick={hideModal}
          />
        </div>
        <div>
          <p>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas lorem nulla, malesuada ut sagittis sit
            amet, vulputate in leo. Maecenas vulputate congue sapien eu tincidunt. Etiam eu sem turpis. Fusce tempor
          </p>
        </div>
      </Modal>
    </Fabric>
  );
};

ReactDOM.render(<App />, document.getElementById('app'))
<div id="app"></div>

<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5d4a4e4c5b024b40426f1e19011e1b011f">[email protected]</a>/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@fluentui/react@7/dist/fluentui-react.js"></script>
<script src="https://unpkg.com/@uifabric/react-hooks@7/dist/react-hooks.js"></script>

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

Setting up the Gumby Framework: A Step-by-Step

As I begin to delve into learning a Responsive CSS Framework, I've decided to do a comparison between Foundation 4, Gumby, and Bootstrap on my own. I had success running Foundation 4 and Bootstrap, but unfortunately Gumby didn't cooperate. Upon ...

Discover choices based on the values in an array

I'm having trouble finding an option in a select menu based on an array value. var array = ["task1", "task2"] var select = document.getElementsByTagName('select'); for (i = 0; i < 2; i++) { $(select).find('option[value=array[i]] ...

Tips for retaining a number even when the page is refreshed

Is there a way to keep the number increasing even after refreshing the webpage? Currently, the number resets every time the page is refreshed. Any suggestions on how to fix this? Here is the number <form method="POST"> &l ...

Place the outcome of the function into the div element's attribute

As a newcomer to HTML and JavaScript, I recently dove into using 3Dmol.js. Following a tutorial, I was able to create this code snippet that actually works: <script src="http://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script> <div id="el ...

In order to add value, it is necessary to insert it into the text box in HTML without using the "on

example <input type="text" id="txt1" onChange="calculateTotal();" /> <input type="text" id="txt2" onChange="calculateTotal();" /> <input type="text" id="txt3" onChange="updateValue();" readonly/> <input type="text" id="txt4" onChange= ...

"Upload a video file and use JavaScript to extract and save the first frame as an image

I have a webpage where users can upload a video file, and the page will generate a thumbnail based on a timestamp provided by the user. Currently, I am focusing on generating the thumbnail from the FIRST frame of the video. Here is an example of my progr ...

Using Vuex: Bypassing Action and triggering Mutation directly within Component

When working with a vue.js app and utilizing vuex as the state management store, one may need to update a property's value in vuex. This can be achieved through two methods: One can dispatch an action method, which will then commit a mutation to a ...

Assistance needed in retrieving an element using jQuery

After posting a similar question and receiving a correct answer that didn't quite meet my needs, I realized it was my mistake. Imagine having the following HTML: <TD nowrap="true" valign="top" width="190px" class="ms-formlabel"> <H3 class=" ...

Having trouble understanding why getStaticProps function is not loading before the main exported function

When I use npm run dev to troubleshoot this issue, it utilizes getStaticProps to process various d3 properties before injecting them into the main output function during runtime. However, it seems that getStaticProps is not running as expected - a consol ...

Exploring Angular 9: Harnessing the Power of Fork Join with an Array of

I have a challenge where I need to send multiple API requests to an endpoint by iterating over an array of values To handle this, I decided to use rxjs library and specifically the forkJoin method //array to keep observables propOb: Observable<any>[ ...

Error: This action is not supported by the object in Internet Explorer 11

I have encountered a strange issue where my code works perfectly in Google Chrome, but throws an error in Internet Explorer specifically at the line mentioned below. Does anyone have any suggestions on what changes need to be made for it to work in IE? va ...

Trouble with AJAX request when trying to connect to a distant server

I am facing an issue with my AJAX request. When I test it on localhost, everything works perfectly fine. However, when I upload the code to a remote server, the request fails without any error messages. Even after checking in Firefox and Chrome, there ar ...

Creating arrow indicators in navigation menus using CSS and JavaScript can be seen on websites like playframework.org

While browsing the site, I noticed that the navigation menu at the top has a unique feature - a small arrow that points upward for the currently selected section (Home, Learn, Download,...). I tried to figure out how they implemented it, but I couldn&apos ...

What significance does this change in font size hold?

Similar Question: Understanding the CSS Usage Could you explain the purpose of this font resizing code in CSS? font:12px/170% Verdana,sans-serif ...

Using JavaScript to dynamically write content to the document in the

What is the correct way to write the HTML break tag "<br>" in JavaScript without it causing a line break? I want the tag to be displayed as text. For example, "the break tag in html is ..." See below for an example of what I am looking for. <scr ...

Are multiple instances of ajax being executed within the modal?

Currently, I am working on a feature that requires an Ajax request. To begin with, the process involves opening a modal by clicking a button with the class '.open-email-modal'. Within this modal, there are two input fields to enter registration d ...

The issue of page content failing to refresh when loaded using AJAX technology

My script utilizes AJAX to dynamically load specific pages on a website. These pages display information that updates based on the current time. However, I have encountered an issue where the page content remains static when loaded through AJAX, almost as ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Align a text box and button in the center with precision using Bootstrap 5

Here is the code snippet using bootstrap 5: <div style="margin-top: 30%" class="text-center"> <h1>Let's get started...</h1> <input id="form-input" style="display: inline-block;" ...

Include the preset value within the textarea input box

I am looking to set a default value in the Textarea field. When the user enters text, I want the default value to always be included with the text. Similar to Fiverr, where the text "I will" is added automatically when the user enters a title. For refer ...