React Js Convert All Array Element to Lowercase

React Js Convert All Array Element to Lowercase:In React JS, you can easily convert all elements of an array to lowercase using state management and the map
function. In this tutorial, we will walk you through a simple example of a React component that takes an array and converts all its elements to lowercase. This tutorial assumes you have a basic understanding of React JS.




Thanks for your feedback!
Your contributions will help us to improve service.
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [originalArray, setOriginalArray] = useState(["Hello", "World", "React", "JS"]);
const convertArrayToLowerCase = () => {
const lowercaseArray = originalArray.map(item => item.toLowerCase());
setOriginalArray(lowercaseArray);
};
return (
<div className='container'>
<h2>React Js Array Element to Lowercase</h2>
<button onClick={convertArrayToLowerCase}>Convert to Lowercase</button>
<p>{JSON.stringify(originalArray)}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
Setting Up the React Component
Firstly, let's set up a basic React component. In the provided code snippet, we have a functional component named App
. It initializes a state variable originalArray
containing an array of strings: ["Hello", "World", "React", "JS"]
xxxxxxxxxx
const { useState } = React;
function App() {
const [originalArray, setOriginalArray] = useState(["Hello", "World", "React", "JS"]);
// ...
}
Converting Array Elements to Lowercase
To convert all elements of originalArray
to lowercase, we utilize the map
function. Inside the convertArrayToLowerCase
function, each element of the array is transformed to lowercase, and the updated array is set back to the state using the setOriginalArray
function.
xxxxxxxxxx
const convertArrayToLowerCase = () => {
const lowercaseArray = originalArray.map(item => item.toLowerCase());
setOriginalArray(lowercaseArray);
};
Implementing the User Interface
In the UI, there is a button labeled "Convert to Lowercase." When this button is clicked, the convertArrayToLowerCase
function is invoked, triggering the array transformation process. The updated array is displayed below the button in JSON format
xxxxxxxxxx
return (
<div className='container'>
<h2>React JS Array Element to Lowercase</h2>
<button onClick={convertArrayToLowerCase}>Convert to Lowercase</button>
<p>{JSON.stringify(originalArray)}</p>
</div>
);
After clicking the button, the output displayed on the webpage will be the lowercase version of the original array:
Output of Example
xxxxxxxxxx
["hello", "world", "react", "js"]
Conclusion
In React JS, you can easily convert all elements of an array to lowercase using state management and the map function. In this tutorial, we will walk you through a simple example of a React component that takes an array and converts all its elements to lowercase. This tutorial assumes you have a basic understanding of React JS.