Assign a value using the select component from Material UI

I just finished creating a dropdown menu

  const [selectedValue, setSelectedValue] = useState('');

  const handleSelectionChange = (e: any) => {
    //setSelectedValue(e)
    console.log('value', selectedValue)

  }
....
  
  <FormControl variant="filled">
            <InputLabel id="demo-simple-select-filled-label" className={classes.field}>Options</InputLabel>
            <Select
              labelId="demo-simple-select-filled-label"
              id="demo-simple-select-filled"
              value={selectedValue}
              onChange={(e)=>handleSelectionChange(e)}
            >
              <MenuItem value="random">
                Random
              </MenuItem>
              <MenuItem value='timeEnd'>Time End</MenuItem>
              <MenuItem value='slidingWindow'>Sliding Window</MenuItem>
            </Select>
          </FormControl>

Now, I need help saving the chosen item's value in the selectedValue variable. How can I do this without encountering the following error message?:

react-dom.development.js:13231 Uncaught Error: Objects are not valid as a React child

Answer №1

To retrieve the value, make sure to access e.target.value

import React, { useState } from "react";
import { FormControl, InputLabel, Select, MenuItem } from "@material-ui/core";
const App = () => {
  const [selectedMethod, setSelectedMethod] = useState("");

  const handleSelectionChange = (
    e: React.ChangeEvent<{
      name?: string | undefined;
      value: unknown;
    }>
  ) => {
    // Ensure type checking
    const value = typeof e.target.value === "string" ? e.target.value : "";

    setSelectedMethod(value);
  };
  return (
    <FormControl variant="filled" style={{ width: "100%" }}>
      <InputLabel
        id="demo-simple-select-filled-label"
        style={{ width: "100%" }}
      >
        Choose Method
      </InputLabel>
      <Select
        labelId="demo-simple-select-filled-label"
        id="demo-simple-select-filled"
        value={selectedMethod}
        onChange={handleSelectionChange}
      >
        <MenuItem value="random">Random</MenuItem>
        <MenuItem value={"timeEnd"}>Time End</MenuItem>
        <MenuItem value={"slidingWindow"}>Sliding Window</MenuItem>
      </Select>
    </FormControl>
  );
};

export default App;

Check out the live demo:

https://codesandbox.io/s/infallible-buck-oen5r?fontsize=14&hidenavigation=1&theme=dark

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

Retrieve the current state of the toggle component by extracting its value from the HTML

I have a unique component that consists of a special switch and several other elements: <mat-slide-toggle (change)="toggle($event)" [checked]="false" attX="test"> ... </mat-slide-toggle> <p> ... </p> F ...

Sending an array to another file upon button click event in a React application

Hey everyone, I'm currently getting started with React. I have this interesting situation where I need to handle an array of IDs that are obtained from selected checkboxes. My goal is to pass this array to another file called Employee.js when a button ...

What is the best way to flatten object literal properties?

I have received an object from a legacy server that I need to restructure on the client-side using JavaScript, jQuery, or Underscore.js. Here is the original structure of the object: [ { "Id":{ "LValue":1, "Value":1 }, ...

Maximizing Particle Performance Using JavaScript

I am experimenting with creating particles in JavaScript for the first time, and I'm unsure if the code below is optimized. When I generate 100 particles on the screen, there isn't much of an FPS drop noticeable. However, when multiple clicks o ...

sending an array from one CodeIgniter view to another view via Ajax

In the following code segments of my application, myArray is an array where each element contains a few objects that I need to use in a second view. When I use alert(myJSON);, I am able to see the array in the alert window. However, when the view loads, i ...

I'm wondering why Jest is taking 10 seconds to run just two simple TypeScript tests. How can I figure out the cause of this sluggish performance?

I've been experimenting with Jest to execute some TypeScript tests, but I've noticed that it's running quite slow. It takes around 10 seconds to complete the following tests: import "jest" test("good", () => { expec ...

Retrieving a PHP script from within a DIV element

I am seeking assistance to successfully load a PHP file from a DIV call. Below is the code I have used: <html> <head> </head> <body> <script class="code" type="text/javascript"> $("#LoadPHP").load("fb_marketing ...

Is there a method in JavaScript to access the object to which a function was originally bound?

I have a curiosity about making the code below function properly, capturing the logging as instructed in the comments. function somePeculiar(func) { var funcThis = undefined; // Instead of undefined, how can we access // ...

Inconsistent updates of LocalStorage triggered by setInterval commands

Having trouble with inconsistent updates in local storage after refreshing a user's auth tokens? Sometimes the local storage updates properly and the app functions well, but other times the token and admin/student fields are unexpectedly deleted despi ...

What is the standard way to write the server-side code for HTTP request and response handling?

I stumbled upon these resources: How to send HTTP request GET/POST in Java and How to SEND HTTP request in JAVA While I understand the client-side aspect, how can this implementation be done on the server side? The goal is to utilize the link on the clie ...

Trouble accessing setState within an axios call in ReactJs

I've encountered an issue while attempting to set the state of the variable isCorrectAnswer within an axios call. The error message Cannot read properties of undefined (reading 'setState') is showing up in the console log. What mistake am I ...

encountering an issue following the initial setup using create-next-app

After searching on Stack Overflow and finding no answers, I am posting this question again. When I create a new project in Next.js using npx create-next-app project-name --ts and run npm run dev without making any changes to the source code, I encounter t ...

How can you create a type in Typescript that is composed of a specific property taken from another type?

I'm still in the process of understanding typed languages, but imagine I have the following scenario: export interface Person { id: number; name: string; } const persons: Array<Person> = [ { id: 1, name: 'foo', }, { ...

The preflight request in Angular2 is being rejected due to failing the access control check: The requested resource does not have the 'Access-Control-Allow-Origin' header

I encountered an issue while attempting to execute a basic POST request to establish an account using an API in .NET. The process fails with the mentioned warning title. Interestingly, performing the same request in Postman (an API testing tool) yields a s ...

Utilize the Material UI Grid component to extend the content of the second column all the way

Currently, I am utilizing the Grid component from material UI and specifically using the auto property for the initial column. Here is my setup: <Grid container className={classes.borderclass}> <Grid item xs={"auto"}> <Items /> ...

The Battle of node.js Modules: Comparing socket.io and express.static

The server.js file I am currently running is set up as follows: module.exports = server; var express = require('express'); var fs = require('fs'); var server = express.createServer(); var port = 58000; server.listen(port); var ...

The Art of Validating Forms in Vue.js

Currently I am in the process of developing a form with validation using Vue, however, I've run into some errors that are showing up as not defined even though they are currently defined. HTML <form class="add-comment custom-form" @submit="checkF ...

There's just something really irritating me about that Facebook Timer feature

Have you ever noticed the timers constantly updating on Facebook? Whether it's an Ajax Request triggered by a timer or a client-side timer, there are numerous timers being used. Does this affect the performance of the website, and is there something c ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...