Home > database >  How to get button's value onclick and write out in React?
How to get button's value onclick and write out in React?

Time:12-31

Imagine a calculator screen. I can write out button's value once, but not many times. I want that if I click the button many times, write out the value so many times.

import { useState } from "react";

function App() {
  const [data, setData] = useState({ number: "" });

  return (
    <>
      <h1>Calculator screen: {data.number}!</h1>

      <button
        type="button"
        value="1"
        onClick={(e) => setData({ ...data, number: e.target.value })}
      >
        1
      </button>
    </>
  );
}

export default App;

CodePudding user response:

The problem here is that you are overwriting your previous number with the same value, what you need is to concatenate the strings.

Do something like this:

onClick={(e) => setData({ ...data, number: `${data.number}${e.target.value}` })}

This concatenates the previous value with the new addition, causing the string to get "bigger".

  • Related