Reputation: 177
I have multiple elements that are coming dynamically and the markup is like this:
<li>
<div>
<input type="radio" value="abc" name="abc">
<span>ABC</span>
</div>
</li>
<li>
<div>
<input type="radio" value="bcd" name="bcd">
<span>BCD</span>
</div>
</li>
What I need is to sort these elements in react? What would be the best approach here? to sort value or name or span content and how to do so?
Currently I'm mapping them:
const RadioButtonComponent = ({question, setAnswer, answer, lang}) => {
const radioSingleElement = question.options.map((opt) => {
return <li onClick={() => setAnswer(option.value)}>
<Radio className="r-buttons" value={opt.value}} /><span>{question.useKeysForLabels ? lang[opt.label] : opt.label}</span>
</li>
});
return (
<RadioGroup name={question.name} selectedValue={answer} onChange={(value) => {setAnswer(value);}>
<ul>
{radioSingleElement}
</ul>
</RadioGroup>
)
}
Upvotes: 1
Views: 3573
Reputation: 7424
Simply sort and map your options
array.
const RadioButtonComponent = ({question, setAnswer, answer, lang}) =>
<RadioGroup
name={question.name}
selectedValue={answer}
onChange={value => setAnswer(value)}
>
<ul>
{options
.sort((opt1, opt2) => opt1.label > opt2.label) // order options alphabetically by label
.map(option =>
<li key={option.value} onClick={() => setAnswer(option.value)}>
<Radio
className="r-buttons"
value={opt.value}
/>
<span>{question.useKeysForLabels ? lang[opt.label] : opt.label}</span>
</li>
)
}
</ul>
</RadioGroup>
Upvotes: 4
Reputation: 1187
There are several ways to handle this, but the best way is to sort the array that you're getting the data from. I'm assuming that you want the user to be able to sort the data in ascending/descending order. So, you would have a data array that looks like this:
constructor(props) {
super(props);
state = {
data: [ { name: 'abc', type: 'foo' }, { name: 'bcd', type: 'bar' }, ...],
sortAscending: true
}
this.sortList = this.sortList.bind(this);
}
sortList() {
let newData = this.state.data.sort((objectA, objectB) => {
if (this.state.sortAscending) {
return objectA.name - objectB.name;
} else {
return objectB.name - objectA.name;
}
this.setState({
sortAscending: !this.state.sortAscending,
data: newData
}
render() {
<button onClick={ this.sortList }>Sort</button>
}
I didn't try that out, but I think you should be able to get that to work if I made a couple of mistakes. Let me know if you have any questions.
Upvotes: 2