Modal Popup In SPFx💡

Introduction

In this article, we will learn about the implementation of Modal Popup in our SPFx component using FluentUi.

Steps

Open a command prompt and create a directory for the SPFx solution.

md spfx-MyModalPopup

Navigate to the above created directory.

cd spfx-MyModalPopup

Run the Yeoman SharePoint Generator to create the solution.

yo @microsoft/sharepoint

Solution Name

Hit Enter for the default name (spfx-MyModalPopup in this case) or type in any other name for your solution.

Selected choice - Hit Enter

Target for the component

Here, we can select the target environment where we are planning to deploy the client web part; i.e., SharePoint Online or SharePoint OnPremise (SharePoint 2016 onwards).

Selected choice - SharePoint Online only (latest).

Place of files

We may choose to use the same folder or create a subfolder for our solution.

Selected choice - same folder.

Deployment option

Selecting Y will allow the app to be deployed instantly to all sites and be accessible everywhere.

Selected choice - N (install on each site explicitly).

Permissions to access web APIs

Choose if the components in the solution require permission to access web APIs that are unique and not shared with other components in the tenant.

Selected choice - N (solution contains unique permissions)

Type of client-side component to create

We can choose to create a client-side web part or an extension. Choose the web part option.

Selected choice - WebPart

Web part name

Hit Enter to select the default name or type in any other name.

Selected choice - MyModalPopup

Web part description

Hit Enter to select the default description or type in any other value.

Framework to use

Select any JavaScript framework to develop the component. Available choices are - No JavaScript Framework, React, and Knockout.

Selected choice - React

The Yeoman generator will perform a scaffolding process to generate the solution. The scaffolding process will take a significant amount of time.

Once the scaffolding process is completed, lock down the version of project dependencies by running the below command,

npm shrinkwrap

In the command prompt, type the below command to open the solution in the code editor of your choice.

npm install @fluentui/react

In MyModalPopup.tsx,

import * as React from 'react';
import { IMyModalPopupProps } from './IMyModalPopupProps';
interface IPopupState {      
  callchildcomponent:boolean;
} 
import { DefaultButton } from '@fluentui/react/lib/Button';
import {MYModal} from './MYModal'
export default class MyModalPopup extends React.Component<IMyModalPopupProps, IPopupState> {
  constructor(props: IMyModalPopupProps, state: IPopupState) {    
    super(props);    
    this.state = {    
      callchildcomponent:false
    }; 
    this.handler = this.handler.bind(this);
    this.Buttonclick = this.Buttonclick.bind(this);
  }
    handler() {
      this.setState({
        callchildcomponent: false
      })
    }
    private Buttonclick(e) {
      e.preventDefault();
    
     this.setState({ callchildcomponent:true });
     
    
    }
  public render(): React.ReactElement<IMyModalPopupProps> {
    return (
      <div>
        
      <DefaultButton onClick={(e) =>this.Buttonclick(e) } text="Open Modal" />
       { this.state.callchildcomponent && <MYModal myprops={this.state} handler = {this.handler}/>}
      </div>
    );
  }
}

In MYModal.tsx,

import * as React from 'react';
import { useId, useBoolean } from '@fluentui/react-hooks';
import {
  getTheme,
  mergeStyleSets,
  FontWeights,
  Modal,
  IIconProps,
  IStackProps,
} from '@fluentui/react';
import { IconButton, IButtonStyles } from '@fluentui/react/lib/Button';
export const MYModal = (myprops) => {
  const [isModalOpen, { setTrue: showModal, setFalse: hideModal }] = useBoolean(false);
  const [isPopup, setisPopup] = React.useState(true);
  const titleId = useId('title');
  React.useEffect(() => {  
      showModal();
  }, [isPopup]); 
  function ExitHandler() {
    hideModal();
    setisPopup(current => !current)
    myprops.handler();
  }
  
  return (
    <div>
      <Modal
        titleAriaId={titleId}
        isOpen={isModalOpen}
        onDismiss={ExitHandler}
        isBlocking={true}
        containerClassName={contentStyles.container}
      >
        <div className={contentStyles.header}>
          <span id={titleId}>Modal Popup</span>
          <IconButton
            styles={iconButtonStyles}
            iconProps={cancelIcon}
            ariaLabel="Close popup modal"
            onClick={ExitHandler}
          />
        </div>
        <div  className={contentStyles.body}>
        <p>
        Saying “please” and “thank you.” It shows gratitude for the things others do for you.
Making introductions. Always introduce yourself to adults who come visit, and introduce friends to each other.
Covering your mouth when you sneeze or cough. Germs are gross!
Not picking your nose in public. No one wants to see that.
Greeting visitors and say goodbye to them. Even if you feel shy, greetings and goodbyes are important.
Asking for things instead of reaching for them. It’s disruptive when children reach across the table during mealtimes.
Knocking on doors before entering a room. Especially the bathroom door!
Responding when an adult asks how you are. It’s even better if you ask her how she is, too.
Not interrupting when grownups are talking. Wait for your turn, no matter how impatient you feel.
Saying “Excuse me” when you need to interrupt a conversation. Sometimes it’s an emergency, but even so, please be polite.
Saying “Excuse me” if you bump into someone. Make sure they know you didn’t do it on purpose.
Not using electronics at the dinner table. Show others that their presence is important to you.
Sitting attentively through plays, movies, and musical performances. Show proper respect, even if you’re bored.
Washing your hands before meals. It’s good etiquette and good hygiene too.
Not commenting on personal appearance. It hurts feelings unnecessarily.
Holding doors open for others. No one likes to have the door slam on them as they enter a room.
Keeping burps silent. And remember to say “Excuse me” afterward.
Offering to help adults if they need it. Help wash someone’s car or carry their groceries.
Giving a genuine apology when needed. Sometimes, the other person needs to hear you say, “I’m sorry.”
Asking to be excused at the end of a meal. Instead of just getting up to leave, say, “Please may I be excused?”
Using good table manners when eating. Use utensils properly and chew with your mouth closed.
Having a positive attitude. You will be someone that people enjoy having around.
Shaking hands. A firm handshake makes a good impression when you meet someone.
Returning items after borrowing them. Show respect for other people’s belongings.
Avoiding bad language. The words you use reveal your character.
Sharing. It’s a basic way to show consideration for the needs and feelings of others.
Giving compliments. Everyone likes to hear nice things about themselves.
Doing tasks for adults without complaining. Don’t make their lives more complicated by arguing.
Writing thank-you notes when you receive gifts. Technology is great, but sometimes people need a more personal touch.
Doing for others what you want them to do for you. If you remember this rule, it’s easier to follow all the others.
          </p>
        </div>
      </Modal>
  
    </div>
    
  );
};

const cancelIcon: IIconProps = { iconName: 'Cancel' };

const theme = getTheme();
const contentStyles = mergeStyleSets({
  container: {
    display: 'flex',
    flexFlow: 'column nowrap',
    alignItems: 'stretch',
  },
  header: [
    // eslint-disable-next-line deprecation/deprecation
    theme.fonts.xLarge,
    {
      flex: '1 1 auto',
      borderTop: '4px solid ${theme.palette.themePrimary}',
      color: theme.palette.neutralPrimary,
      display: 'flex',
      alignItems: 'center',
      fontWeight: FontWeights.semibold,
      padding: '12px 12px 14px 24px',
    },
  ],
  body: {
    flex: '4 4 auto',
    padding: '0 24px 24px 24px',
    overflowY: 'hidden',
    selectors: {
      p: { margin: '14px 0' },
      'p:first-child': { marginTop: 0 },
      'p:last-child': { marginBottom: 0 },
    },
  },
});
const stackProps: Partial<IStackProps> = {
  horizontal: true,
  tokens: { childrenGap: 40 },
  styles: { root: { marginBottom: 20 } },
};
const iconButtonStyles: Partial<IButtonStyles> = {
  root: {
    color: theme.palette.neutralPrimary,
    marginLeft: 'auto',
    marginTop: '4px',
    marginRight: '2px',
  },
  rootHovered: {
    color: theme.palette.neutralDark,
  },
};

Expected Output

Modal Popup in SPFX

Conclusion

In this article, we learned how to implement Modal Popup in our SPFx component. I hope this helps someone. Happy coding :)