Home > Mobile >  React.Js Find which element of the array is selected by the user
React.Js Find which element of the array is selected by the user

Time:04-03

Basically I have a component that is a list of rooms that a user has joined. On top of this component there is a search section, and aside of the search input there are some options about the search, like search by "Room Name" , search by "Organization name " etc. I keep this options in objects inside of an array alongside the id of the option. Then I map this array to show all the options. Now I can display those options but I cant find a way to know which of those options the user has selected. The user has to select only one option and then the option is highlighted

This is the component

This is my code

CodePudding user response:

You need to use react state hook for the same. Whenever one of them is selected update the state with the selected ones name or id, or any selector you need. This example code should help https://blog.logrocket.com/how-to-build-tab-component-react/

CodePudding user response:

I keep this options in objects inside of an array alongside the id of the option. Then I map this array to show all the options.

For this problem, you have to place your array of objects in a useState hook. docs: https://reactjs.org/docs/hooks-state.html

In your individual search option objects, add a boolean property named isSelected and set the default values to false (no search options selected yet).

sample object structure { id: 1, optionName: 'Room Name', isSelected: false}

then, create an onClick function to set the isSelected property to true of the selected option & to set the new state of the array of objects. Hope this helped! Goodluck brother

  • Related