Force an Input field to Uppercase in React

avatar

Borislav Hadzhiev

Thu Apr 28 20221 min read

Force an Input field to Uppercase in React #

To force an input field to uppercase in React:

  1. Store the value of the input in a state variable.
  2. Set the onChange prop on the input.
  3. Use the toUpperCase() method to uppercase the field's value, e.g. event.target.value.toUpperCase().
App.js
import {useState} from 'react'; const App = () => { const [message, setMessage] = useState(''); const handleChange = event => { const result = event.target.value.toUpperCase(); setMessage(result); }; return ( <div> <div>hello world</div> <input id="message" name="message" type="text" value={message} onChange={handleChange} /> </div> ); }; export default App;

input uppercase only

We set the onChange prop on the input element, so every time its value changes the handleChange function is invoked.

The target property on the event object refers to the input field, so we can access the input's value as event.target.value.

The value of an input field is guaranteed to be a string, even if the type of the input is set to number, so we can directly call the toUpperCase method on it.

App.js
const str = 'hello world'; const upper = str.toUpperCase(); console.log(upper); // 👉️ "HELLO WORLD"

The toUpperCase method returns a new string that represents the calling string converted to upper case.

Use the search field on my Home Page to filter through my more than 1,000 articles.