What is the best way to include a check mark icon using MUI or Tailwind CSS for every item selected in a dropdown menu?

I need help with adding a small check/tick icon next to the selected value, for example: Operations ✓ when the user chooses operations in the TopicList dropdown list. The TopicList is a class component used to retrieve data from the database which includes: Operations, Array, Repetition, Function, Selection. If the user selects two different values, it should look like this: Operations ✓ Array ✓ Repetition Function Selection. How can I update the code to address this issue? Here is an illustration of how I want it to appear when the user selects Array. https://i.stack.imgur.com/CUxBb.png

import axios from "axios";
import React, { useState } from "react";
import TopicList from "../Components/topicList";
import CheckIcon from '@mui/icons-material/Check';

function CreateEvent(success, message) {
  const navigate = useNavigate();
  const [selectedValues, setSelectedValues] = useState([]); // array to store selected values

  const getDataFromTopicList = (val) => {
    if (val !== "" && !selectedValues.includes(val)) {
      setSelectedValues([...selectedValues, val]);
    }
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(selectedValues); // selectedValues array contains all selected values from all TopicList components

    axios({
      method: "POST",
      url: BASE_URL + "events/submitEvent",
      data: {
        topicId: selectedValues,
      },

      headers: { "Content-Type": "application/json" },
    })
      .then((response) => {
        if (response.status === 200) {
          toast.success("Successfully Created", {
            position: toast.POSITION.TOP_CENTER,
          });
        } else {
          toast.error(response.data.message, {
            position: toast.POSITION.TOP_CENTER,
          });
        }
      })
      .catch((err) => {
        if (err.response) {
          toast.error(err.response.data.message, {
            position: toast.POSITION.TOP_CENTER,
          });
        } else {
          toast.error("Failed to Create", {
            position: toast.POSITION.TOP_CENTER,
          });
        }
      });
  };

  return (
    <div className="">
      <div>
        <form
          onSubmit={handleSubmit}
        >
          <h1>
            Create an Event
          </h1>
          <div>
            <div>
              <TopicList
                selectedValues={selectedValues}
                getDataFromTopicList={getDataFromTopicList}
              />
            </div>
          </div>
        </form>
      </div>
    </div>
  );
}

export default CreateEvent;
import axios from "axios";
import React from "react";
import CheckIcon from "@mui/icons-material/Check";

const BASE_URL = process.env.REACT_APP_BASE_URL;

export default class TopicList extends React.Component {
  state = {
    topics: [],
  };

  componentDidMount() {
    axios.get(BASE_URL + `events/topic`).then((res) => {
      const topics = res.data;
      this.setState({ topics });
    });
  }

  render() {
    return (
      <select required onChange={(val) => this.getCat(val.target.value)}>
        {this.state.topics.map((topic) => (
          <option value={topic.topicId}>
          {topic.topic}
          {this.props.selectedValues.includes(topic.topicId) && <CheckIcon style={{ color: "green" }} />}
        </option>
        ))}
      </select>
    );
  }
}

Answer №1

It appears that the provided code includes MUI but is not utilizing its components within the TopicList.

Below is a simple example showcasing the use of MUI Select, along with the necessary implementation of CheckIcon for multiple selected values.

For a condensed demonstration, visit: stackblitz

The example excludes the data fetching part for ease of understanding, maintaining the same topics state and obtaining props for selectedValues in TopicList.

The update function for selectedValues has been adjusted for the MUI component while retaining an array of selected topicId, facilitating potential integration with data fetching without major code restructuring.

Imports for MUI components in TopicList:

import OutlinedInput from '@mui/material/OutlinedInput';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import ListItemText from '@mui/material/ListItemText';
import ListItemIcon from '@mui/material/ListItemIcon';
import Select from '@mui/material/Select';
import CheckIcon from '@mui/icons-material/Check';

The altered output of TopicList:

<FormControl sx={{ m: 3, width: 300 }}>
  <InputLabel id="topic-form-input-label">Topic</InputLabel>
  <Select
    labelId="topic-form-label"
    id="multiple-topic-select"
    multiple
    value={this.props.selectedValues}
    onChange={this.props.onChange}
    input={<OutlinedInput label="Topic" />}
    renderValue={(selected) =>
      selected
        .map((topicId) => {
          const selectedTopic = this.state.topics.find(
            (item) => item.topicId === topicId
          );
          return selectedTopic ? selectedTopic.topic : topicId;
        })
        .join(", ")
    }
  >
    {this.state.topics.map((topic) => {
      const selected = this.props.selectedValues.includes(topic.topicId);
      return (
        <MenuItem key={topic.topicId} value={topic.topicId}>
          {selected && (
            <ListItemIcon>
              <CheckIcon style={{ color: "green" }} />
            </ListItemIcon>
          )}
          <ListItemText inset={!selected} primary={topic.topic} />
        </MenuItem>
      );
    })}
  </Select>
</FormControl>

Selected values received from the parent component:

const [selectedValues, setSelectedValues] = useState([]);
const handleChange = (event) => {
  const {
    target: { value },
  } = event;
  setSelectedValues(typeof value === "string" ? value.split(",") : value);
};
<TopicList
  selectedValues={selectedValues}
  onChange={handleChange}
/>

Answer №2

Click here to view a demo of a select element with checkboxes nested inside. If you want to check out the code, simply click on this link.

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

Creating unique backgrounds for multiple webpages with React (Ensuring backgrounds stay consistent after refreshing)

Home.js file const Home = () => { var navigate = useNavigate(); const changeBackground = () => { navigate("/builder"); var htmlElement = document.getElementsByTagName('html'); htmlElement[0].style.backgr ...

Is it true that DOM objects in JavaScript are considered objects?

I've been searching for an official answer to this question, but it seems there is some confusion. Some people consider DOM objects to be JS objects, while others argue that they are different entities. What is the correct answer? If you search on Sta ...

Fill out a React formik form with the data that is already in place

Seeking guidance on how to manipulate or repopulate an existing form in React with backend data. I am using Formik and Formik Grid along with Axios for data retrieval. My goal is to edit a specific item in the inventory by updating its values from the da ...

How to prevent collapse when selecting a node in React.js Mui Treeview

Is there a way to prevent the Treeview from collapsing every time a node is selected? I want it to render a button based on the selected node. Here's an example that I've created: https://codesandbox.io/s/summer-water-33fe7?file=/src/App.js ...

Converting a List of Maps from Immutable.js into a List of Lists and utilizing it as the dataset for Google Charts

I am currently working on implementing the Google Charts library to visualize some time series data. Right now, I have dummy data stored in a separate file from my application. In this file, I have an Immutable List structured like this: le ...

Steps for refreshing Google reCAPTCHA on an AJAX-enabled webpage

I am encountering an issue with two captchas on my website. One captcha is loaded upon refresh, while the second captcha is loaded on a different page via ajax. The problem arises when I click on the "No" button after selecting it on the second page. I wan ...

The submission form is being triggered immediately upon the page loading

I have a form on the landing page that sends parameters to Vuex actions. It functions correctly when I click the submit button and redirects me to the next page as expected. However, there seems to be a problem. Whenever I open or refresh the page, the par ...

There are no specified operations outlined in the Node.js Express documentation

swagger ui https://i.stack.imgur.com/UIavC.png I've been struggling to resolve this issue where the /swagger endpoint seems to only partially read the swagger.json file. Despite configuring everything correctly, no errors are appearing. It simply dis ...

Refreshing a jsp page without the need to reload the content

On my jsp page, I am displaying the contents of a constantly changing table. This means that users have to refresh the page every time they want to see updated information. Is there a way for me to update the content dynamically without requiring users t ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Disappear text gradually while scrolling horizontally

There is a need to create a special block that displays fading text on horizontal scroll. However, the problem is that the block is situated on a non-uniform background, making the usual solution of adding a linear gradient on the sides unsuitable. Click ...

Setting up various connections is made possible through Node.js Socket.io

In the process of developing a straightforward chat application using socket.io and incorporating passport.js for user authentication, an issue arises when users log out and then back in. The previous socket connection remains active, resulting in two conn ...

Generate clickable links on a web page with PHP and a form

Every week I find myself tediously creating links by manually copying and pasting. It's starting to feel like a crazy process, and I'm sure there must be a faster way. A123456 B34567 d928333 s121233 I need these numbers to be transformed into h ...

Vue.js has a feature where it automatically closes the form tag within a for loop

In my Vue.js application, I have created a table where each row is a form with a submit button. This is the code snippet I am using: <div id="admin-user"> <table class="table"> <tr v-for="(user, index) in users"> < ...

Encoding a JSON representation of an HTML list where all children are displayed at each parent item

Here is the structured list that I am currently working with: function convert( name_ref ) { name_ref = name_ref + " > ol > li"; var mylist = []; $(name_ref).each(function () { if ($(this).find('> ol > li').length){ myl ...

Connect or disconnect an element to a JavaScript event handler using an anonymous function

I'm stuck on a basic issue... I have a custom metabox in my WordPress blog, and here's my event handler: jQuery('tr input.test').on('click', function( event ){ event.preventDefault(); var index = jQuery(this).close ...

Are the events objects failing to render or is the scope not being broadcasted properly

I'm having trouble displaying my events using the ionic-calendar plugin by calling the $scope.loadEvents method. Unfortunately, the events are not showing up on the calendar. Here is the link to the plugin I am using: https://github.com/twinssbc/Ioni ...

How to Delete Decimal Points from a String Using Regular Expressions

I am searching for a way in JavaScript, such as REGEX, to eliminate decimal numbers from a string. Here is an example input: Mazda 6 2.0 Skyactiv-G Wagon 2018 - Startstop.sk - TEST Mercedes C63 AMG Sound REVVING 6,3l V8 And here is the expected output: M ...

Having trouble retrieving information from the local API in React-Native

Currently, I have a web application built using React and an API developed in Laravel. Now, I am planning to create a mobile app that will also utilize the same API. However, I'm encountering an issue where I cannot fetch data due to receiving the err ...

What is the best way to transfer data to a different page in NextJS?

I need a solution for transferring data from my /app/mypage/ page to a new tab where /app/mypage/edit is loaded. The goal is to avoid reloading the data and instead pass it directly. The data object being transferred is quite large, so an efficient metho ...