Home > Net >  How can I store all the dynamic values and attribute labels in a state in react js
How can I store all the dynamic values and attribute labels in a state in react js

Time:03-08

I am using react js. I have an attributes array of objects on my single product page and I am displaying the array of objects into the UI. The UI look like this:

enter image description here

I am trying to get the values of the selected attributes, I have set onClick handler to get the value and label but I am only getting the value that is removed after clicking on the second attribute which I don't want. I want to store all the values and attribute labels in a state. The attributes are dynamic sometimes it will be 2 or more or none.

This is the code for dynamic attributes.

{product?.attributes.map(attr => {
        return <div onClick={e => handleAttribute(e.target)} className=" mr-6 items-center">
            <span className="mr-3"><b>{attr.label}</b></span><br />
            <div className="relative">
                <select className="rounded appearance-none border border-gray-200 py-2 focus:outline-none focus:border-indigo-500 text-base pl-3 pr-10">
                    {attr?.selected.map(select => {
                        return <option>{select.label}</option>
                    })}

                </select>
    })}

This is the function but I am confused about how can I get the values and also label for each attributes and it will store in a state.

   const handleAttribute = (e) => {
        console.log(e, 'attr');

    }

My expected output is something like this:

[
{label: colors, selected: Black},
{label: Size, selected: M}
]

The attributes database look like this:

   {
            attributes: [{
                label: "colors",
                selected: [{
                    label: "Black",
                    value: "Black"
                },
                {
                    label: 'Green',
                    value: 'Green'
                }]


            },
            {
                label: "size",
                selected: [{
                    label: "M",
                    value: "M"
                },
                {
                    label: 'S',
                    value: 'S'
                }]
            }
        ]
            
        }

CodePudding user response:

<select onChange((e) => handleAttribute(e))>
{attr?.selected.map(select => {
            return <option value={select.value}>{select.label}</option>
})}
</select>

const handleAttribute = (e) => {
    console.log(e.target.value);
}

Hope this helps basically call onChange in select and pass value into the options

then in the handleAttribute method use e.target.value to get the value of the selected option

CodePudding user response:

You should use State and onChange handler to make sure all the data should be displayed at the same time. For More Ref see State.

  • Related