Struggling with passing values to onClickHandler because of MUI

I'm looking to create a category navigation menu that includes icons and labels. I attempted to do this using Chips:

                 {categories.map((category) => (
                    <Chip
                        key={category._id}
                        avatar={<Avatar alt={category.name} src={category.icon} />}
                        label={category.name}
                        variant="outlined"
                        onClick={(e) => handleClick(e)}
                        value={category._id}
                    />
                ))}

I also tried using Tabs -> Tab components, but ran into issues with the "value" attribute not being produced when clicked.

const handleClick = (e) => {

    const valueTargeting= e.target.value;
    console.log(valueTargeting);
};

Is there a solution to make either of these methods work, or should I consider designing a custom button instead? Additionally, I noticed that they do output a "value" when clicked in a specific small area. Could this be a bug on my part?

Answer №1

Chip is not giving the expected result because it doesn't explicitly hold a value. To make it return a value to your event handler, you must enclose the desired value within the onClick function itself. Here's an example:

{categories.map((category) => {
  return (
    <Chip
      label={category.name}
      // Note that 'category._id' is being passed from the handler instead of `e`
      onClick={handleClick(category._id})}
    />
  );
})}

Code Sandbox for MUI 4: https://codesandbox.io/s/chip-click-mui4-ggl0z?file=/demo.js:940-1325

Code Sandbox for MUI 5: https://codesandbox.io/s/chip-click-mui5-y5xkk?file=/demo.js

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

React-Query leads to variable becoming undefined upon component update

I'm currently utilizing dnd-beautiful-kit to organize Cards on my platform. Each Card contains specific information, as shown in the video, along with an Avatar component. The Avatar can either display the user's image (if avatarSource exists) or ...

ReactJS: Error in syntax detected in src/App.js at line 16, column 6. This token is unexpected

Just starting out with reactjs and encountered a simple example in a tutorial. Ran into a syntax error when trying to return html tags. Below is the error that popped up: ./src/App.js Syntax error: C:/Users/react-tutotial/src/App.js: Unexpected token ...

Top and bottom labels with a line for navigating through steps - Material UI Stepper

I have been working on creating a stepper using Material UI (V5). Here is the code I currently have: import * as React from 'react'; import Box from '@mui/material/Box'; import Stepper from '@mui/material/Stepper'; import Step ...

The absence of the 'Access-Control-Allow-Origin' header is reported even though it is actually present

I have been attempting to send a POST request from one website to my own site. Despite allowing CORS access explicitly, every time I try to make the actual POST request, I am faced with the No 'Access-Control-Allow-Origin' header is present on th ...

Please be patient until setInterval() completes its task

In order to add a dice-rolling effect to my Javascript code, I am considering using the setInterval() method. To test this out, I have come up with the following code: function rollDice() { var i = Math.floor((Math.random() * 25) + 5); var j = i; ...

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...

vue.js and the various elements that make up its architecture

My component content is not appearing!!! I have checked the router multiple times and it seems to be functioning correctly, but when I run the project, the components are empty. Even though I have added a lot of content to them, they appear to be blank. ...

Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :) I am trying to convert the object into an array with the following expected result: result = [ { id: 'test-1', message: 'test#1.1' }, { id: 'test-1', mess ...

When trying to append in jQuery, the error "JQuery V[g].exec is not a

Attempting to create a script that adds a table to a div within the website using the following function: function generateTable(container, data) { var table = $("<table/>"); $.each(data, function (rowIndex, r) { var row = $("<tr/>"); ...

The localhost is not updating on subsequent runs of npm run dev after the initial run

Every time I launch npm run dev (for my nextjs application), it functions properly on the initial run. However, after making modifications to my files, saving them, and checking my localhost, the changes do not appear. What is the solution? Currently, I f ...

Using JQuery's .mouseover and .mouseout methods to modify font colors on a webpage

Hi there, I'm new to JQuery and trying to experiment with some basic functionalities. I have a simple navigation menu created using an unordered list, and I want to change the font color of the currently hovered list item using JQuery. However, I&apos ...

Using recursion in JavaScript to determine if a given number is prime

I am feeling a bit puzzled about how to tackle this issue. My goal is to have all prime numbers return as true, and if not, then false. I noticed that my current logic includes 2, which returns 0 and automatically results in false because 2 has a remainder ...

Is there a way to choose the final JSON element using Javascript or Google Apps Script?

Imagine if I extracted this data from a constantly updating JSON file. [{ "data": { "member": "Feufoe, Robert", "project": "Random Event", }, "folder": null, "id": 1062110, "spam": null }, { "data": { "membe ...

What is the best way to style MUI's Button component with a link to appear like a standard button?

I have a Button that allows users to download a file with a specific filename. Here is the code I used: <Button color='primary' href=`/apiproxy/objects/${id}/subobjects` LinkComponent={React.forwardRef((props, ref) => <Link {...pro ...

Styling the file input type in AngularLearn how to customize the

I've come across numerous queries on how to style an input type file, but I'm struggling to implement it in an angular context. So, what is the best way to customize the appearance of an input type file within an angular application? Below is t ...

Make sure to switch up the font color with each new use of the "append" function

Currently, on my page, I am using the append function to add a new line of text (".newText") every 5 seconds. This is my current implementation: var fontColors var randomColor $(function(){ fontColors = ['red','orange','yello ...

CORS policy blocked: A missing 'Access-Control-Allow-Origin' header is causing errors on the requested resource

When I developed my E-commerce MERN app, it worked perfectly on http://localhost:****. However, when I deployed the backend as HTTPS, the GET method was functioning correctly but the POST method was not. An error message stating "blocked by CORS policy" ap ...

What is the best way to retrieve an object instead of an array?

When attempting to retrieve a JSON Object, I unexpectedly received an array instead. My query is based on the primary key, so I anticipate only one result. This is my current method : router.get("/student_info/:id", (req, res, next) => { connecti ...

Is the background element rather than its input being focused upon when clicking in the link tool's dialog within ContentTools?

I am utilizing ContentTools within a Bootstrap modal. The issue I am facing is that when I select text and click the hyperlink tool, the link dialog pops up but immediately focuses on an element in the background (such as the modal close button). This prev ...

Tips for showcasing JavaScript variables on a webpage

I am working with various JavaScript variables that involve displaying values inside div elements. goalDiv = "<div class=goal-parent id=goal-parent"+Id+">"+ "<div class=goal>"+ "<div class=top-layer>"+ "<div class=compone ...