乐闻世界logo
搜索文章和话题

How to sort an array based on selected language? ( ReactJS )

1个答案

1

In React, to sort an array based on the selected language, we first need to identify the element types within the array, which typically include strings that can be sorted using language-sensitive rules. To achieve this, we can utilize the JavaScript Intl.Collator object, which is an internationalization-sensitive comparator for string comparison.

Here is a specific example demonstrating how to sort an array containing city names based on the user's selected language (such as English, Chinese, etc.) within a React component.

jsx
import React, { useState } from 'react'; function LanguageSensitiveSort() { const [language, setLanguage] = useState('en'); // Default language is English const [cities, setCities] = useState(['北京', '洛杉矶', '纽约', '上海', '巴黎']); // Called when the language selection changes const handleLanguageChange = (event) => { setLanguage(event.target.value); sortCities(event.target.value); }; // Sort the cities based on the selected language const sortCities = (lang) => { const collator = new Intl.Collator(lang); const sortedCities = [...cities].sort(collator.compare); setCities(sortedCities); }; return ( <div> <select onChange={handleLanguageChange}> <option value="en">English</option> <option value="zh">中文</option> <option value="fr">Français</option> </select> <ul> {cities.map((city, index) => ( <li key={index}>{city}</li> ))} </ul> </div> ); } export default LanguageSensitiveSort;

In this example, the component LanguageSensitiveSort is defined with a state language to store the currently selected language and another state cities to store the city list. It includes a dropdown select box that allows users to choose a language (English, Chinese, French). When the user changes the selection, the handleLanguageChange function is triggered, updating the language state and invoking the sortCities function to sort the city array.

Within sortCities, an Intl.Collator instance is created based on the selected language, enabling the collator.compare method to compare strings according to language-specific rules and achieve language-sensitive sorting. After sorting, the cities state is updated, triggering the component to re-render and display the sorted city list.

This approach ensures the application displays appropriate data sorting based on the user's language preference, enhancing the user experience.

2024年7月18日 22:34 回复

你的答案