Search code examples
javascriptreactjsbuttoninputreact-hooks

display input box value when triggered by button click


The project i am creating in React.js requires me to take in input from the user and display it on the webpage, i want my balance button to display the input value when clicked but currently when i enter a value in the input box it displays automatically rather than waiting for the button click to be triggered before displaying on the webpage. from my code below i was wondering if i am missing something like a handleClick function or add event handlers? As i am new to working with React.js please help??

import React from "react";
import { useState } from "react";

export default function BalanceInput() {
  const [userBalance, setUserBalance] = useState(0);

  function displayBalance() {
    setUserBalance(0);
  }

  return (
    <div>
      <label for="balanceInput">Enter Bank Balance: </label>
      <input
        type="text"
        onChange={(event) => setUserBalance(event.target.value)}
        id="balanceInput"
        placeholder="Enter balance here"
        defaultValue={0}
      />

      <h3>Current Balance: {userBalance}</h3>
      <button onClick={displayBalance}>Balance</button>
    </div>
  );
}

Solution

  • Just add a separate state that is triggered by the button click, and then use that boolean to determine whether to show the current value of the input or zero.

    Note: the label property for in React is htmlFor.

    const { useState } = React;
    
    function BalanceInput() {
      const [buttonClicked, setButtonClicked] = useState(false);
      const [userBalance, setUserBalance] = useState(0);
    
      function handleChange(event) {
        if (userBalance > 0) {
          setUserBalance(0);
          setButtonClicked(false);
        }
        setUserBalance(event.target.value);
      }
    
      return (
        <div>
          <label htmlFor="balanceInput">Enter Bank Balance: </label>
          <input
            type="text"
            onChange={handleChange}
            id="balanceInput"
            placeholder="Enter balance here"
            defaultValue={0}
          />
          <h3>Current Balance: {buttonClicked ? userBalance : 0}</h3>
          <button onClick={() => setButtonClicked(true)}>Balance</button>
        </div>
      );
    }
    const node = document.getElementById('root');
    const root = ReactDOM.createRoot(node);
    root.render(<BalanceInput />);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
    <div id="root"></div>