Home > Blockchain >  Whenever i try to change the value of this cons variable whole content disappear
Whenever i try to change the value of this cons variable whole content disappear

Time:06-16

import React,{useState} from 'react'

export default function Box() {

  const [count,setCount] = useState('hello);
  setCount("welcome")
  return (
    
    <div className="box">
    <textarea name="input" id="input1" cols="30" rows="10" value={count}></textarea>
    
      <button value="up was clickd" id='btn1' >Convert toupper case</button>
    </div>
    
  )
}

CodePudding user response:

You are unconditionally enqueuing the state update. The component is stuck render looping.

Use a useEffect or some other conditional way (i.e. onClick callback, etc) to enqueue the state update.

Example:

export default function Box() {
  const [count, setCount] = useState('hello');

  useEffect(() => {
    setCount("welcome");
  }, []);
  
  return (
    <div className="box">
      <textarea
        name="input"
        id="input1"
        cols="30"
        rows="10"
        value={count}
      />
    
      <button value="up was clickd" id='btn1'>
        Convert toupper case
      </button>
    </div>
  );
}

CodePudding user response:

Your code will go into an infinite-render loop. Reason: You are calling a setState unconditionally.

Link which shows the error.

Ideally, your state change should be caused by an action. But currently it is in the top level of the component body and is called on every render. And the state change itself causes a render. Creating your loop.

A simple fix could be to trigger state change on button click

import React,{useState} from 'react'

export default function Box() {

  const [count,setCount] = useState('hello');
  const change = () => {
    setCount("welcome");
  }

  return (
    
    <div className="box">
    <textarea name="input" id="input1" cols="30" rows="10" value={count}></textarea>
    
      <button value="up was clickd" id='btn1' onClick={change}>Convert toupper case</button>
    </div>
    
  )
}
  • Related