React class component experiencing issues with Material UI popover functionality

I'm new to using Material UI and find that all its documentation is based on function components, which I am not familiar with. I'm having trouble getting the popover to work - whenever I hover over the text, the function triggers but the popover doesn't show up. I can access classes using this.props.classes. It would be greatly appreciated if someone could assist me with this.

import React, { Component } from "react";
import Popover from "@material-ui/core/Popover";
import Typography from "@material-ui/core/Typography";
import { withStyles } from "@material-ui/core/styles";

const useStyles = (theme) => ({
  root: {
    backgroundColor: "red",
    height: "30px",
  },
  lable: {
    transform: "translate(5px, 2px) scale(1)",
    pointerEvents: "none",
    width: "100%",
    height: "100%",
    padding: "10px",
    color: "red",
  },
  popover: {
    pointerEvents: "none",
    color:"pink"
  },
  paper: {
    padding: theme.spacing(1),
  },
  etc:{
    color: "red"
  }
});

class SomeThing extends Component {
open;
constructor(props){
  super(props)
  this.handlePopoverClose = this.handlePopoverClose.bind(this);
    this.handlePopoverOpen = this.handlePopoverOpen.bind(this);
  this.state={
    anchorEl: null,
  }
}
componentDidMount(){
  this.open = Boolean(this.state.anchorEl);
}
  handlePopoverOpen = (event) => {
    console.log("triggered!!!", event.currentTarget.innerText);
    this.setState({ anchorEl: event.currentTarget.innerText });
  };

  handlePopoverClose = () => {
    console.log("triggered again!!!", this.props);
    this.setState({ anchorEl: null });
  };
  render() {
    return (
      <div>
        <Typography
          aria-owns={this.open ? "mouse-over-popover" : undefined}
          aria-haspopup="true"
          className={this.props.classes.etc}
          onMouseEnter={this.handlePopoverOpen}
          onMouseLeave={this.handlePopoverClose}
        >
          Hover with a Popover.
        </Typography>
        <Popover
          id="mouse-over-popover"
          className={this.props.classes.popover}
          classes={{
            paper: this.props.classes.paper
          }}
          open={this.open}
          anchorEl={this.state.anchorEl}
          anchorOrigin={{
            vertical: "bottom",
            horizontal: "left"
          }}
          transformOrigin={{
            vertical: "top",
            horizontal: "left"
          }}
          onClose={this.handlePopoverClose}
          disableRestoreFocus
        >
          <Typography>I use Popover.</Typography>
        </Popover>
      </div>
    );
  }
}

export default withStyles(useStyles)(SomeThing);

Answer №1

If you want to ensure that your open variable is always a boolean and not undefined, define it within the render method. This will prevent any issues with its value.

render() {
  const open = Boolean(this.state.anchorEl);

  return (
    <div>
      <Typography
        aria-owns={open ? "mouse-over-popover" : undefined}
        aria-haspopup="true"
        className={this.props.classes.etc}
        onMouseEnter={this.handlePopoverOpen}
        onMouseLeave={this.handlePopoverClose}
      >
        Hover with a Popover.
      </Typography>
      ...
    </div>
  );
}

https://codesandbox.io/s/smoosh-frost-bvu1y?fontsize=14&hidenavigation=1&theme=dark

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

Interactive sliding panel in Material Design UI

I am experiencing an issue with the Swipeable drawer feature from Material UI. In a normal Drawer, it is not necessary to add a function for onOpen. So my question is, what should I include there? container={container} variant=" ...

Setting up React Context API with TypeScript: A Step-by-Step Guide

I recently updated my app.js file to app.tsx for improved functionality. However, I encountered an error with the current value. app.tsx import React, { createContext, useState } from "react"; import SelectPage from "./pages/select/select& ...

Encountering a problem while trying to run the command `npm run build`, receiving an error stating `TypeError: MiniCssExtractPlugin is not a

I encountered an issue while working on my react app. It runs smoothly with npm start, but when I attempt to build the app, it throws an error message. PS D:\ ****\ **\*\profile> npm run build > <a href="/cdn-cgi/l/email-prote ...

Customize the appearance of a SelectField (or its underlying DropDownMenu) using Material-UI styling options

Recently, I was experimenting with a basic SelectField feature and it seems to be functioning properly. However, I can't help but notice how unattractive it looks! My setup includes the default MaterialUI component styles along with the standard them ...

What causes the "Invalid hook call" error to occur when the useQuery function is invoked?

Encountering an issue while trying to use the useQuery() function from react-admin within a custom component. Despite the clear error message, I'm struggling to determine the right course of action. Visiting the provided website and following the inst ...

What is the method for establishing a default value for a Select element in Material Tailwind?

Currently, I am facing a situation where I have a Select component with 3 options, but the tailwind material Option component does not support the selected tag. As a result, I am unable to set a default value while rendering the component. Does anyone hav ...

Tips for personalizing the Material-UI sticky header to work with horizontal scrolling

Check out this example of a Material UI table with a sticky header on CodeSandox: https://codesandbox.io/s/yi98d?file=/demo.tsx I encountered an issue where the left side header cells slide behind each other when I added a stickyHeader prop to the Materia ...

What is the best way to utilize multiple models under a single root in ReactJS?

Greetings! I currently have a root structure in the following code snippet: <body> <noscript>You need to enable JavaScript to run this app.</noscript> <button >Platform</button> <button >Game</button> < ...

Access data from State in React

Just starting out with React. I have a backend API that I want to send requests to using Axios. I currently have two input fields for numbers: const [input, setInput] = useState(0); const [input2, setInput2] = useState(0); <div> ...

Integrating domain name into a post request using React

Currently, I have a frontend (react, Node.js) and a backend Springboot hosted on the same remote hosting service at . The frontend and backend are placed in different environments but function well individually. I connected my frontend to a domain and up ...

What steps should I take to transition from a class to a function in this scenario?

I am struggling to make the following code work properly. Every attempt I have made has resulted in issues with the event. import React from 'react' import YouTube from 'react-youtube'; export default class youtube extends React.Comp ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

"Transitioning from Material UI version 0.x to 1.y: A Guide to Migration

After utilizing Material UI v0 for some time, I've decided it's time to upgrade to MUI v1.x since v0.x is no longer supported. Could you please furnish me with a migration guide? ...

Maintain stack navigation in React Native's createSwitchNavigator even when switching screens

According to the documentation: "SwitchNavigator is designed to display only one screen at a time. By default, it does not support back actions and resets routes to their default state when switching away. This behavior aligns with our desired functionalit ...

The functionality of Flatbutton(Input handler) appears to be malfunctioning

I am having trouble with the file uploader from Material-UI. It doesn't seem to be working properly when I try to select a file. Does anyone have any suggestions on how to handle the input from the file selector? <FlatButton icon={< ...

What is the best way for me to bring in this function?

Currently, I am in the process of developing a point-of-sale (POS) system that needs to communicate with the kitchen. My challenge lies in importing the reducer into my express server. Despite multiple attempts, I have been unable to import it either as a ...

What steps do I need to follow to deploy my React application on GitHub?

After successfully creating my React project and pushing the full repository to GitHub through Visual Studio Code, I am now wondering how I can deploy my React project live on a server using the tools available on GitHub. Can anyone provide guidance on t ...

Is there a way to prevent my Header links from wrapping during window size testing?

https://i.stack.imgur.com/YTc3F.png The image above showcases my standard header layout, while the one below illustrates what occurs as I resize the window. https://i.stack.imgur.com/re44T.png Is there a specific CSS solution to prevent the Text navLink ...

Tips for incorporating dynamic content into React Material UI expansion panels while maintaining the ability to have only one tab active at a time

I'm working on a project using WebGL and React where I generate a list of users from mock data upon clicking. To display this content in an accordion format, I decided to use Material UI's expansion panel due to my positive past experience with ...

What strategies and techniques should be considered when creating websites optimized for mobile devices?

With a wealth of experience in programming languages like Java, Python, and C, I actively engage in self-study to enhance my skills. While I have dabbled in creating mobile-friendly websites, upon reviewing my work, it is evident that my frontend developme ...