0

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

mirkovski
  • 75
  • 2
  • 14

3 Answers3

3

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));
}
Almaju
  • 1,283
  • 12
  • 31
  • Thanks but how would I be able to make it to capitalize only the first letter of the string? :) – mirkovski Mar 24 '22 at 00:46
  • 1
    Check this: https://stackoverflow.com/questions/1026069/how-do-i-make-the-first-letter-of-a-string-uppercase-in-javascript – Almaju Mar 24 '22 at 00:50
  • Thanks for the link it helped me out a lot but I'm almost there, I want my values to look like this "Text Value" but with the current code I am getting "Text value" – mirkovski Mar 24 '22 at 01:14
  • 1
    You can try that then: `setText(e.target.replace(/(^\w|\s\w)/g, m => m.toUpperCase()));`. See https://stackoverflow.com/a/60610887/5103610 – Almaju Mar 24 '22 at 09:59
1

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;
skipperhoa
  • 431
  • 3
  • 7
0
 const handlecapClick = () => {    
    let newtext = text.charAt(0).toUpperCase() + text.slice(1);
    setText(newtext);
  };
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103