ToggleButtonGroup in Material UI is a great way to create toggle

I am trying to implement the ToggleButtonGroup feature from Material UI in my React application. I am facing an issue where I am unable to pass values into my state correctly. The code snippet provided below shows that while the Select component works fine and can change the state's date, the ToggleButtonGroup does not. I want the ToggleButtonGroup to function similar to the Select component as it aligns better with my UI design. Can someone please point out where I might be going wrong?

state = {
    text: '',
    date: ''
}

handleChange = (event) => {
    this.setState({
        [event.target.name]: event.target.value
    })
}

handleSubmit = (event) => {
    event.preventDefault()

    // Do nothing if input field is empty.
    if (this.state.text === '') {
        return
    }

    // Submit the form.
    this.props.onSubmit({
        id: shortid.generate(),
        text: this.state.text,
        date: this.state.date,
        complete: false
    })

    // Clear input field after submission.
    this.setState({
        text: ''
    })
}
            <Select onChange={this.handleChange} name="date" id="date-select" variant="standard">
                <MenuItem value=""></MenuItem>
                <MenuItem value="today">Today</MenuItem>
                <MenuItem value="tomorrow">Tomorrow</MenuItem>
                <MenuItem value="week">This week</MenuItem>
            </Select>
            <ToggleButtonGroup onChange={this.handleChange} value="date" name="date" id="date-select" exclusive={true} size="small">
                <ToggleButton value="today">Today</ToggleButton>
                <ToggleButton value="tomorrow">Tomorrow</ToggleButton>
                <ToggleButton value="week">This week</ToggleButton>
            </ToggleButtonGroup>

Answer №1

When using the ToggleButtonGroup, the onChange callback expects two parameters: the event and the selected value, which can be customized as follows:

handleChange = (name, newValue /*Value of the selected button*/) => {
    console.log(newValue); //value of the selected button
    this.setState({
        [name]: newValue
    })
}

If the handleChange function is common for both Select and ToggleButtonGroup, it can be modified like this:

<Select onChange={(e) => this.handleChange("date", e.target.value)} ...

<ToggleButtonGroup onChange={(e, value) => this.handleChange("date", value)}..

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

Simple HTML files on a local server are having trouble loading images and JavaScript, yet the CSS is loading

Having worked in web design for quite some time, I recently began working on a basic Angular app that is meant to be very simple. For this project, I am only using the angular files and a single html file as the foundation. As I started setting up the bas ...

Notify user when Redux action is completes in ReactJS/Redux application

I've been working on a custom notification component that should display a message and then hide itself after a few seconds when certain redux actions, like login_fail, are triggered. However, I'm facing an issue where the message briefly pops up ...

Suggestions for creating a simple implementation of a 3 x 3 cell layout with a large center using flexbox are

Creating a grid layout like this 3 x 3 cell with large center using CSS Grid is quite straightforward. .container { display: grid; grid-template-columns: 60px 1fr 60px; grid-template-rows: 60px 1fr 60px; } But what if we wanted to achieve the same ...

The fixed table header is misaligned with the body columns' width

I was looking for a way to add a vertical scrollbar to my table, and I ended up wrapping the entire table in a div. The result was that the table head was fixed in position. Is there a simpler method to include a scrollbar in a table without affecting the ...

Create a stunning MUI App bar with a blurred effect below a fixed Navbar

Is there a method to apply a blur effect to the background of my material-ui AppBar component, creating a visually appealing overlay below the fixed navbar? I have experimented with using filter: blur(0) but it does not achieve the desired result. I am lo ...

I am interested in using a loop in Angular to highlight my div element

Enhancing my comprehension regarding the mentioned images. If I don't select anything within the div property, the default style (css) should appear like this, at least when one div is selected. However, the issue arises when unable to select. This ...

Is there a way to stack multiple Divs on top of each other using Float instead of relying on absolute positioning?

I've decided to revamp my approach and transition from using absolute positions to utilizing floats for positioning elements the way I desire. Now the challenge lies in figuring out how to float multiple divs on top of each other, allowing users to s ...

When using React, I noticed that the AuthContext does not update when I change the state

After creating a useState ( [logined,setLogined] ) in authContext and sharing it as a value, I noticed that even when I change the logined value in signout, my Navbar does not re-render. This led me to place useEffect in Navbar to check the logined state ...

CSS Padding Hover Transition solution for Eliminating Flickering Text issue

Is it possible to achieve this? I'm attempting to animate the padding around a centered text link. When the text link is clicked, the padding changes from 20% to 100%, which works correctly. The text is horizontally and vertically centered using CSS ...

Angular has the capability to rewrite URLs in CSS, providing a unique way

An issue arises in Angular when using a base set and html5mode with SVGs. This causes things like filter: url(#url) to be rewritten as filter: url(/base/#url). https://github.com/angular/angular.js/issues/8934 Disabling html5 mode and removing the base d ...

How can I change the background color of a selected row in material-table?

I am looking to achieve a similar behavior as demonstrated in this example using the material-table library: https://codesandbox.io/s/table-hover-colors-zw9nt If you are interested in learning more about the material-table library, you can visit these li ...

The hideCol method does not work on jqGrid

Encountering a problem with the hidecol method in jqGrid. Despite calling the method, nothing seems to happen. Using version 4.5 of jqGrid. The table is created as follows: // Table creation using jqGrid $('#shipTable').jqGrid({ data: tabl ...

What is the best way to merge an array of objects into a single object?

Is there a way to dynamically convert object1 into object2, considering that the keys like 'apple' and 'water' inside the objects are not static? const object1 = { apple:[ {a:''}, {b:'&apos ...

Ways to stop react-router from appending # to the URL?

How can I prevent the "#" from being added at the end of the URL as mentioned in the title? routes.jsx (export default (withHistory, onUpdate) => { const history = withHistory? (Modernizr.history ? browserHistory ...

Could anyone clarify the workings of the async function in this specific useEffect situation?

Within a child component, there is an onClick event: onClick={()=>{ //2. an image is clicked, and the choice is added to the choiceOrder state, and then a jsonupdate is called -- 3. in ChooseBy.js //onclick, add or remove the choice choosebyprop ...

What is the inner workings of CSS?

I'm curious about the inner workings of CSS. Does the HTML get interpreted before CSS, or vice versa? Or does it all apply as soon as the browser has constructed the DOM? I would appreciate a detailed explanation on this topic. ...

What is the option for receiving automatic suggestions while formatting components in a react.js file?

When styling elements in our app using app.css or styles.css, VS Code provides auto-suggestions. For example, if we type just "back" for background color, it will suggest completions. However, this feature does not work in react.js or index.js. Why is that ...

Tips for effectively handling state and props in more extensive React applications

Exploring the most effective methods for passing props between parent and child components in React has become paramount in navigating medium to large-scale projects. Establishing a standardized approach is crucial to mitigate confusion and technical backl ...

ReactJS and Docker-Compose issue: "Essential file not found"

My ReactJS application has been dockerized for development using Docker for Windows. The application is built into a docker image and runs on a container with the help of docker-compose tool. The package.json file below shows an outdated ReactJS scaffoldin ...

What is the best way to ensure that my multiple choice code in CSS & JS only allows for the selection of one option at a time? Currently, I am able

I'm currently facing a small issue that I believe has a simple solution. My knowledge of Javascript is limited, but I am eager to improve my skills in coding for more visually appealing websites. My problem lies in the code snippet below, where I am ...