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

Trouble displaying JSX fragment content on the screen

[postslug].js import {PostData} from '../../data/postdata' export async function getStaticProps({ params }) { const posts = PostData.find((p) => p.slug === params.postslug); return { props: { post: posts, }, }; } ...

Tips on altering the quantity of columns in a ul list dynamically

I'm trying to create a list with 2 columns, and I want it to switch to 3 columns when the browser window is wide enough (for example, on a 23 inch monitor). Can this be achieved using CSS or any other method? Here is my current CSS: .search-results ...

JavaScript Animation of Text

I have a challenge where I want to animate text's opacity in JavaScript after the user presses enter. However, I am struggling to achieve this with my current code. I can provide all of my code for you to review and help me understand why the animatio ...

The onChange event for React select is being triggered twice, incorrectly using the old value the second time

I am currently implementing React Select to display a list of items. When an item is changed, I need to show a warning based on a specific flag. If the flag is true, a dialog box will be shown and upon confirmation, the change should be allowed. After each ...

Issue with horizontal scrolling functionality in DataTables

I have a table with over 10 columns, and I am using datatables to display the data. I have enabled horizontal scrolling due to the large number of columns, but the scroll is not appearing. Can someone please assist me with this issue? Here is a screenshot ...

the JavaScript anchor feature is malfunctioning

Steps to Play Back: To start, in the header section, select any of the links with anchors: ##bankaccount #pack #platform #acq ##scorecard ##intrade #form Next, scroll up to the top of the page Then, reload the page Actual Outcome: Upon reloading a page w ...

Tips for managing the mui-autocomplete popup/component

Seeking advice on how to programmatically control the visibility of the mui-autocomplete item list. Is there a way to determine if it is currently "open" or closed? The mui-autocomplete component provides an "open" property that, when set to true, display ...

The issue of CSS3 Grid-gap not functioning properly on iPhone devices

I've been working on creating a CSS template and everything seems to be functioning correctly, except for the grid gap which doesn't seem to work properly on my iPhone. Here's the code I have so far: <div class="grid"> <h1 ...

What is the best way to constrain the ratio of a full-width image display?

I am in need of a solution for displaying an image at full width inside a frame with a 16:9 aspect ratio. The image needs to be centered within the frame and adjust responsively when resizing the screen. My preference is to achieve this using just CSS. ...

The Unique Font That Mysteriously Blocks Fake Italic Styles on Webkit Browsers

Currently, I am utilizing the PT Sans Narrow font in my project, which unfortunately only offers regular and bold styles. As a result, I require the browser to apply faux italics when needed. Strangely, this functionality is only working on non-webkit brow ...

Encountering a glitch while trying to set up a new React application with

Whenever I try to execute "yarn create react-app app", the following error message pops up: The error appears to be caused by the presence of spaces in my system username. How can I run this command without having to modify my system username? success In ...

Resizing anchor element using CSS

Hey there, I'm having trouble scaling my anchor tag when hovering over it. Here's the code I'm using: a { color: red; text-decoration: none; transition: all 0.5s; } a:hover { ...

Upgrading from Vuetify 2 to 3 involves replacing the deprecated styles like .v-application, rounded, and flat with

I need help with upgrading from Vuetify/Vue 2 to Vue 3. I don't have much experience in front-end development, but I am responsible for updating some old code to keep things running smoothly. The migration guide is not very clear and assumes a certain ...

What strategies can I employ to address this historical issue?

Encountered TypeError: (0 , history_history__WEBPACK_IMPORTED_MODULE_6_.default) is not a function This issue arises in my history.js file import { createBrowserHistory } from 'history'; export default createBrowserHistory({ forceRefresh: tr ...

React Router: Dispatch not triggering when route changes

I have multiple paths that share the same controller: <Route component={Search} path='/accommodation(/:state)(/:region)(/:area)' /> and when the route changes, I trigger the api function within the component: componentWillReceiveProps = ...

The requested URL /api/users/register does not exist. Error 404

While creating a money manager application utilizing the MERN Stack, I encountered an issue with posting data to the database. Whenever I click on the register button, an error is thrown stating that it Cannot POST /api/users/register. Despite setting up a ...

Can anyone help me with fixing the error message 'Cannot assign to read-only property 'exports' of the object' in React?

Recently, I decided to delve into the world of React and started building a simple app from scratch. However, I have run into an issue that is throwing the following error: Uncaught TypeError: Cannot assign to read-only property 'exports' of o ...

The necessity for unique "key" props for every child in a list is generating an error within the custom component

When mapping over an array to render a custom card component for each index, I encountered an error stating "Each child in a list should have a unique key prop." Despite passing the index as the key and trying various methods like using React.Fragment or ...

Implementing next-i18next in Components

I followed all the instructions in the documentation without success. Why isn't the code below functioning properly? With NextJs, it seems that Server-Side Rendering (SSR) is only supported for pages in the pages folder. For instance, how can I imple ...

What could be the reason for receiving a Firebase INVALID_DYNAMIC_LINK_DOMAIN error message?

I'm having trouble implementing email verification in my React website. Whenever I use the sendSignInLinkToEmail function, I encounter the following error: XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=xxxxxxxxxxxxxxxxxxx [ ...