Insert the user's choice as a MenuItem within the Select component

I currently have a default list of options for the user. However, I want to allow users to add their own category dynamically. This will trigger a dialog box to appear. How can I modify my code so that the value property starts from number 4? Take a look at what I've implemented below:

class Registration extends React.PureComponent {
  constructor() {
    super();
    this.state = {
      open: false,
      type: '',
      platform: [],
    };

  }


  handleOpen = (type) => this.setState({ open:true, type });
  handleClose = () => this.setState({ open:false });

  addPlatform = (event) => this.setState({ platform: event.target.value});

  render() {
    const { type, platform} = this.state;
    const actions = [
      <FlatButton
        label="Cancel"
        primary
        onTouchTap={this.handleClose}
      />,
      <FlatButton
        label="Submit"
        primary
        onTouchTap={this.handleClose}
      />,
    ];
    return (
      <div className="registration">
        <Card>
          <Dialog
              title={`Add ${type}`}
              actions={actions}
              modal={false}
              open={this.state.open}
              onRequestClose={this.handleClose}
              >
              {type === 'category' ?
              <TextField
                type="text"
                hintText="Category Name"
                onChange={this.addCategory}
              /> :
              <TextField
                type="text"
                hintText="Platform Name"
                onChange={this.addPlatform}
              />
            }
          </Dialog>
          <SelectField
            value={this.state.valueOfCategory}
            onChange={this.handleCategoryChange}
            hintText="Category"
          >
            <MenuItem value={1} primaryText="Food" />
            <MenuItem value={2} primaryText="Travel" />
            <MenuItem value={3} primaryText="Communication" />
          </SelectField>
          <FloatingActionButton onTouchTap={() => this.handleOpen('category')}><ContentAdd /></FloatingActionButton>
          <RaisedButton label="Done" onClick={this.onSubmit} />
        </Card>
      </div>
    );
  }
}

export default Registration;

Answer №1

class UserRegistration extends React.Component {
  constructor() {
    super();
    this.state = {
      open: false,
      type: '',
      interests: ["Food", "Travel", "Communication"],
    };

  }


  handleOpenModal = (type) => this.setState({ open:true, type });
  handleCloseModal = () => this.setState({ open:false });

  addInterest = (event) => this.setState({ interests: [...this.state.interests, event.target.value]});

  render() {
    const { type, interests} = this.state;
    const actions = [
      <FlatButton
        label="Cancel"
        primary
        onTouchTap={this.handleCloseModal}
      />,
      <FlatButton
        label="Submit"
        primary
        onTouchTap={this.handleCloseModal}
      />,
    ];
    return (
      <div className="user-registration">
        <Card>
          <Dialog
              title={`Add ${type}`}
              actions={actions}
              modal={false}
              open={this.state.open}
              onRequestClose={this.handleCloseModal}
              >
              {type === 'category' ?
              <TextField
                type="text"
                hintText="Category Name"
                onChange={this.addCategory}
              /> :
              <TextField
                type="text"
                hintText="Interest Name"
                onChange={this.addInterest}
              />
            }
          </Dialog>
          <SelectField
            value={this.state.valueOfCategory}
            onChange={this.handleCategoryChange}
            hintText="Category"
          >

            {
              interests.map((item, index) => <MenuItem value={index+1} primaryText={item} />)
            }

          </SelectField>
          <FloatingActionButton onTouchTap={() => this.handleOpenModal('category')}><ContentAdd /></FloatingActionButton>
          <RaisedButton label="Done" onClick={this.onSubmit} />
        </Card>
      </div>
    );
  }
}

export default UserRegistration;

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

Error in ReactJS: Trying to access a property called 'maps' of an undefined value causing a TypeError with Google Map integration

While attempting to include the GeoCoder API code, I encountered an error stating "TypeError: Cannot read property 'maps' of undefined". This is the code snippet: import React from 'react'; import { compose, withProps,withHandlers } f ...

Guide: Passing and reading command line arguments in React JavaScript using npm

When launching the react application, I utilize npm start which is defined in package.json as "start": "react-scripts start -o". Within the JavaScript code, I currently have: const backendUrl = 'hardCodedUrl'; My intention ...

Development of Chrome Extensions, JavaScript dilemma

Hey there, I'm new to JavaScript and I've been diving into the world of creating Chrome extensions. I'm trying to set up a content script and browser action, but I'm struggling to get it up and running. I know I'm probably making a ...

Is it possible to modify the navbar background color in React.js by using the 'props.location.pathname'?

I am looking to adjust the navigation bar color based on the page. On the homepage, I want the background color to be rgba(255, 255, 255, .0), and white on all other pages. const currentPage = props.location.pathname const classes = useStyles() useEffe ...

Guide for using express.js

Similar to how you can use to view the source code of all classes in Java, is there a resource available to view the source code of the express module? ...

What is the best way to trigger an event in VueJS?

I recently implemented a table using Vuetify in my project. The table is now split into two components - the Table component and the Row component. My challenge is how to handle the same function, this.selected = !this.selected!, when dealing with 2 differ ...

What is the best way to incorporate bullet points into a textarea?

How can I make a bullet point appear when pressing the 'enter' button inside a textarea? I tried using this code, but it doesn't seem to work. Any suggestions? <script> $(".todolist").focus(function() { if(document.getElementById( ...

Convert JSON response date format to a format specified by the user

The following code snippet is currently returning the dates for $("#dob") and $("#anniversery") as 2014-04-01T00:00:00 This is my current code: <script> $(function() { function log(message) { $("<div>").text(message).p ...

Managing React state fields utilizing an array of objects

I am struggling to integrate this with my React state. The current setup is functional and allows me to access the necessary data, but I aim to enhance the 'questions' field so that it becomes an array of objects instead of a single object. this. ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Tips for altering the browser tab color on a PC or Mac with HTML or JavaScript

While I am aware of the method to change theme colors on mobile devices using <meta name="theme-color" content=" #0000ffbb" />, I prefer browsing on my laptop. Are there ways to customize browser tab appearance using HTML or JS fo ...

Guide on routing error 500 globally to a specific page with React-Redux

Currently, I am utilizing the react-redux starter found at this link. I am seeking guidance on how to redirect all API 500 errors to a specific page. Can someone assist me with this? ...

What is the best way to replicate the Ctrl+A action on an element using jQuery or JavaScript?

Is there a way to trigger the Ctrl+A key combination in a textarea element when a specific event occurs, without resorting to caret positioning or selecting all text separately? I'm looking for a method that simulates hitting Ctrl+A using a cross-brow ...

Issue with VueJS 2 and TypeScript: computed value unable to recognize property specified in data object

When creating the following component: <template lang="html"> <div> <p>{{ bar }}</p> </div> </template> <script lang="ts"> import Vue from 'vue'; export const FooBar = Vue.ex ...

Tips for ensuring that a nested object in an array contains only a single object

My array is structured like this: [ { object1:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object2:{ childObj1:[grandChild1,grandChild2], childObj1, childObj1} }, { object3:{ childObj1:[grandChild1,grandChild2 ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

using reactjs to dynamically render elements based on the selected condition in a select box

Is there a way to dynamically change an element based on the selected value of a dropdown in React? I'm looking for help with rendering conditions. Here's a snippet of my code: <Col span={12}> <Form.Item label='Qu ...

Display words on screen and then alter hue using HTML and CSS

Is there a way to dynamically change the color of text inside <a> tags from black to red after a specific time interval and keep it permanently red? do { document.getElementById("code").innerHTML +="<a>Hello World</a><br>"; awa ...

React - Utilizing Secondary Prop Value in Material UI Node Components

I've been working on streamlining my code and am wondering about the best way to pass an additional value using props while fetching data from the backend. I'm utilizing material UI's Autocomplete with the PERN stack. Everything is functioni ...

A guide on sending multiple input values using the same class name or id through ajax

My goal is to send multiple input values through AJAX to my PHP script. Everything works smoothly when I use getElementById. However, I have the functionality to add a child. The issue arises when it only retrieves values from the first child while iterati ...