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
CodePudding user response:
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));
}
CodePudding user response:
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;