0

I am using React and have the following component:

import React from 'react';

function Calculate({ work }) {

    var inputValue = 0;

    const totalAmountToBePaid = () => {
        inputValue++;
        console.log("=====> Total Amount To Be Paid", work);
        console.log(inputValue);
    };

    return (
        <div>
            <header className="App-header">
                <input type="number" id="amount" value={inputValue} readOnly></input>
                <button onClick={totalAmountToBePaid}>Total Amount To Be Paid</button>
            </header>
        </div>
    )
}

export default Calculate;

When I click the button, I need it to update value of the input by calling the totalAmountToBePaid function.

The above solution just leave the value of the input on its default value of 0.

I am new to React, so please excuse my ignorance. I think I might need to gave a state object.

Thank you

1
  • React updates DOM once the state is changed, so you should add inputValue to the state inorder to reflect the change. Commented Oct 23, 2019 at 9:23

2 Answers 2

3

Yes, you are missing the state object.

Replace it with following

function Calculate({ work }) {
  const [inputValue, setInputValue] = React.useState(0)

    const totalAmountToBePaid = () => {

      setInputValue(inputValue+1);

        console.log("=====> Total Amount To Be Paid", work);
        console.log(inputValue);
    };

    return (
        <div>
            <header className="App-header">
                <input type="number" id="amount" value={inputValue} readOnly></input>
                <button onClick={totalAmountToBePaid}>Total Amount To Be Paid</button>
            </header>
        </div>
    )
}

Working Example https://codesandbox.io/s/dank-pine-9hk26

Since you are new to React, I think you should go through React docs. https://reactjs.org/docs/state-and-lifecycle.html to understand basics.

Sign up to request clarification or add additional context in comments.

Comments

0

If you dont need the console.logs you can just do;

const [inputValue, setInputValue] = useState(0);

<button onClick={() => setInputValue(inputValue+1)}>Total Amount To Be Paid</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.