Home > Mobile >  Show the name of the menu item when I select it with react hooks
Show the name of the menu item when I select it with react hooks

Time:11-17

So i have on my parent component some data like this:

const filters =[
name1,
name2,
name3,
etc

]

and I try to make a Select button with a list (using mui/material) from that data that i get on my component using props. I actually made the list while I map through the data like my code below. But the problem is that i want when I select an item the name to be shown on the select button and change every time I select a diffrent one. Thats why used useState to change the value every time but im not sure how can i make a function to get each name from the data, becaue I use the map function after the select component.

import * as React from 'react';
import { Button, Menu, MenuItem } from '@mui/material';
import { FormControl, FormHelperText, Select } from '@mui/material';

import { useEffect, useState } from 'react';

const SampleMenuList = (props) => {
    
    const [checked, setChecked] = useState(0);
    const [anchorEl, setAnchorEl] = React.useState(null);

    const [value, setValue] = useState(''); //here im setting the state 


    const open = Boolean(anchorEl);

    const handleToggle = (value) => { 
        setAnchorEl(null);
        if (value !== checked) {
            setChecked(value);
            props.onFilterChange(props.filters[value]);
        }
        
    };

    const handleSelectChange = (event) => {
        setValue() // here im not sure how can i get the name from the data when i choose is menu item
    };

    return (
        

        <Select value={value} onChange={handleSelectChange}>
            {props.filters.map((c, idx) => {
                const labelId = `checkbox-list-label-${idx}`;
                return (
                    <MenuItem
                        onClick={handleToggle.bind(this, idx)}
                        key={idx}
                        id={labelId}
                        value={c}
                    >
                        {c}
                    </MenuItem>
                );
            })}
        </Select>
    );
};

export default SampleMenuList;



CodePudding user response:

You can get the value of selected item from event object.

More about Select in Mui

Example: (replaces handleSelectChange event)

const handleSelectChange = (event) => {
  setValue(event.target.value);
};

Hope this will help!

  • Related