0

I have a textarea and a button. The button is disabled by default and when the user starts typing, I enable the button to be clicked. But the problem is that, the onClick function is not called while already disabled = false was set.

I've seen this: button onClick doesn't work when disabled=True is initialized (Reactjs) Seems to be a good idea, but after I setState with the new value, my component is re-rendering, and I don't really want that.

const refText = useRef(null);
const refBtn = useRef(null);

function handleBtnStatus(e) {
    let text = e.target.value;
    if(text.replace(/\s/g, "").length > 0) {
        refBtn.current.disabled = false;
    }
    else {
        refBtn.current.disabled = true;
    }
}

function postThis() {
    console.log("You posted! Text:", refText.current.value);

    // disable again
    refBtn.current.disabled = true;

    // delete previous text wrote
    refText.current.value = "";
}

return (
    <>
        {isLogged && (
            <div className="container">
                <div className="content">
                    <div className="utool-item-text">
                        <textarea name="textArea" placeholder="Write something.." ref={refText} onChange={(e) => handleBtnStatus(e)}></textarea>
                    </div>
                    <div className="utool-item-post">
                        <button className="ust-btn-post" ref={refBtn} disabled={true} onClick={postThis}>Da Tweet</button>
                    </div>
                </div>
                <div className="posts-section">
                    <div className="list-posts">
                        {posts.map((p) => {
                            return (p.hidden === false ? (
                                <div className="post" key={p.id}>
                                    <div className="post-text">
                                        <span>{p.text}</span>
                                    </div>
                                </div>
                            ) : (''))
                        })}
                    </div>
                </div>
            </div>
        )}
    </>
)

Any help?

Galbert
  • 177
  • 1
  • 8
  • You **must** not maniûlate DOM directly when using React. So you have to store your textarea value in a state, and enable/disable the button depending on the state value, directly in JSX – dbuchet Jan 13 '23 at 14:55

1 Answers1

1

Use state instead of refs, re-rendering is ok for your case

Simplified example:

import React, { useState } from 'react';

const SimpleExample = () => {
  const [textAreaValue, setTextAreaValue] = useState('');

  return (
    <>
      <button disabled={!textAreaValue} onClick={() => console.log('onClick handler')}>
        click me
      </button>
      <textarea value={textAreaValue} onChange={(e) => setTextAreaValue(e.target.value)} />
    </>
  );
};

And I would recommend checking this Use state or refs in React.js form components?