How to create a controlled form in react that allows upper case letters only?

I have written simple toInputUppercase function which override e.target.value and applied attribute onInput to <input /> element which I want to be capitalize.

import React, { useState } from "react";
import ReactDOM from "react-dom";

const toInputUppercase = e => {
  e.target.value = ("" + e.target.value).toUpperCase();
};

const App = () => {
  const [name, setName] = useState("");

  return (
    <input
      value={name}
      onChange={e => setName(e.target.value)}
      onInput={toInputUppercase} // apply on input which do you want to be capitalize
    />
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

Hope it will work for you.


This should be sufficient:

handleChange(event) {
  const input = event.target;
  const start = input.selectionStart;
  const end = input.selectionEnd;

  this.setState(
    {value: input.value.toUpperCase()},
    () => input.setSelectionRange(start, end)
  );
}

Also check: http://blog.vishalon.net/javascript-getting-and-setting-caret-position-in-textarea


You can simply add this property to the input field :

onInput={(e) => e.target.value = ("" + e.target.value).toUpperCase()}

Hope it works :)