Home > Software design >  How to configure 'value' in the input field in React?
How to configure 'value' in the input field in React?

Time:01-01

In React, I have a textbox with a Submit button that is visible when the user clicks 'Wave At Me' and is not visible after the user clicks 'Submit'. What do I put for value in the input tag? How do I get value should I can use it in the setFormText method? In the component class, value is below, but what is the equivalent for the function code?

<input type="text" value={this.state.value} onChange={this.handleChange} />

My code is below in the default App() function, currently the user is unable to change the text:

const [currentVisibility, setVisibility] = useState(false);
const [currentFormText, setFormText] = useState("");

//wave at me button just shows the form
const wave = async () => {
    setVisibility(true);
    console.log("form appears")
  }

// I don't think it's correct to use changeValue function

  const changeValue = async () => {
    console.log("formed had some text");
  }

  const handleChange = async () => {
    console.log("form was changed");
  }

//the handle submit should read the value from the input field to use in the parameter string of the wave() function. 
  const handleSubmit = async () => {
    try {
      setVisibility(false);
      const { ethereum } = window;

      if (ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();
        const wavePortalContract = new ethers.Contract(contractAddress, contractABI, signer);

        let count = await wavePortalContract.getTotalWaves();
        console.log("Retrieved total wave count...", count.toNumber());

        //change to currentText instead of water bottle
        const waveTxn = await wavePortalContract.wave("water bottle");
        console.log("Mining...", waveTxn.hash);

        await waveTxn.wait();
        console.log("Mined -- ", waveTxn.hash);

        count = await wavePortalContract.getTotalWaves();
        console.log("Retrieved total wave count...", count.toNumber());

      } else {
        console.log("Ethereum object does not exist!");
      }
    } catch (error) {
      console.log(error)
    }
  }
return {currentVisibility && (

          <form onSubmit={handleSubmit}>
            <label>
              Message:
          <input type="text" value="" onChange={handleChange} />
            </label>
            <input type="submit" value="Submit" />
          </form>
        )}

CodePudding user response:

The useState hook returns the state value and a setter function. So in your case, currentFormText is the state value and setFormText is the setter function. Thus, your input should read:

<input type="text" value={currentFormText} onChange={handleChange} />

If you do this, you'll notice you can't change the input's value. That's because React is now "controlling" the value of the input; in other words, React is now the "source of truth" for this input (rather than the browser/HTML itself). Because of this, you'll need to add to your handler function:

// we certainly don't need the `async` keyword here!
const handleChange = (event) => {
    console.log("form was changed");
    setFormText(event.target.value);
}

CodePudding user response:

  1. On form submit refresh the page, you need to put this code e.preventDefault(); in handleSubmitfunction !

  2. When handleChange function call you need to set the input value in currentFormText state that's why you unable to change the text !

Try this code it's work for me

function App() {
  const [currentVisibility, setVisibility] = useState(true);
  const [currentFormText, setFormText] = useState("");

  //wave at me button just shows the form
  const wave = async () => {
    setVisibility(true);
    console.log("form appears")
  }

  const changeValue = async () => {
    console.log("formed had some text");
  }

  const handleChange = async (value) => {
    setFormText(value)
    console.log("form was changed");
  }

  //the handle submit should read the value from the input field to use in the parameter string of the wave() function. 
  const handleSubmit = async (e) => {
    try {
      e.preventDefault();
      setVisibility(false);
      const { ethereum } = window;

      if (ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();
        const wavePortalContract = new ethers.Contract(contractAddress, contractABI, signer);

        let count = await wavePortalContract.getTotalWaves();
        console.log("Retrieved total wave count...", count.toNumber());

        //change to currentText instead of water bottle
        const waveTxn = await wavePortalContract.wave("water bottle");
        console.log("Mining...", waveTxn.hash);

        await waveTxn.wait();
        console.log("Mined -- ", waveTxn.hash);

        count = await wavePortalContract.getTotalWaves();
        console.log("Retrieved total wave count...", count.toNumber());

      } else {
        console.log("Ethereum object does not exist!");
      }
    } catch (error) {
      console.log(error)
    }
  }

  return (
    currentVisibility &&
    <form onSubmit={(e) => handleSubmit(e)}>
      <label>
        Message:
        <input type="text" value={currentFormText} onChange={(e) => handleChange(e.target.value)} />
      </label>
      <input type="submit" value="Submit" />
    </form>
  )
}


export default App;
  • Related