Grapes and Cheese
Grapes and Cheese

Reputation: 9

Passing data from an input button click?

I am new to React. I am just playing around with passing values around. I am confused what I am doing wrong with the button click. I want that to check the value from the input and to generate a random number. Here is my code:


export default function Random() {
  const [state, setState] = useState({
    start: "",
    final: ""
  });

  let handleClick = (e) => {
    setState({
      start: e.target.value,
      final: Math.floor(Math.random() * state.start) + 1
    });
  };

  return (
    <div>
      <h1>Randomizer based off your number</h1>
      <input onChange={handleClick} type="number" />
      <button onClick={handleClick}>Random number</button>
      <h4>{`You entered ${state.start} and the random number is ${state.final}`}</h4>
    </div>
  );
}

Upvotes: 0

Views: 1120

Answers (1)

Robert May
Robert May

Reputation: 819

The e referenced in e.target.value is referring to the event. This should work for your onChange handler, as the target of the event is the <input />. However, when clicking the button, the target of the event is the <button />. Therefore e.target.value will attempt to read the value of the button, rather than the value of the input.

If you want to read the value of the input, try using a ref:

export default function Random() {
  const input = useRef();
  const [state, setState] = useState({
    start: "",
    final: ""
  });

  let handleClick = () => {
    setState({
      start: input.current.value,
      final: Math.floor(Math.random() * state.start) + 1
    });
  };

  return (
    <div>
      <h1>Randomizer based off your number</h1>
      <input onChange={handleClick} type="number" ref={input} />
      <button onClick={handleClick}>Random number</button>
      <h4>{`You entered ${state.start} and the random number is ${state.final}`}</h4>
    </div>
  );
}

Or if you want the button to use a random number, try this:

let handleClick = (e) => {
    setState({
      start: e.target.value || Math.random(),
      final: Math.floor(Math.random() * state.start) + 1
    });
  };

Upvotes: 2

Related Questions