Search code examples
cssreactjsformsfrontendantd

Auto Capitalization of Input value in React


so I have an input field that accepts any input the user types and I've already made it look like it has auto capitalization of first letter using CSS styles: textTransform: capitalize but when I assign a useState variable to the input field, the value isn't properly capitalize as shown on the input field. I want the useState variable's value to have proper capitalization as shown in the input field.

Here's my simple code:

import {useState} from "react"
import "./styles.css";
import {Input} from "antd";

export default function App() {
  const [text, setText] = useState("")
  return (
    <div className="App">
      <Input placeHolder="Type Something" style={{textTransform:"capitalize"}} onChange={(e)=>{setText(e.target.value)}}/>
      <br/>
      value = {text}
    </div>
  );
}

Also here's a codesandbox link for better visualization


Solution

  • You need to change the value of the input when passing it to the state:

    onChange={(e) => {
      setText(e.target.value.charAt(0).toUpperCase() + e.target.value.slice(1));
    }