Steps to Implement Dropdown with Multiple Selection in ReactJS

Recently, I've started exploring React and now I'm eager to create a customized select component similar to the one shown in this image: https://i.sstatic.net/D2IDC.png

I've successfully created a basic select element like this:

<select >
  <option value="volvo">Volvo</option>
</select>

However, I am facing a challenge when it comes to creating a dynamic select that fetches its values from an object within this.state. The structure of my state object is as follows:

state: { "first_one": "All accounts", "second_one": "second property", "third_one": "All Web Site Data"}

My goal is to display these values in a custom select format. When the user clicks on the select, I want to open a modal without displaying the dropdown list. Unfortunately, I am unsure how to implement this feature. Are there any libraries in reactJS that could help me achieve this? I would greatly appreciate any guidance or solutions you can provide.

Answer №1

Here is a solution that should do the trick. Basically, you store all your options in the state as mentioned before, giving each one a value and the corresponding display name. The activeItem in the state keeps track of the current selection in the dropdown and is updated through the onChange event.

class TaskList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      activeItem: '',
        items: [
          {
            value: "allAccounts",
            name: "All accounts"
          },
          {
            value: "secondProperty",
            name: "Second Property"
          },
          {
            value: "allWebsites",
            name: "All Web Site Data"
          }
        ]
    }
  }

  componentDidMount() {
    this.setState({activeItem: this.state.items[0].value})
  }

  render() {
    const {items, activeItem } = this.state;
    return (
      <div>
        <select onChange={(e) => this.setState({activeItem: e.target.value})}>
          {items.length && items.map((item, index) => {
                return <option key={index} value={item.value}>{item.name}</option>;    
          })}
        </select>
        <div>Active Item: {activeItem}</div>
      </div>
    )
  }
}

ReactDOM.render(<TaskList />, document.querySelector("#app"))

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

Custom variables can be passed to subscription buttons through Paypal

I am currently working on finding a solution to passing custom variables when applying for a subscription for my created web service. The code on the front end that I have implemented so far is as follows: const createSubscription = (data, actions) => { ...

Executing Rake tasks on the live server fails because of an issue with ExecJS

I currently have a Rails 4 application running on a RHEL 6 server. The production environment utilizes Passenger and Apache2. Recently, I've been attempting to schedule Rake tasks in the production environment using the Whenever Gem and Cron. Howev ...

What does the client perceive or not perceive? Node.js, JavaScript, MySQL

For a university project, I am tasked with creating a web application that is compatible with both desktop browsers and mobile devices. The technologies I will be using include HTML, CSS, JavaScript, Node.js, and MySQL. I have recently familiarized myself ...

Is there a way to make a string evaluate inline using JavaScript and React?

In my function, the following code works perfectly: console.log(theme.colors.blues[1]); To make the last part dynamic, I tried the following approach: const getColor = (theme, passedColorProp) => { console.log(theme.colors.[passedColorProp]); }; g ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...

To retrieve the request parameter within the socket.on operation

As a newcomer to node.js, I may have made some mistakes along the way. Please bear with me. When trying to retrieve parameters passed in the URL like localhost:3000?id=man&fm=gilli, I used the following code: app.get('/',function(req, re ...

Determining the offsetWidth and scrollWidth for option elements within a select field containing the multiple attribute on Internet Explorer 11

My select input element has multiple attributes and a fixed width set. Unfortunately, due to the fixed width, the overflowing content in the x-direction is not visible. To address this issue, I have created a JavaScript function that uses the title attribu ...

Is there a workaround available for the JavaScript timeout and interval functions in XPages SSJS?

While utilizing XPages' server-side JavaScript (SSJS), I find myself longing for the timing/scheduling features like setTimeout, setInterval, clearTimeout, and clearInterval. Has anyone developed a polyfill to add these crucial functions to SSJS? ...

The placement of text appears to be incorrect when applying the float:left property in CSS

My issue is that I want #text1 to display on the right side of #video1, and #text2 to be positioned next to #video2. However, currently #text2 is also appearing beside #video1. Can someone please explain why this is happening and provide a solution to fi ...

Steps to showcase a HTML modal based on the outcome of a JavaScript/AJAX database query

Currently in the process of developing a Facebook game utilizing html and Javascript. With two modals on an html page (referred to as ModalA and ModalB), the goal is to link both modals to a single button, triggering the display of only one modal based on ...

Implementing NodeJS to showcase an array of items - the step-by-step guide

I'm currently setting up a webpage to display a list of books using NodeJS, but despite my efforts, the page remains blank when I launch it. My goal is to showcase the array of books on the page, and so far, here's the code that I have written. A ...

HowlerJS: Unauthorized Access - Error Code 401

Working with Angular 7, I have developed an application that consumes data from an API. I have successfully implemented CRUD functionalities using an http-interceptor that adds a token to each request. However, I encountered a 401 error when integrating Ho ...

jQuery Datatables causing hyperlinks to malfunction on webpage

After implementing jQuery datatables on this example using a PHP serverside processing file pulling data from MySQL, the Sign-in button used to work but now it just reloads the same index page. Manually typing in the address linked to the Sign In page work ...

Prioritize loading the JS function before initiating PHP validation

My current challenge involves calling a JavaScript function from PHP upon form submission. The error message I am encountering indicates that the function is not defined. This issue arises because PHP is loaded before JavaScript, resulting in the function ...

Looking for assistance with fixing the echo issue in my PHP temperature converter script. Any help is greatly appreciated

Below is my PHP code for converting temperatures: <html> <head> <title>Temperature Conversion</title> <meta charset="utf-8"> </head> <body> <form name="tempConvert" method=&q ...

Using ant-design with react-draggable for modals: A step-by-step guide

Trying to implement a modal window using ant-design with the react-draggable npm package has been quite challenging. For those unfamiliar, react-draggable is a simple component for enabling drag functionality on elements. However, I encountered an issue wh ...

Queries with MongoDB RegEx fail to return any matches if the search string contains parentheses

When trying to implement case-insensitivity using regex, it seems to work well for plain strings. However, if special characters like parenthesis are involved in the search query for the name, the database returns no results. For example, a search for "Pu ...

What causes getServersideprops to return undefined?

The data I am trying to fetch is showing as undefined in the console. Here is the code snippet: export default function Home({ data }) { console.log(data); return ( <div> <h2>Welcome !!</h2> </div> ); } export a ...

The paginationMeta.hasNextPage function in mui DataGrid seems to be malfunctioning

Despite explicitly setting the paginationMeta.hasNextPage prop to false in the code snippet below: return ( <DataGrid rows={rows} columns={rfqCols} paginationModel={paginationModel} paginationMeta={{hasNextPage: false}} so ...

The button's color remains static in Internet Explorer despite attempts to change it using a linear gradient background image

I'm curious why the button appears grey in IE and turns blue on hover, rather than starting off blue and becoming darker blue when hovered over. I've managed to make it work in other browsers, but I'm struggling with the code for IE. Thank ...