Error in React Bootstrap: ReferenceError - 'openModal' is not defined

Whenever the button is clicked, my intention is for a modal to open. I have written the code for it, but I'm encountering errors that I can't seem to resolve. Here's the snippet of my code:

import React from "react";
import {
    Modal,
    Button,
    Card,
    CardHeader,
    CardBody,
    CardTitle,
    CardFooter,
    Table,
    Row,
    ButtonGroup,
    Col,
  } from "reactstrap";

  function Table() {
    state = {
      isOpen: false
    };
    openModal = () => this.setState({ isOpen: true });
    closeModal = () => this.setState({ isOpen: false });

  return (
      <>
        <div className="contentGroup">
          <Row>
            <Col md="12">
              <Card>
                    <CardHeader>
                    <ButtonGroup style={{float: 'right'}}>
                        <Button className="btn-round btn-icon" color="blue" onClick={this.openModal} style={{float: 'right'}}>
                            <i className="icon-plus-add"/>
                        </Button>
                    </ButtonGroup>
                   </CardHeader>
                       ...
             </Card>
             <Modal show={this.state.isOpen} onHide={this.closeModal}>
              <Modal.Header closeButton>
              <Modal.Title>Modal heading</Modal.Title>
              </Modal.Header>
              <Modal.Body>Modal text</Modal.Body>
              <Modal.Footer>
              <Button color="info" onClick={this.closeModal}>
                Close
              </Button>
              </Modal.Footer>
              </Modal>
          </Col>
        </Row>
     </div>
    </>
   );
  }

export default Table;

The console is displaying the following errors:

'state' is not defined       no-undef     
'openModal' is not defined   no-undef 
'closeModal' is not defined  no-undef

I am unsure why these errors are occurring. Any assistance would be greatly appreciated.

Answer №1

It is recommended to rename the component to CustomTable instead of using Table to prevent any naming conflicts with the imported Table from reactstrap.

Avoid using this keyword within functional components and consider implementing hooks in your code.

import React, { useState } from "react";
import {
    Modal,
    Button,
    Card,
    CardHeader,
    CardBody,
    CardTitle,
    CardFooter,
    Table,
    Row,
    ButtonGroup,
    Col,
  } from "reactstrap";

function CustomTable() {

  const [ isOpen , setIsOpen ] = useState(false);
    

  const openModal = () =>  setIsOpen(true);

  const closeModal = () => setIsOpen(false);

  return (
      <>
        <div className="contentGroup">
          <Row>
            <Col md="12">
              <Card>
                    <CardHeader>
                    <ButtonGroup style={{float: 'right'}}>
                        <Button className="btn-round btn-icon" color="blue" onClick={openModal} style={{float: 'right'}}>
                            <i className="icon-plus-add"/>
                        </Button>
                    </ButtonGroup>
                   </CardHeader>
                       ...
             </Card>
             <Modal show={isOpen} onHide={closeModal}>
              <Modal.Header closeButton>
              <Modal.Title>Modal heading</Modal.Title>
              </Modal.Header>
              <Modal.Body>Modal text</Modal.Body>
              <Modal.Footer>
              <Button color="info" onClick={closeModal}>
                Close
              </Button>
              </Modal.Footer>
              </Modal>
          </Col>
        </Row>
     </div>
    </>
   );
}

export default CustomTable;

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

Tips for resolving the error message "CORS policy blocking XMLHttpRequest access while trying to retrieve data from an API"

I've scoured through numerous similar questions without finding a solution that works for me. In the process of creating a React application, I'm attempting to retrieve data from my university's library API, which is in XML format. To conve ...

Create a cookie on a subdomain that is accessible by all other subdomains

I have been working on a NextJS project that involves multiple apps on separate subdomains. My objective is to enable single sign-on so that when I log in to one app, I am automatically signed in to all the others. We are utilizing nookies as our cookie ha ...

Retrieving server-side data in Next.js

As I dive into the world of Next.js coming from React, I've been able to make things work for the most part. However, when I tried creating a server component to test server-side fetching, I encountered some strange issues. Usually, when I start the ...

What steps can be taken to update the cart if all products have been removed?

How can I implement a refresh for my cart page every time the product length is 0 without causing unreachable code? It seems like there must be a simple solution to this problem. switch (action.type){ case "REMOVE_PRODUCT": return ...

Advantages of choosing between the <NextLink/> and the <Button href="/somePage"/> components in the powerful Mui React UI libraries

Currently engaged in a project, I am wondering if there exists a substantial disparity in the utilization of these two components. Prior to this change, the return button was implemented as follows: <NextLink href="/settings" ...

Error message encountered in NextJS: Prop type validation failed for the `href` prop in the `<Link>` component. It should be a `string` or an `object`, but it was found to be `undefined

I'm trying to implement a header layout in my project, but I encountered an error. The error message states: "Failed prop type: The prop href expects a string or object in <Link>, but got undefined instead. Open your browser's console to vi ...

Is there a way to code an automatic way to trigger the opening of a Material-UI Select field?

If you're looking for the select field, check it out in the Material-UI demo here Although its methods seem to be inherited from the menu/popover classes, I've been struggling to trigger the 'open' action when the onFocus event occurs. ...

How can you determine the class of an element that was clicked within an iframe?

Is it possible to retrieve the class of an element that is clicked within an iframe? Here is the HTML code: <input id="tag" type="text"> <iframe id="framer" src="SameDomainSamePort.html"></iframe> This is the JavaScript code: $(docum ...

Guide on transforming headless wordpress href to a <Link> tag

I am currently working on a project using Next.js with the WordPress API, also known as headless WordPress. In my application, I am displaying content from a Gutenberg area which includes text and links. However, a problem I have encountered is that the li ...

A guide to dynamically incorporating form fields in React.js

I am looking to dynamically add form fields. Additionally, I want the durationprice to be added dynamically on click, along with a button to dynamically add a full plan. { plan: [ { planname: "", description: "", cuisine: "", ...

Material-UI has officially deprecated the `css` function and is now recommending the use of the `styleFunctionSx` instead

I developed a component library called dot-components that is built on top of mui-org/material-ui. In another application utilizing my dot-components library, I have observed a console warning popping up during unit tests. Console Warning console.warn ...

The journey of data starting from a PHP file, moving through JavaScript, and circling back to PHP

I've encountered an interesting challenge with my PHP file and Wordpress shortcode. It all starts when the shortcode is embedded in a webpage, triggering a php function from within the file. This function executes an SQL query to extract data, then s ...

Import the complete JSON file into a variable as an array

I am struggling with loading an external json file (locations.json) into a variable and then using the information found here: http://www.json.org/js.html Despite trying various methods, I have not been successful in populating the variable. Even after fo ...

What is the best way to structure a nested object model in Angular?

Issue occurred when trying to assign the this.model.teamMembersDto.roleDto to teamMembersDto. The error message states that the property roleDto does not exist on type TeamMembersDropdownDto[], even though it is nested under teamMembersDto. If you look at ...

Dropdown search menus are failing to appear in the correct location

I have 4 dependent search dropdown menus side by side. There are two issues I am facing: Whenever I type in any of the drop-down menus, the MySQL-connected lists appear but not directly beneath the actual 'input-type-search-box'. Additional ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...

How can we avoid multiple taps on Ext.Button in Sencha Touch?

Currently working on a Sencha Touch game, but struggling with users tapping buttons multiple times. Looking for a simple solution to prevent multiple tap events in the app.js file so that only one tap event is executed even if a user taps or presses for an ...

Assigning a property to the Next.js response object

I recently discovered a fascinating concept involving setting an attribute on the response object within a Next.js API handler and being able to access that attribute in subsequent requests. This functionality took me by surprise as I couldn't find an ...

Enhancing the Aesthetics of Your Online Experience

I am attempting to format an input text using a react app. The goal is for this component to receive a text input from props, undergo the necessary "translator" functions, and display the translated code on the right side. I want the new text const newInpu ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...