Monday, May 2, 2022

Multi-Selection List in React


 

In this post we will implement a simple multi-selection list in react.


We start with the component configuration. The name of the component is GuiMultiSelect.


import styles from './component.module.css'

function GuiMultiSelect(props) {
const {selected, options, onChange, label} = props



The multi-selection receives the following properties:

  • options - strings list of the possible values
  • selected - strings list of the selected values
  • label - the label to add for the list
  • onChange - callback to invoke upon selection change


The rendering of the component includes the label, and the select element, which includes list of the options.


  return (
<div>
<div className={styles.label}>
{label}
</div>
<select
multiple={true}
className={styles.select}
size={20}
onChange={handleChange}
>
{items}
</select>
</div>
)
}

export default GuiMultiSelect



The options rendering uses the values from the options property, and set the selected attribute.



const items = []
options.forEach(option => {
items.push(
<option
key={option}
value={option}
selected={selected.includes(option)}
>
{option}
</option>,
)
})





The onChange will get the updated status for each option, and send a new strings list of the selected values.


function handleChange(event) {
const newSelected = []
const items = event.target.getElementsByTagName('option')
for (let i = 0; i < items.length; i++) {
const option = items[i]
if (option.selected) {
newSelected.push(option.value)
}
}
onChange(newSelected)
}


In addition, we add styling for the elements.


component.module.css

.select {
width: 500px;
font-size: 20px;
margin-left: 20px;
}

.label{
padding: 25px;
}



The full code is below.

component.js

import styles from './component.module.css'

function GuiMultiSelect(props) {
const {selected, options, onChange, label} = props

function handleChange(event) {
const newSelected = []
const items = event.target.getElementsByTagName('option')
for (let i = 0; i < items.length; i++) {
const option = items[i]
if (option.selected) {
newSelected.push(option.value)
}
}
onChange(newSelected)
}

const items = []
options.forEach(option => {
items.push(
<option
key={option}
value={option}
selected={selected.includes(option)}
>
{option}
</option>,
)
})

return (
<div>
<div className={styles.label}>
{label}
</div>
<select
multiple={true}
className={styles.select}
size={20}
onChange={handleChange}
>
{items}
</select>
</div>
)
}

export default GuiMultiSelect




No comments:

Post a Comment