Steven
Steven

Reputation: 269

Select the text from one textarea and show the same but capitilized text in other textarea in react js

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

Answers (1)

DecPK
DecPK

Reputation: 25408

You can use useRef here as:

CODESANDBOX LINK

<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

Related Questions