Reputation: 269
I have this simple react js application in which I am simply converting the text from upper to lower text using useState. But this text is being capitalized in the same textarea, I want to show the capitalized text on another textarea. and leave the lower case text in the same area. Here is my code:
import React from 'react'
import { useState } from 'react'
function TextArea(props) {
const handleUpperClick= () => {
let newText = text.toUpperCase();
setText(newText)
}
const handleOnChange= (event) => {
setText(event.target.value);
console.log(event.target.value);
}
const [text, setText] = useState("Enter the text here please!");
return (
<div>
<h1>{props.heading}</h1>
<div className="mb-3">
<label htmlFor="myBox" className="form-label">Example Text Area</label>
<textarea name="" id="myBox" value={text} onChange={handleOnChange} cols="30" rows="10" className="form-control"></textarea>
</div>
<button className="btn btn-primary" onClick={handleUpperClick}>
Convert to Upper Case
</button>
<div className="mb-3">
<label htmlFor="myBox" className="form-label">Capital</label>
<textarea name="" id="myBox" cols="30" rows="10" className="form-control"></textarea>
</div>
</div>
)
}
export default TextArea
Please help me with this approach.
Upvotes: 1
Views: 288
Reputation: 25408
You can use useRef
here as:
<textarea
name=''
id='myBox'
cols='30'
rows='10'
ref={capitalCaseTextArea}
className='form-control'
></textarea>;
and declare capitalCaseTextArea
as:
const capitalCaseTextArea = useRef(null);
and on clicking button you can set value of textarea
as:
const handleUpperClick = () => {
let newText = text.toUpperCase();
// setText(newText);
capitalCaseTextArea.current.value = newText;
};
Upvotes: 1