0

I am working on a React Typescript project. In here for a usage I need to get the index of the array map() to another function.

        <select className="form-control" value={cbnState} onChange={(e) => showDemographicInfo(e)}>
           {cbnArray.map((item: any, index:any) => (
              <option value={item.cbn}>{item.cbn} | {item.unit} | {index}</option>
            ))}
        </select> 
         

In here I want to pass thin index to OnChange function (showDemographicInfo)

This is the code of onChange function

const showDemographicInfo = (event: any) => {    
if (cbnList.length > 1 && cbnState === COMBINED) {
  setLeftArrowClass(ClassModifier.IN);
  setRightArrowClass(ClassModifier.IN);
}
setCbnState(event.target.value);

if (event.target.value !== COMBINED) {
  updateUserId(event.target.value);
  setCombinedState(false);
  setUnit(unit);
} else {
  setCombinedState(true);
  updateUserId(cbnArray[1]);
}

console.log("Index ",cbnArray[]);

};

In this cbnArray[] I need to add the index. Like cbnArray[index value].

Can anyone tell me how can I do that. I tried for a long time and couldn't find a solution

2
  • do you mean to get index of option was selected inside showDemographicInfo ? Commented Jun 9, 2021 at 15:39
  • @somallg yes . That is Commented Jun 9, 2021 at 15:42

1 Answer 1

1

Simply access selectedIndex of select element will give you the selected index

  const showDemographicInfo = (event: any) => {
    const select = event.target;
    console.log(select.selectedIndex);
  };

Working sandbox

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.