React's Material-UI AppBar is failing to register click events

I'm experimenting with React, incorporating the AppBar and Drawer components from v0 Material-UI as functional components. I've defined the handleDrawerClick function within the class and passed it as a prop to be used as a click event in the functional component. However, I am facing an issue where passing the function as a prop might not be working as expected. If there's an alternative method to achieve the desired functionality on click, I would greatly appreciate any assistance. It's important that we utilize the fancy components within the functional components while rendering them in the class, just like demonstrated in the Demo. The functionality of opening and closing the drawer should be controlled by the onLeftIconButtonClick.

I have provided a functioning demo on StackBlitz here => Working Demo

Below is the code:

import React, { Component } from 'react';
import { render } from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import './style.css';

export const getMenuBar = (isBarOpened) => {
  return(
    <Drawer open={isBarOpened}>
      <MenuItem>Menu Item</MenuItem>
      <MenuItem>Menu Item 2</MenuItem>
    </Drawer>
  );
}

export const getAppBar = (handleDrawerClick) => {
  return(
    <AppBar 
      title="My AppBar" 
      className="st_appBarClass" 
      titleStyle={{ color: "#FFFFFF" }}
      onLeftIconButtonClick={handleDrawerClick()}
    />
  );
}

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      isMenuOpened: false
    };
  }

  handleDrawerClick = (e) => {
    console.log(e);
    if(e) {
      this.setState({ isMenuOpened: !this.state.isMenuOpened });
    }
  }

  render() {
    return (
      <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
        <div className='product-list-wrapper'>
          {/*<ProductList products={products} />*/}
          {getAppBar(this.handleDrawerClick)}
          {getMenuBar(this.state.isMenuOpened)}
        </div>
      </MuiThemeProvider>
    )
  }
}

render(<App />, document.getElementById('root'));

Answer №1

const generateAppBar = (toggleDrawer) => {
  return(
    <AppBar 
      title="Custom AppBar" 
      className="appBarStyle" 
      titleStyle={{ color: "#000000" }}
      onLeftIconButtonClick={toggleDrawer} //Exclude ()
    />
  );
}

Answer №2

To show the menu remove any unnecessary parentheses

<AppBar 
      title="My AppBar" 
      className="st_appBarClass" 
      titleStyle={{ color: "#FFFFFF" }}
      onLeftIconButtonClick={handleDrawerClick}//<---here
    />

To hide the menu add an onClick function to the parent div

<div onClick={this.handleDrawerClick} className='product-list-wrapper'> //<----here
          {/*<ProductList products={products} />*/}
          {getAppBar(this.handleDrawerClick)}
          {getMenuBar(this.state.isMenuOpened)}
        </div>

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

Navigating through different components in Angular without using templates

Searching for a straightforward solution using Angular to manage routes. I have a webpage generated by the server featuring a basic Google map and some logic spread across three separate controllers. Now, I aim to integrate routing into this setup. Nothi ...

Triggering Submit Button Based on Checkbox Value in jQuery

Hey there, I'm encountering an issue. Let's say I have two types of checkboxes - one for person and one for company. If I submit the form without checking any of the person or company checkboxes, I want jQuery to display an alert. Otherwise, the ...

The AngularJS framework is not effectively generating the desired table structure

EDIT 1 - Here is a Plnkr example that demonstrates the issue - http://plnkr.co/edit/qQn2K3JtSNoPXs9vI7CK?p=preview ---------------- ORIGINAL CODE AND PROBLEM ---------------- I've been using the angular datatable library (angular-datatables) to g ...

Determine the dimensions of Expo's React Native Over the Air (OTA) update

Is there a method to determine the size of the required download for an OTA update before existing deployed apps (e.g. v1) retrieve it following the publication of a new managed Expo app (e.g. v2)? ...

What is the best method for eliminating tags from an HTML tag attribute using PHP?

I have a substantial amount of posts created using an old CMS. The content is in HTML markup, but unfortunately it's quite messy. It includes constructs like: ....<IMG alt="Хит сезона - <b>Лучшие фразы...</b>" src=" ...

On paste events, CKEditor will strip away all HTML tags except for div and span elements

I am trying to implement a feature in CKeditor where all HTML tags are removed when a user pastes content using Ctrl+v. The code I have written so far does not seem to work as expected. <script type="text/javascript"> CKEDITOR.on('instanceR ...

Navigating through choices in select element using webdriverio

Sample HTML: <select id="random_text"> <option value="option1">asadka_TEST</option> <option value="option2">Peter Parker</option> <option value="option3">Clark Kent</option> <option value="optio ...

Design all buttons, except for the two specific buttons

.button , button{ border:solid black 2px !important; } Using this code, I have added a border to all buttons. But now, I need to exclude the buttons "searchsubmit" and "single_add_to_cart_button" from having a border. How can I achieve that? ...

sorting in React table not functioning properly for computed column

I have a column titled 'EV/Resource ($ per oz)' that appears to not sort correctly in my react table. Instead of sorting in ascending or descending order, it randomizes the table sort. I'm unsure if I am handling this as a "calculated column ...

Determine whether there is text present on a webpage using JavaScript

I am familiar with Python coding from selenium import webdriver driver = webdriver.Chrome() driver.get('http://WEBSITE') assert 'TEXT' in driver.page_source However, I now require the equivalent JavaScript code. ...

ng-include does not incorporate a partial view

I am facing an issue with ng-include as this code is not functioning properly and I'm unable to identify the error. <select name="select" id="select" class='input-large' ng-model="selectedbien"> ...

View content from a text file on a webpage

Hi everyone, I could really use some assistance with a project I'm currently working on. As someone who is new to programming, I am facing a challenge. My goal is to showcase the contents of a plain text file on a webpage. This text file, titled titl ...

`The issue arises when attempting to send an email using nodemailer`

I've encountered an issue while trying to send emails through a React website or Postman. The website displays an error message "Cannot POST /contact". Below is the content of my index.js file: const express = require('express') const app = ...

Running compiler-produced assembler code within the program

Recently, I came across an interesting presentation discussing inline ASM generation in Javascript optimization. The presentation can be found at the following link: . In another paper located here: https://sites.google.com/site/juliangamble/Home/Compiler ...

Validation of Single Fields in Angular Reactive Forms

When I validate a reactive form in Angular, I expect the error message to show up beneath the invalid field whenever incorrect data is entered. <form (ngSubmit)=sendQuery() [formGroup]="form"> <div *ngFor='let key of modelKeys&ap ...

Is it possible to drag the div container in HTML to resize its width from both left to right and right to left?

After posing my initial inquiry, I have devised a resizing function that allows for the expansion of a div's width. When pulling the right edge of the div to resize its width from left to right, is it possible to adjust the direction or how to resize ...

Guide on extracting the ID within a for loop and incorporating it into a Vue.js function

In order to make an API request, I need to retrieve the id. However, whenever I try to include <a v-on:click="showRecipe({{inf.Id}})">Recipe</a> in my code, the entire page crashes. Removing this line resolves the issue. How can I pass the id ...

Retrieve Checkbox within a Span using Jquery

Trying to achieve the selection of a checkbox when a user clicks on a div using jQuery. The provided fiddle shows my attempt: http://jsfiddle.net/5PpsJ/ The code snippet I have written so far is as follows, but it doesn't seem to select the checkbox ...

Having trouble with my sorting algorithm - am I overlooking something obvious?

function Controller($scope) { var sortItems = [ { "text": "Second", "a": 2 }, { "text": "Fifth", "a": 5 }, { "text": "First", "a": 1 }, { "text": "Fourth", "a": 4 }, { "text": "Third", "a": 3 } ]; va ...

Tips for preventing multiple counter buttons from conflicting with one another

Currently, I am in the process of creating an online restaurant platform that allows customers to place food orders. To streamline this process, I am developing individual cards for each food item available on the menu. In addition, I am implementing butto ...