Home > Mobile >  Why is {text.length} not working in react.js code. I want length of the changing state text.Please h
Why is {text.length} not working in react.js code. I want length of the changing state text.Please h

Time:06-26

import React, { useState } from 'react';

export default function TextForm(props){

const [text,setText]=useState();

const toUppercase=()=>{
    console.log("button is clicked");
    let newText=text.toUpperCase();
    setText(newText);
}

const changingText=(event)=>{
    setText(event.target.value)
}
return(
    <>
    <div className="container">
        <h1>{props.heading}</h1>
        <div className="mb-3">
          <textarea className="form-control" id="txtarea" rows="10" value={text} placeholder="Enter Your text here" onChange={changingText}></textarea>
        </div>
        <button className="btn btn-primary" onClick={toUppercase}>Click to convert to uppercase</button>
    </div>
    <div className="container my-2">
        <h1>Your text summary</h1>
        <p>{text.length} is number of character</p>
    </div>
    </>
)

}

This is the error it shows[1]:https://i.stack.imgur.com/MeoMH.jpg

CodePudding user response:

there is your error

setText(...text,event.target.value);

firt store previous value and add new value otherwise settext every time overwrite by one word

  • Related