What is the best way to include the "onChange" function in a component that does not natively support this prop?

After finding a useful code snippet on this page to switch languages, I attempted to enhance it by incorporating material UI components for better styling. However, whenever I change the language, it redirects me back to the home page because the MenuList component I'm utilizing does not support the onChange prop like the select element in the original code.

So, my question is: How can I implement the onChange functionality with this third-party component?

The unmodified code looks like this:

import React, { Component } from 'react'
import PropTypes from 'prop-types'

class Language extends Component {
  static contextTypes = {
    language: PropTypes.object,
  }

  state = {
    value: '',
  }

  componentDidMount() {
    const { language } = this.context
    this.setState({
      value: language.locale || language.detected,
    })
  }

  handleChange = event => {
    const { language } = this.context
    const { originalPath } = language
    const { value } = event.target

    if (value === this.state.value) {
      return
    }

    this.setState({ value }, () => {
      localStorage.setItem('language', value)
      window.location.href = `/${value}${originalPath}`
    })
  }

  render() {
    const { language } = this.context
    const { languages } = language
    const { value } = this.state

    if (!value) {
      return null
    }

    return (
      <select value={value} onChange={this.handleChange}>
        {languages.map(({ value, text }) => (
          <option key={value} value={value} >
            {text}
          </option>
        ))}
      </select>
    )
  }
}

export default Language

On the other hand, my modified version doesn't function properly due to the fact that MenuList doesn't support the onChange prop:

return (
  <MenuList value={value} onChange={this.handleChange}>
    {languages.map(({ value, text }) => (
      <MenuItem key={value} value={value} >
        <Link to={value}>
          {text}
        </Link>
      </MenuItem>
    ))}
  </MenuList>
)

To explore further and see the issue firsthand, you can check out the codesandbox. The crucial file here is src/component/language.js: https://codesandbox.io/s/mo75j2jxyx

Answer №1

When using MenuItem in your code, make sure to utilize the onClick prop for handling click events. Here's an example of how you can create a click event handler:

handleClick = event => {
    const { value } = event.currentTarget;
};

For more examples and information on implementing menus, you can check out this resource.

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

The functionality of State in react-native is not functioning as expected

I have an array that I am mapping like this: {activeNewsCategories.map((i) => ( <Tags key={i} tagName={i} getNewsByCategory={getNewsByCategory} /> ...

Eliminating redundant JSON records upon fetching fresh data

I have a list containing duplicate entries: var myList = [ { "id": 1, name:"John Doe", age:30 }, { "id": 2, name:"Jane Smith", age:25 }, { "id": 3, name:"John Doe", age:30 }, { &qu ...

Navigating advanced search through nuanced filters dynamically with AngularJS

Here you will find the advanced search form: https://i.stack.imgur.com/g7Hiz.png I have successfully created a URL and parameters for document sections, but I am struggling to come up with a solution for managing the "Add Property Restrictions" section w ...

The state variables of React components do not always retain their most recent value

Currently, I am working on implementing the functionality of an event based library called powerbi-client-react. The first step involves retrieving the component using getEmbeddedComponent and storing it in the variable report. Then, I need to utilize the ...

Ajax login feature not redirecting to login popup after successful login

When attempting to open a popup by clicking on the login window, a pop-up appears with a URL requesting username and password along with Google sign-in. However, when a user tries to log in using Google sign-in through the pop-up, it fails to redirect to ...

Currently, I am creating a regular expression to manage a specific task, but I have hit a roadblock in

Criteria: The string must not contain any uppercase letters. Special characters such as '^$.?*+()' are not allowed in the string. If the string includes '[', it must be followed by zero or more characters other than '[' and & ...

Passing state from a parent component to a child router component using React router-dom ends up displaying as undefined in the

Within the main component App.js, I am passing the user state to the child component Book: import React, { useEffect, useState } from "react"; import NavBar from "./components/NavBar"; import Signup from "./pages/Signup"; impo ...

Adding Material-UI icons dynamically in a React TypeScript project requires understanding the integration of imported icons

I have a collection of menu buttons with icons, stored in an array of objects. The icon names are saved as strings that correspond to Material UI icons: interface MenuButton { text: string, onClickFunction: Function icon: string } export defau ...

"Can you explain the process by which React grabs the props using the code `const props = this.props

I recently came across an interesting article authored by Dan. The example provided in the article caught my attention: class ProfilePage extends React.Component { showMessage = (user) => { alert('Followed ' + user); }; handleClick ...

Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below: { "params": { "time_to_diagnosis": [ { "field": "date_of_diagnosis", "value": "" }, { "field": "date_of_symptom_onset", "value": "2019-09-01" } ], "time ...

Display and conceal various elements in Vue.js using a data list

I'm a beginner in Vue.js, currently using Vue+Webpack. I am trying to make each link display data based on their respective ids when clicked, and match with the show attribute. I have created this functionality in a .vue file. export default { el ...

Node.js routing currently lacks the ability to easily verify the presence of a JWT token for every route

I have a node application where, upon routing to ('/login') with valid credentials, I generate a JWT token with an expiry time and direct the user to the next page. If the user tries to access any other route directly (e.g., '/home') af ...

Is it possible to modify the number format of an input field while in Antd's table-row-edit mode?

I am currently utilizing the Table Component of Ant Design v2.x and unfortunately, I cannot conduct an upgrade. My concern lies with the inconsistent formatting of numbers in row-edit mode. In Display mode, I have German formatting (which is desired), but ...

Is it possible to move between textboxes using arrow keys in HTML?

Is there a way to navigate through textboxes using arrow keys in HTML without relying on jQuery? Possibly utilizing JavaScript, HTML, CSS, or another method? Thank you for your help! <body> <form> <input type="text"&g ...

tips on retrieving the Vue element using a method in Vue.js

How can I dynamically add an element to the array by clicking a button in vue.js? Is it possible to call the method aggiungiViaggio on click, and how do I determine which viaggio I am currently in? Below is an example of the HTML: <div class=" ...

Jasmine tests for AngularJS directive failed to invoke the link function

I can't figure out why the link function of my directive isn't being called in a Jasmine test. I've created a simple example to illustrate. Here is the code for my directive (TestDirective.js): 'use strict'; angular.module(&ap ...

What are some solutions for resetting pagination icons to their default settings in material-table for React?

Hey there, I've been working on setting up a front-end display for a table using material-table in React. Everything has been going smoothly until I noticed some strange pagination icons instead of the usual arrows. Here's a screenshot for refere ...

Vue.js / Nginx / Node.js - Error 413: Payload Too Big

My frontend is built using Vue.js and is hosted on an nginx server in production. Here's a snippet of my nginx.conf configuration: server { listen 80; server_name localhost; root /usr/share ...

The Redux store has been modified, yet the changes are not reflected in the

In my Posts.js component, I am mapping every object in the posts array. Within this function, I attempt to filter all notes that have the same post_id as the id of the current mapped post object and store them in a variable called filteredNotes. I then pas ...

Leveraging promises with node.js and couched/nano for asynchronous operations

Currently experimenting with the Q promises library in conjunction with couchDB and Nano. The code below is able to display messages in the console, however, it seems that the database is not being created as expected. var nano = require('nano') ...