mirkovski
mirkovski

Reputation: 75

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

Upvotes: 0

Views: 8142

Answers (3)

Hetal Malaviya
Hetal Malaviya

Reputation: 1

 const handlecapClick = () => {    
    let newtext = text.charAt(0).toUpperCase() + text.slice(1);
    setText(newtext);
  };

Upvotes: 0

You can try the following code below:

import React,{useEffect, useState} from "react"
const Home=()=>{
  const [text, setText] = useState("")
  const changeInput = (e)=>{
    let str = e.target.value;
  let con =   str.split(' ')
    .map(function (word, index) {
      // First character upper case else lower case
      return word.charAt(0)
        .toUpperCase() + word.slice(1)
        .toLowerCase();
    })
    .join(' ');
    setText(con);
  }
 
  return (
    <div>
      <input placeHolder="Type Something" style={{textTransform:"capitalize"}} onChange={(e)=>changeInput(e)}/>
      <br/>
      value = {text}
    </div>
  );
}

export default Home;

Upvotes: 1

Almaju
Almaju

Reputation: 1383

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));
}

Upvotes: 3

Related Questions