0

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>
  );
}

1 Answer 1

2

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
    });
  };
Sign up to request clarification or add additional context in comments.

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.