You might have a use case in your application where you need the user to select multiple items, for example, selecting favorite artists from a large list of options. This article aims to help you in creating a component that is highly customizable, reusable, and robust.
Individual button component
We will first create a reusable button component that we will render in our selector component. This component will contain a simple TouchableHighlight
that will change its style when it is pressed, indicating its selection status.
We create a state named selected
which will store a boolean which will indicate if the button is pressed or not. This state will be toggled at the press of the button and a callback function onPress
(which would be accepted as a component prop
) will be invoked with the latest selected
value. This will help us inform the parent component that an option has been selected.
This will result in a component that will look like this
Selector component
We will now create the selector component that should render multiple OptionButtons
from an array of data. Let's create the UI for rendering the buttons in a list first.
The above code will give us a UI that should look something like this
Next, we will move on to the implementation of the logic and filtering of these items.
In the method onItemSelect
, we toggle the addition and subtraction of an item from the selectedItems
array when an item is pressed. This would result in the following behavior.
Next, we will filter the list depending on the search term entered in the text field.
onSearchInput
method manipulates the data array depending on the search term entered.
Conclusion
This article focuses on creating a multi-item selector component in react native efficiently. This component is highly customizable and can adapt to your requirements.