Home > Back-end >  how can i get my button to disappear? in reactjs
how can i get my button to disappear? in reactjs

Time:11-12

i am trying to make my button disappear if my textarea is empty

until now i have made some code for it but i still cant do it

in the code i am trying to make the css dynamic by having it change accoring to some ternery condition id the condition is met the css will allow the button to work and if not the other css class will turn the button off my problem is that i want the on/off condition to work only when the textfield has more than one letter ( is not empty ) this will help me in my posting application as it will not post any empty posts instead only posts with letters and words ( non empty textarea) will post

here is the code:

function PostingNow() {
  
  const [post, setPost] = useContext(Mycontext);
  const tw = useRef('')
  const[count,setCount] = useState(false)

  

  return (
    <div >
    
      <textarea  placeholder='whats up?' className="box" ref={tw}></textarea>

      
      
    
      <button className={count?'tweetbutton':'unclickable'} >
        Tweet 
      </button>

      </div>
      
    
      
      
      {post.map((post, i) => (
        <Postingcomponent name ='user name'image={Photo} key={i} postContent={post}/>
        
      ))}
    </div>
  );
}
export default PostingNow

CodePudding user response:

You can conditionally render your button in the jsx.

First make your textarea a controlled component so you have access to its state.

Then write

{textAreaText && <button ... />}

CodePudding user response:

Make the textarea to be a controlled input

const [textarea, setTextarea] = useState("")

...

<textarea onChange={e => setTextarea(e.target.value)}>{textarea}</textarea>

Then for the button:

{textarea && <button ... />}

For better UX, it's recommended to disable the button instead of removing it from DOM.

<button disabled={!textarea} ... />

CodePudding user response:

If you make the TEXTAREA tag something like:

<textarea placeholder='whats up?' className="box" ref={tw} class='unclickable' 
        onkeyup="fixPostButton(this, 'postButton', 'unclickable', 'tweetbutton');">

And make the BUTTON:

<button id="postButton" >Tweet</button>   

Then this javascript will change the class after each keystroke:

<script>
function fixPostButton(txta, butn, isempty, notempty) {
  var classX = (txta.value == '') ? isempty : notempty ;
  document.getElementById(butn).className = classX; }
</script>
  • Related